1
0
Fork 0
mirror of https://github.com/mozilla/pdf.js.git synced 2025-04-22 16:18:08 +02:00

Merge branch 'master' of git://github.com/mozilla/pdf.js into text-select

Conflicts:
	src/canvas.js
	web/viewer.js
This commit is contained in:
Artur Adib 2011-11-28 10:02:07 -05:00
commit 4cfc552163
28 changed files with 6828 additions and 131 deletions

View file

@ -59,15 +59,121 @@ function ScratchCanvas(width, height) {
return canvas;
}
function addContextCurrentTransform(ctx) {
// If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
if (!ctx.mozCurrentTransform) {
// Store the original context
ctx._originalSave = ctx.save;
ctx._originalRestore = ctx.restore;
ctx._originalRotate = ctx.rotate;
ctx._originalScale = ctx.scale;
ctx._originalTranslate = ctx.translate;
ctx._originalTransform = ctx.transform;
ctx._transformMatrix = [1, 0, 0, 1, 0, 0];
ctx._transformStack = [];
Object.defineProperty(ctx, 'mozCurrentTransform', {
get: function getCurrentTransform() {
return this._transformMatrix;
}
});
Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
get: function getCurrentTransformInverse() {
// Calculation done using WolframAlpha:
// http://www.wolframalpha.com/input/?
// i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
var m = this._transformMatrix;
var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
var ad_bc = a * d - b * c;
var bc_ad = b * c - a * d;
return [
d / ad_bc,
b / bc_ad,
c / bc_ad,
a / ad_bc,
(d * e - c * f) / bc_ad,
(b * e - a * f) / ad_bc
];
}
});
ctx.save = function ctxSave() {
var old = this._transformMatrix;
this._transformStack.push(old);
this._transformMatrix = old.slice(0, 6);
this._originalSave();
};
ctx.restore = function ctxRestore() {
var prev = this._transformStack.pop();
if (prev) {
this._transformMatrix = prev;
this._originalRestore();
}
};
ctx.translate = function ctxTranslate(x, y) {
var m = this._transformMatrix;
m[4] = m[0] * x + m[2] * y + m[4];
m[5] = m[1] * x + m[3] * y + m[5];
this._originalTranslate(x, y);
};
ctx.scale = function ctxScale(x, y) {
var m = this._transformMatrix;
m[0] = m[0] * x;
m[1] = m[1] * x;
m[2] = m[2] * y;
m[3] = m[3] * y;
this._originalScale(x, y);
};
ctx.transform = function ctxTransform(a, b, c, d, e, f) {
var m = this._transformMatrix;
this._transformMatrix = [
m[0] * a + m[2] * b,
m[1] * a + m[3] * b,
m[0] * c + m[2] * d,
m[1] * c + m[3] * d,
m[0] * e + m[2] * f + m[4],
m[1] * e + m[3] * f + m[5]
];
ctx._originalTransform(a, b, c, d, e, f);
};
ctx.rotate = function ctxRotate(angle) {
var cosValue = Math.cos(angle);
var sinValue = Math.sin(angle);
var m = this._transformMatrix;
this._transformMatrix = [
m[0] * cosValue + m[2] * sinValue,
m[1] * cosValue + m[3] * sinValue,
m[0] * (-sinValue) + m[2] * cosValue,
m[1] * (-sinValue) + m[3] * cosValue,
m[4],
m[5]
];
this._originalRotate(angle);
};
}
}
var CanvasGraphics = (function canvasGraphics() {
// Defines the time the executeIRQueue is going to be executing
// before it stops and shedules a continue of execution.
var kExecutionTime = 50;
// Number of IR commands to execute before checking
// if we execute longer then `kExecutionTime`.
var kExecutionTimeCheck = 500;
function constructor(canvasCtx, objs, textLayer) {
this.ctx = canvasCtx;
this.current = new CanvasExtraState();
@ -78,6 +184,9 @@ var CanvasGraphics = (function canvasGraphics() {
this.ScratchCanvas = ScratchCanvas;
this.objs = objs;
this.textLayer = textLayer;
if (canvasCtx) {
addContextCurrentTransform(canvasCtx);
}
}
var LINE_CAP_STYLES = ['butt', 'round', 'square'];
@ -119,31 +228,33 @@ var CanvasGraphics = (function canvasGraphics() {
var i = executionStartIdx || 0;
var argsArrayLen = argsArray.length;
// Sometimes the IRQueue to execute is empty.
if (argsArrayLen == i) {
return i;
}
var executionEndIdx;
var startTime = Date.now();
var objs = this.objs;
do {
executionEndIdx = Math.min(argsArrayLen, i + kExecutionTimeCheck);
while (true) {
if (fnArray[i] !== 'dependency') {
this[fnArray[i]].apply(this, argsArray[i]);
} else {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var depObjId = deps[n];
for (i; i < executionEndIdx; i++) {
if (fnArray[i] !== 'dependency') {
this[fnArray[i]].apply(this, argsArray[i]);
} else {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var depObjId = deps[n];
// If the promise isn't resolved yet, add the continueCallback
// to the promise and bail out.
if (!objs.isResolved(depObjId)) {
objs.get(depObjId, continueCallback);
return i;
}
// If the promise isn't resolved yet, add the continueCallback
// to the promise and bail out.
if (!objs.isResolved(depObjId)) {
objs.get(depObjId, continueCallback);
return i;
}
}
}
i++;
// If the entire IRQueue was executed, stop as were done.
if (i == argsArrayLen) {
@ -160,7 +271,7 @@ var CanvasGraphics = (function canvasGraphics() {
// If the IRQueue isn't executed completly yet OR the execution time
// was short enough, do another execution round.
} while (true);
}
},
endDrawing: function canvasGraphicsEndDrawing() {

View file

@ -24,7 +24,7 @@ var ColorSpace = (function colorSpaceColorSpace() {
constructor.parse = function colorSpaceParse(cs, xref, res) {
var IR = constructor.parseToIR(cs, xref, res);
if (IR instanceof SeparationCS)
if (IR instanceof AlternateCS)
return IR;
return constructor.fromIR(IR);
@ -50,11 +50,12 @@ var ColorSpace = (function colorSpaceColorSpace() {
var hiVal = IR[2];
var lookup = IR[3];
return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);
case 'SeparationCS':
var alt = IR[1];
var tintFnIR = IR[2];
case 'AlternateCS':
var numComps = IR[1];
var alt = IR[2];
var tintFnIR = IR[3];
return new SeparationCS(ColorSpace.fromIR(alt),
return new AlternateCS(numComps, ColorSpace.fromIR(alt),
PDFFunction.fromIR(tintFnIR));
default:
error('Unkown name ' + name);
@ -134,11 +135,17 @@ var ColorSpace = (function colorSpaceColorSpace() {
var lookup = xref.fetchIfRef(cs[3]);
return ['IndexedCS', baseIndexedCS, hiVal, lookup];
case 'Separation':
case 'DeviceN':
var name = cs[1];
var numComps = 1;
if (isName(name))
numComps = 1;
else if (isArray(name))
numComps = name.length;
var alt = ColorSpace.parseToIR(cs[2], xref, res);
var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
return ['SeparationCS', alt, tintFnIR];
return ['AlternateCS', numComps, alt, tintFnIR];
case 'Lab':
case 'DeviceN':
default:
error('unimplemented color space object "' + mode + '"');
}
@ -151,33 +158,45 @@ var ColorSpace = (function colorSpaceColorSpace() {
return constructor;
})();
var SeparationCS = (function separationCS() {
function constructor(base, tintFn) {
this.name = 'Separation';
this.numComps = 1;
this.defaultColor = [1];
/**
* Alternate color space handles both Separation and DeviceN color spaces. A
* Separation color space is actually just a DeviceN with one color component.
* Both color spaces use a tinting function to convert colors to a base color
* space.
*/
var AlternateCS = (function alternateCS() {
function constructor(numComps, base, tintFn) {
this.name = 'Alternate';
this.numComps = numComps;
this.defaultColor = [];
for (var i = 0; i < numComps; ++i)
this.defaultColor.push(1);
this.base = base;
this.tintFn = tintFn;
}
constructor.prototype = {
getRgb: function sepcs_getRgb(color) {
getRgb: function altcs_getRgb(color) {
var tinted = this.tintFn(color);
return this.base.getRgb(tinted);
},
getRgbBuffer: function sepcs_getRgbBuffer(input, bits) {
getRgbBuffer: function altcs_getRgbBuffer(input, bits) {
var tintFn = this.tintFn;
var base = this.base;
var scale = 1 / ((1 << bits) - 1);
var length = input.length;
var pos = 0;
var numComps = base.numComps;
var baseBuf = new Uint8Array(numComps * length);
var baseNumComps = base.numComps;
var baseBuf = new Uint8Array(baseNumComps * length);
var numComps = this.numComps;
var scaled = new Array(numComps);
for (var i = 0; i < length; ++i) {
var scaled = input[i] * scale;
var tinted = tintFn([scaled]);
for (var j = 0; j < numComps; ++j)
for (var i = 0; i < length; i += numComps) {
for (var z = 0; z < numComps; ++z)
scaled[z] = input[i + z] * scale;
var tinted = tintFn(scaled);
for (var j = 0; j < baseNumComps; ++j)
baseBuf[pos++] = 255 * tinted[j];
}
return base.getRgbBuffer(baseBuf, 8);

View file

@ -552,7 +552,7 @@ var PDFDoc = (function pdfDoc() {
switch (type) {
case 'JpegStream':
var IR = data[2];
new JpegImage(id, IR, this.objs);
new JpegImageLoader(id, IR, this.objs);
break;
case 'Font':
var name = data[2];

View file

@ -179,7 +179,7 @@ var PartialEvaluator = (function partialEvaluator() {
var w = dict.get('Width', 'W');
var h = dict.get('Height', 'H');
if (image instanceof JpegStream) {
if (image instanceof JpegStream && image.isNative) {
var objId = 'img_' + uniquePrefix + (++self.objIdCounter);
handler.send('obj', [objId, 'JpegStream', image.getIR()]);

View file

@ -20,6 +20,8 @@ var PDFFunction = (function pdfFunction() {
var array = [];
var codeSize = 0;
var codeBuf = 0;
// 32 is a valid bps so shifting won't work
var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);
var strBytes = str.getBytes((length * bps + 7) / 8);
var strIdx = 0;
@ -30,7 +32,7 @@ var PDFFunction = (function pdfFunction() {
codeSize += 8;
}
codeSize -= bps;
array.push(codeBuf >> codeSize);
array.push((codeBuf >> codeSize) * sampleMul);
codeBuf &= (1 << codeSize) - 1;
}
return array;
@ -76,6 +78,17 @@ var PDFFunction = (function pdfFunction() {
},
constructSampled: function pdfFunctionConstructSampled(str, dict) {
function toMultiArray(arr) {
var inputLength = arr.length;
var outputLength = arr.length / 2;
var out = new Array(outputLength);
var index = 0;
for (var i = 0; i < inputLength; i += 2) {
out[index] = [arr[i], arr[i + 1]];
++index;
}
return out;
}
var domain = dict.get('Domain');
var range = dict.get('Range');
@ -85,9 +98,8 @@ var PDFFunction = (function pdfFunction() {
var inputSize = domain.length / 2;
var outputSize = range.length / 2;
if (inputSize != 1)
error('No support for multi-variable inputs to functions: ' +
inputSize);
domain = toMultiArray(domain);
range = toMultiArray(range);
var size = dict.get('Size');
var bps = dict.get('BitsPerSample');
@ -105,15 +117,36 @@ var PDFFunction = (function pdfFunction() {
encode.push(size[i] - 1);
}
}
encode = toMultiArray(encode);
var decode = dict.get('Decode');
if (!decode)
decode = range;
else
decode = toMultiArray(decode);
// Precalc the multipliers
var inputMul = new Float64Array(inputSize);
for (var i = 0; i < inputSize; ++i) {
inputMul[i] = (encode[i][1] - encode[i][0]) /
(domain[i][1] - domain[i][0]);
}
var idxMul = new Int32Array(inputSize);
idxMul[0] = outputSize;
for (i = 1; i < inputSize; ++i) {
idxMul[i] = idxMul[i - 1] * size[i - 1];
}
var nSamples = outputSize;
for (i = 0; i < inputSize; ++i)
nSamples *= size[i];
var samples = this.getSampleArray(size, outputSize, bps, str);
return [
CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,
outputSize, bps, range
outputSize, bps, range, inputMul, idxMul, nSamples
];
},
@ -127,64 +160,74 @@ var PDFFunction = (function pdfFunction() {
var outputSize = IR[7];
var bps = IR[8];
var range = IR[9];
var inputMul = IR[10];
var idxMul = IR[11];
var nSamples = IR[12];
return function constructSampledFromIRResult(args) {
var clip = function constructSampledFromIRClip(v, min, max) {
if (v > max)
v = max;
else if (v < min)
v = min;
return v;
};
if (inputSize != args.length)
error('Incorrect number of arguments: ' + inputSize + ' != ' +
args.length);
// Most of the below is a port of Poppler's implementation.
// TODO: There's a few other ways to do multilinear interpolation such
// as piecewise, which is much faster but an approximation.
var out = new Float64Array(outputSize);
var x;
var e = new Array(inputSize);
var efrac0 = new Float64Array(inputSize);
var efrac1 = new Float64Array(inputSize);
var sBuf = new Float64Array(1 << inputSize);
var i, j, k, idx, t;
for (var i = 0; i < inputSize; i++) {
var i2 = i * 2;
// clip to the domain
var v = clip(args[i], domain[i2], domain[i2 + 1]);
// encode
v = encode[i2] + ((v - domain[i2]) *
(encode[i2 + 1] - encode[i2]) /
(domain[i2 + 1] - domain[i2]));
// clip to the size
args[i] = clip(v, 0, size[i] - 1);
// map input values into sample array
for (i = 0; i < inputSize; ++i) {
x = (args[i] - domain[i][0]) * inputMul[i] + encode[i][0];
if (x < 0) {
x = 0;
} else if (x > size[i] - 1) {
x = size[i] - 1;
}
e[i] = [Math.floor(x), 0];
if ((e[i][1] = e[i][0] + 1) >= size[i]) {
// this happens if in[i] = domain[i][1]
e[i][1] = e[i][0];
}
efrac1[i] = x - e[i][0];
efrac0[i] = 1 - efrac1[i];
}
// interpolate to table
TODO('Multi-dimensional interpolation');
var floor = Math.floor(args[0]);
var ceil = Math.ceil(args[0]);
var scale = args[0] - floor;
// for each output, do m-linear interpolation
for (i = 0; i < outputSize; ++i) {
floor *= outputSize;
ceil *= outputSize;
var output = [], v = 0;
for (var i = 0; i < outputSize; ++i) {
if (ceil == floor) {
v = samples[ceil + i];
} else {
var low = samples[floor + i];
var high = samples[ceil + i];
v = low * scale + high * (1 - scale);
// pull 2^m values out of the sample array
for (j = 0; j < (1 << inputSize); ++j) {
idx = i;
for (k = 0, t = j; k < inputSize; ++k, t >>= 1) {
idx += idxMul[k] * (e[k][t & 1]);
}
if (idx >= 0 && idx < nSamples) {
sBuf[j] = samples[idx];
} else {
sBuf[j] = 0; // TODO Investigate if this is what Adobe does
}
}
var i2 = i * 2;
// decode
v = decode[i2] + (v * (decode[i2 + 1] - decode[i2]) /
((1 << bps) - 1));
// do m sets of interpolations
for (j = 0, t = (1 << inputSize); j < inputSize; ++j, t >>= 1) {
for (k = 0; k < t; k += 2) {
sBuf[k >> 1] = efrac0[j] * sBuf[k] + efrac1[j] * sBuf[k + 1];
}
}
// clip to the domain
output.push(clip(v, range[i2], range[i2 + 1]));
// map output value to range
out[i] = (sBuf[0] * (decode[i][1] - decode[i][0]) + decode[i][0]);
if (out[i] < range[i][0]) {
out[i] = range[i][0];
} else if (out[i] > range[i][1]) {
out[i] = range[i][1];
}
}
return output;
return out;
}
},

View file

@ -229,12 +229,12 @@ var PDFImage = (function pdfImage() {
return constructor;
})();
var JpegImage = (function jpegImage() {
function JpegImage(objId, imageData, objs) {
var JpegImageLoader = (function jpegImage() {
function JpegImageLoader(objId, imageData, objs) {
var src = 'data:image/jpeg;base64,' + window.btoa(imageData);
var img = new Image();
img.onload = (function jpegImageOnload() {
img.onload = (function jpegImageLoaderOnload() {
this.loaded = true;
objs.resolve(objId, this);
@ -246,12 +246,12 @@ var JpegImage = (function jpegImage() {
this.domImage = img;
}
JpegImage.prototype = {
getImage: function jpegImageGetImage() {
JpegImageLoader.prototype = {
getImage: function jpegImageLoaderGetImage() {
return this.domImage;
}
};
return JpegImage;
return JpegImageLoader;
})();

View file

@ -236,7 +236,7 @@ var Parser = (function parserParser() {
return new LZWStream(stream, earlyChange);
} else if (name == 'DCTDecode' || name == 'DCT') {
var bytes = stream.getBytes(length);
return new JpegStream(bytes, stream.dict);
return new JpegStream(bytes, stream.dict, this.xref);
} else if (name == 'ASCII85Decode' || name == 'A85') {
return new Ascii85Stream(stream);
} else if (name == 'ASCIIHexDecode' || name == 'AHx') {

View file

@ -756,8 +756,13 @@ var PredictorStream = (function predictorStream() {
return constructor;
})();
// A JpegStream can't be read directly. We use the platform to render
// the underlying JPEG data for us.
/**
* Depending on the type of JPEG a JpegStream is handled in different ways. For
* JPEG's that are supported natively such as DeviceGray and DeviceRGB the image
* data is stored and then loaded by the browser. For unsupported JPEG's we use
* a library to decode these images and the stream behaves like all the other
* DecodeStreams.
*/
var JpegStream = (function jpegStream() {
function isAdobeImage(bytes) {
var maxBytesScanned = Math.max(bytes.length - 16, 1024);
@ -789,24 +794,56 @@ var JpegStream = (function jpegStream() {
return newBytes;
}
function constructor(bytes, dict) {
function constructor(bytes, dict, xref) {
// TODO: per poppler, some images may have 'junk' before that
// need to be removed
this.dict = dict;
if (isAdobeImage(bytes))
bytes = fixAdobeImage(bytes);
// Flag indicating wether the image can be natively loaded.
this.isNative = true;
this.src = bytesToString(bytes);
this.colorTransform = -1;
if (isAdobeImage(bytes)) {
// when bug 674619 land, let's check if browser can do
// normal cmyk and then we won't have to the following
var cs = xref.fetchIfRef(dict.get('ColorSpace'));
// DeviceRGB and DeviceGray are the only Adobe images that work natively
if (isName(cs) && (cs.name === 'DeviceRGB' || cs.name === 'DeviceGray')) {
bytes = fixAdobeImage(bytes);
this.src = bytesToString(bytes);
} else {
this.colorTransform = dict.get('ColorTransform');
this.isNative = false;
this.bytes = bytes;
}
} else {
this.src = bytesToString(bytes);
}
DecodeStream.call(this);
}
constructor.prototype = {
getIR: function jpegStreamGetIR() {
return this.src;
},
getChar: function jpegStreamGetChar() {
constructor.prototype = Object.create(DecodeStream.prototype);
constructor.prototype.ensureBuffer = function jpegStreamEnsureBuffer(req) {
if (this.bufferLength)
return;
var jpegImage = new JpegImage();
jpegImage.colorTransform = this.colorTransform;
jpegImage.parse(this.bytes);
var width = jpegImage.width;
var height = jpegImage.height;
var data = jpegImage.getData(width, height);
this.buffer = data;
this.bufferLength = data.length;
};
constructor.prototype.getIR = function jpegStreamGetIR() {
return this.src;
};
constructor.prototype.getChar = function jpegStreamGetChar() {
error('internal error: getChar is not valid on JpegStream');
}
};
return constructor;

View file

@ -40,7 +40,8 @@ function onMessageLoader(evt) {
'parser.js',
'pattern.js',
'stream.js',
'worker.js'
'worker.js',
'../external/jpgjs/jpg.js'
];
// Load all the files.