From 37c9765ab4cab757fa6f8cd37dc0e6c71cf5256b Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 12:14:53 +0200
Subject: [PATCH 1/7] Optimized Lexer_getObj 2x faster

---
 src/core/parser.js | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/core/parser.js b/src/core/parser.js
index b5a4b791a..a4dc3e4f0 100644
--- a/src/core/parser.js
+++ b/src/core/parser.js
@@ -755,19 +755,19 @@ var Lexer = (function LexerClosure() {
       // command
       var str = String.fromCharCode(ch);
       var knownCommands = this.knownCommands;
-      var knownCommandFound = knownCommands && (str in knownCommands);
+      var knownCommandFound = knownCommands && knownCommands[str] !== undefined;
       while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
         // stop if known command is found and next character does not make
         // the str a command
         var possibleCommand = str + String.fromCharCode(ch);
-        if (knownCommandFound && !(possibleCommand in knownCommands)) {
+        if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
           break;
         }
         if (str.length === 128) {
           error('Command token too long: ' + str.length);
         }
         str = possibleCommand;
-        knownCommandFound = knownCommands && (str in knownCommands);
+        knownCommandFound = knownCommands && knownCommands[str] !== undefined;
       }
       if (str === 'true') {
         return true;

From 0a51b1e616c95a838922240edad212441b998416 Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 12:16:15 +0200
Subject: [PATCH 2/7] utils.js optimization of isFOO methods

---
 src/shared/util.js | 18 ++++++++----------
 1 file changed, 8 insertions(+), 10 deletions(-)

diff --git a/src/shared/util.js b/src/shared/util.js
index 3aa2164f5..ae4d85d40 100644
--- a/src/shared/util.js
+++ b/src/shared/util.js
@@ -911,15 +911,15 @@ function isBool(v) {
 }
 
 function isInt(v) {
-  return typeof v == 'number' && ((v | 0) == v);
+  return typeof v === 'number' && ((v | 0) === v);
 }
 
 function isNum(v) {
-  return typeof v == 'number';
+  return typeof v === 'number';
 }
 
 function isString(v) {
-  return typeof v == 'string';
+  return typeof v === 'string';
 }
 
 function isNull(v) {
@@ -931,7 +931,7 @@ function isName(v) {
 }
 
 function isCmd(v, cmd) {
-  return v instanceof Cmd && (!cmd || v.cmd == cmd);
+  return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
 }
 
 function isDict(v, type) {
@@ -942,7 +942,7 @@ function isDict(v, type) {
     return true;
   }
   var dictType = v.get('Type');
-  return isName(dictType) && dictType.name == type;
+  return isName(dictType) && dictType.name === type;
 }
 
 function isArray(v) {
@@ -950,13 +950,11 @@ function isArray(v) {
 }
 
 function isStream(v) {
-  return typeof v == 'object' && v !== null && v !== undefined &&
-         ('getBytes' in v);
+  return typeof v === 'object' && v !== null && v.getBytes !== undefined;
 }
 
 function isArrayBuffer(v) {
-  return typeof v == 'object' && v !== null && v !== undefined &&
-         ('byteLength' in v);
+  return typeof v === 'object' && v !== null && v.byteLength !== undefined;
 }
 
 function isRef(v) {
@@ -1298,7 +1296,7 @@ PDFJS.createPromiseCapability = createPromiseCapability;
       HandlerManager.scheduleHandlers(this);
       return nextPromise;
     },
-    
+
     catch: function Promise_catch(onReject) {
       return this.then(undefined, onReject);
     }

From d4a01f603429d255c0b1c294f8edbe5be2fd2800 Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 12:43:20 +0200
Subject: [PATCH 3/7] evaluator.js minor optimizations

---
 src/core/evaluator.js | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/src/core/evaluator.js b/src/core/evaluator.js
index ccfa138e9..c6ca1c3e8 100644
--- a/src/core/evaluator.js
+++ b/src/core/evaluator.js
@@ -569,11 +569,11 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
         var dict = (isStream(pattern) ? pattern.dict : pattern);
         var typeNum = dict.get('PatternType');
 
-        if (typeNum == TILING_PATTERN) {
+        if (typeNum === TILING_PATTERN) {
           var color = cs.base ? cs.base.getRgb(args, 0) : null;
           return this.handleTilingType(fn, color, resources, pattern,
                                        dict, operatorList);
-        } else if (typeNum == SHADING_PATTERN) {
+        } else if (typeNum === SHADING_PATTERN) {
           var shading = dict.get('Shading');
           var matrix = dict.get('Matrix');
           pattern = Pattern.parseShading(shading, matrix, xref, resources);
@@ -947,7 +947,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
           }
 
           var glyphUnicode = glyph.unicode;
-          if (glyphUnicode in NormalizedUnicodes) {
+          if (NormalizedUnicodes[glyphUnicode] !== undefined) {
             glyphUnicode = NormalizedUnicodes[glyphUnicode];
           }
           glyphUnicode = reverseIfRtl(glyphUnicode);
@@ -1479,7 +1479,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
 
       var composite = false;
       var uint8array;
-      if (type.name == 'Type0') {
+      if (type.name === 'Type0') {
         // If font is a composite
         //  - get the descendant font
         //  - set the type according to the descendant font
@@ -1545,7 +1545,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
       var properties;
 
       if (!descriptor) {
-        if (type.name == 'Type3') {
+        if (type.name === 'Type3') {
           // FontDescriptor is only required for Type3 fonts when the document
           // is a tagged pdf. Create a barbebones one to get by.
           descriptor = new Dict(null);
@@ -2074,7 +2074,7 @@ var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
         }
         if (!isCmd(obj)) {
           // argument
-          if (obj !== null && obj !== undefined) {
+          if (obj != null) {
             args.push((obj instanceof Dict ? obj.getAll() : obj));
             assert(args.length <= 33, 'Too many arguments');
           }
@@ -2165,9 +2165,9 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
     // have been found at index.
     for (var i = 0; i < count; i++) {
       var arg = argsArray[index + 4 * i + 2];
-      var imageMask = arg.length == 1 && arg[0];
-      if (imageMask && imageMask.width == 1 && imageMask.height == 1 &&
-          (!imageMask.data.length || (imageMask.data.length == 1 &&
+      var imageMask = arg.length === 1 && arg[0];
+      if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
+          (!imageMask.data.length || (imageMask.data.length === 1 &&
                                       imageMask.data[0] === 0))) {
         fnArray[index + 4 * i + 2] = OPS.paintSolidColorImageMask;
         continue;

From 35e418c603e5307bab705fc526ba9caebced43ba Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 14:40:33 +0200
Subject: [PATCH 4/7] Optimized CanvasGraphics_executeOperatorList 66% faster

---
 src/display/canvas.js | 33 +++++++++++++++++++--------------
 1 file changed, 19 insertions(+), 14 deletions(-)

diff --git a/src/display/canvas.js b/src/display/canvas.js
index 22b027530..34b877aa9 100644
--- a/src/display/canvas.js
+++ b/src/display/canvas.js
@@ -394,6 +394,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
   // Defines the time the executeOperatorList is going to be executing
   // before it stops and shedules a continue of execution.
   var EXECUTION_TIME = 15;
+  // Defines the number of steps before checking the execution time
+  var EXECUTION_STEPS = 10;
 
   function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
     this.ctx = canvasCtx;
@@ -726,18 +728,21 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
       var argsArrayLen = argsArray.length;
 
       // Sometimes the OperatorList to execute is empty.
-      if (argsArrayLen == i) {
+      if (argsArrayLen === i) {
         return i;
       }
 
-      var endTime = Date.now() + EXECUTION_TIME;
+      var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
+                             typeof continueCallback === 'function');
+      var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
+      var steps = 0;
 
       var commonObjs = this.commonObjs;
       var objs = this.objs;
       var fnId;
 
       while (true) {
-        if (stepper && i === stepper.nextBreakPoint) {
+        if (stepper !== undefined && i === stepper.nextBreakPoint) {
           stepper.breakIt(i, continueCallback);
           return i;
         }
@@ -750,16 +755,13 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
           var deps = argsArray[i];
           for (var n = 0, nn = deps.length; n < nn; n++) {
             var depObjId = deps[n];
-            var common = depObjId.substring(0, 2) == 'g_';
+            var common = depObjId[0] === 'g' && depObjId[1] === '_';
+            var objsPool = common ? commonObjs : objs;
 
             // If the promise isn't resolved yet, add the continueCallback
             // to the promise and bail out.
-            if (!common && !objs.isResolved(depObjId)) {
-              objs.get(depObjId, continueCallback);
-              return i;
-            }
-            if (common && !commonObjs.isResolved(depObjId)) {
-              commonObjs.get(depObjId, continueCallback);
+            if (!objsPool.isResolved(depObjId)) {
+              objsPool.get(depObjId, continueCallback);
               return i;
             }
           }
@@ -768,15 +770,18 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
         i++;
 
         // If the entire operatorList was executed, stop as were done.
-        if (i == argsArrayLen) {
+        if (i === argsArrayLen) {
           return i;
         }
 
         // If the execution took longer then a certain amount of time and
         // `continueCallback` is specified, interrupt the execution.
-        if (continueCallback && Date.now() > endTime) {
-          continueCallback();
-          return i;
+        if (chunkOperations && ++steps > EXECUTION_STEPS) {
+          if (Date.now() > endTime) {
+            continueCallback();
+            return i;
+          }
+          steps = 0;
         }
 
         // If the operatorList isn't executed completely yet OR the execution

From 412febe4a41e4f80c9be085b63349264e2a40ab1 Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 14:46:59 +0200
Subject: [PATCH 5/7] canvas.js minor optimizations

---
 src/display/canvas.js | 21 +++++++++------------
 1 file changed, 9 insertions(+), 12 deletions(-)

diff --git a/src/display/canvas.js b/src/display/canvas.js
index 34b877aa9..ad0503485 100644
--- a/src/display/canvas.js
+++ b/src/display/canvas.js
@@ -940,18 +940,15 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
       var old = this.current;
       this.stateStack.push(old);
       this.current = old.clone();
-      if (this.current.activeSMask) {
-        this.current.activeSMask = null;
-      }
+      this.current.activeSMask = null;
     },
     restore: function CanvasGraphics_restore() {
-      var prev = this.stateStack.pop();
-      if (prev) {
-        if (this.current.activeSMask) {
+      if (this.stateStack.length !== 0) {
+        if (this.current.activeSMask !== null) {
           this.endSMaskGroup();
         }
 
-        this.current = prev;
+        this.current = this.stateStack.pop();
         this.ctx.restore();
       }
     },
@@ -1507,7 +1504,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
     // Color
     getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
       var pattern;
-      if (IR[0] == 'TilingPattern') {
+      if (IR[0] === 'TilingPattern') {
         var color = IR[1];
         pattern = new TilingPattern(IR, color, this.ctx, this.objs,
                                     this.commonObjs, this.baseTransform);
@@ -1583,13 +1580,13 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
       this.save();
       this.baseTransformStack.push(this.baseTransform);
 
-      if (matrix && isArray(matrix) && 6 == matrix.length) {
+      if (isArray(matrix) && 6 === matrix.length) {
         this.transform.apply(this, matrix);
       }
 
       this.baseTransform = this.ctx.mozCurrentTransform;
 
-      if (bbox && isArray(bbox) && 4 == bbox.length) {
+      if (isArray(bbox) && 4 === bbox.length) {
         var width = bbox[2] - bbox[0];
         var height = bbox[3] - bbox[1];
         this.rectangle(bbox[0], bbox[1], width, height);
@@ -1741,7 +1738,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
                                                              matrix) {
       this.save();
 
-      if (rect && isArray(rect) && 4 == rect.length) {
+      if (isArray(rect) && 4 === rect.length) {
         var width = rect[2] - rect[0];
         var height = rect[3] - rect[1];
         this.rectangle(rect[0], rect[1], width, height);
@@ -2059,7 +2056,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
     consumePath: function CanvasGraphics_consumePath() {
       var ctx = this.ctx;
       if (this.pendingClip) {
-        if (this.pendingClip == EO_CLIP) {
+        if (this.pendingClip === EO_CLIP) {
           if (ctx.mozFillRule !== undefined) {
             ctx.mozFillRule = 'evenodd';
             ctx.clip();

From e0bf7e215148148cc9287cfd3bc456427be0f06c Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 14:54:40 +0200
Subject: [PATCH 6/7] Optimized genericComposeSMask

Declaring the composition and backgdrop functions outside of genericComposeSMask
is more efficient.
---
 src/display/canvas.js | 83 +++++++++++++++++++++++--------------------
 1 file changed, 45 insertions(+), 38 deletions(-)

diff --git a/src/display/canvas.js b/src/display/canvas.js
index ad0503485..a39601142 100644
--- a/src/display/canvas.js
+++ b/src/display/canvas.js
@@ -601,49 +601,54 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
     }
   }
 
+  function composeSMaskBackdrop(bytes, r0, g0, b0) {
+    var length = bytes.length;
+    for (var i = 3; i < length; i += 4) {
+      var alpha = bytes[i];
+      if (alpha === 0) {
+        bytes[i - 3] = r0;
+        bytes[i - 2] = g0;
+        bytes[i - 1] = b0;
+      } else if (alpha < 255) {
+        var alpha_ = 255 - alpha;
+        bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
+        bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
+        bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
+      }
+    }
+  }
+
+  function composeSMaskAlpha(maskData, layerData) {
+    var length = maskData.length;
+    var scale = 1 / 255;
+    for (var i = 3; i < length; i += 4) {
+      var alpha = maskData[i];
+      layerData[i] = (layerData[i] * alpha * scale) | 0;
+    }
+  }
+
+  function composeSMaskLuminosity(maskData, layerData) {
+    var length = maskData.length;
+    for (var i = 3; i < length; i += 4) {
+      var y = ((maskData[i - 3] * 77) +     // * 0.3 / 255 * 0x10000
+               (maskData[i - 2] * 152) +    // * 0.59 ....
+               (maskData[i - 1] * 28)) | 0; // * 0.11 ....
+      layerData[i] = (layerData[i] * y) >> 16;
+    }
+  }
+
   function genericComposeSMask(maskCtx, layerCtx, width, height,
                                subtype, backdrop) {
-    var addBackdropFn;
-    if (backdrop) {
-      addBackdropFn = function (r0, g0, b0, bytes) {
-        var length = bytes.length;
-        for (var i = 3; i < length; i += 4) {
-          var alpha = bytes[i] / 255;
-          if (alpha === 0) {
-            bytes[i - 3] = r0;
-            bytes[i - 2] = g0;
-            bytes[i - 1] = b0;
-          } else if (alpha < 1) {
-            var alpha_ = 1 - alpha;
-            bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) | 0;
-            bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) | 0;
-            bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) | 0;
-          }
-        }
-      }.bind(null, backdrop[0], backdrop[1], backdrop[2]);
-    } else {
-      addBackdropFn = function () {};
-    }
+    var hasBackdrop = backdrop !== undefined;
+    var r0 = hasBackdrop ? backdrop[0] : 0;
+    var g0 = hasBackdrop ? backdrop[1] : 0;
+    var b0 = hasBackdrop ? backdrop[2] : 0;
 
     var composeFn;
     if (subtype === 'Luminosity') {
-      composeFn = function (maskDataBytes, layerDataBytes) {
-        var length = maskDataBytes.length;
-        for (var i = 3; i < length; i += 4) {
-          var y = ((maskDataBytes[i - 3] * 77) +     // * 0.3 / 255 * 0x10000
-                   (maskDataBytes[i - 2] * 152) +    // * 0.59 ....
-                   (maskDataBytes[i - 1] * 28)) | 0; // * 0.11 ....
-          layerDataBytes[i] = (layerDataBytes[i] * y) >> 16;
-        }
-      };
+      composeFn = composeSMaskLuminosity;
     } else {
-      composeFn = function (maskDataBytes, layerDataBytes) {
-        var length = maskDataBytes.length;
-        for (var i = 3; i < length; i += 4) {
-          var alpha = maskDataBytes[i];
-          layerDataBytes[i] = (layerDataBytes[i] * alpha / 255) | 0;
-        }
-      };
+      composeFn = composeSMaskAlpha;
     }
 
     // processing image in chunks to save memory
@@ -654,7 +659,9 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
       var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
       var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
 
-      addBackdropFn(maskData.data);
+      if (hasBackdrop) {
+        composeSMaskBackdrop(maskData.data, r0, g0, b0);
+      }
       composeFn(maskData.data, layerData.data);
 
       maskCtx.putImageData(layerData, 0, row);

From 6731de6829d1ea7a1c627f736d993cd4c8283782 Mon Sep 17 00:00:00 2001
From: p01 <p01@opera.com>
Date: Mon, 2 Jun 2014 14:58:16 +0200
Subject: [PATCH 7/7] Minor refactoring of EvaluatorPreprocessor_read

---
 src/core/evaluator.js | 41 ++++++++++++++++++-----------------------
 1 file changed, 18 insertions(+), 23 deletions(-)

diff --git a/src/core/evaluator.js b/src/core/evaluator.js
index c6ca1c3e8..15b6a1f58 100644
--- a/src/core/evaluator.js
+++ b/src/core/evaluator.js
@@ -2074,7 +2074,7 @@ var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
         }
         if (!isCmd(obj)) {
           // argument
-          if (obj != null) {
+          if (obj !== null) {
             args.push((obj instanceof Dict ? obj.getAll() : obj));
             assert(args.length <= 33, 'Too many arguments');
           }
@@ -2090,37 +2090,32 @@ var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
         }
 
         var fn = opSpec.id;
-
-        // Some post script commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
-        if (!opSpec.variableArgs && args.length !== opSpec.numArgs) {
-          while (args.length > opSpec.numArgs) {
-            this.nonProcessedArgs.push(args.shift());
-          }
-
-          while (args.length < opSpec.numArgs && this.nonProcessedArgs.length) {
-            args.unshift(this.nonProcessedArgs.pop());
+        var numArgs = opSpec.numArgs;
+
+        if (!opSpec.variableArgs) {
+          // Some post script commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
+          if (args.length !== numArgs) {
+            var nonProcessedArgs = this.nonProcessedArgs;
+            while (args.length > numArgs) {
+              nonProcessedArgs.push(args.shift());
+            }
+            while (args.length < numArgs && nonProcessedArgs.length !== 0) {
+              args.unshift(nonProcessedArgs.pop());
+            }
           }
-        }
 
-        // Validate the number of arguments for the command
-        if (opSpec.variableArgs) {
-          if (args.length > opSpec.numArgs) {
-            info('Command ' + fn + ': expected [0,' + opSpec.numArgs +
-                 '] args, but received ' + args.length + ' args');
-          }
-        } else {
-          if (args.length < opSpec.numArgs) {
+          if (args.length < numArgs) {
             // If we receive too few args, it's not possible to possible
             // to execute the command, so skip the command
             info('Command ' + fn + ': because expected ' +
-                 opSpec.numArgs + ' args, but received ' + args.length +
+                 numArgs + ' args, but received ' + args.length +
                  ' args; skipping');
             args = [];
             continue;
-          } else if (args.length > opSpec.numArgs) {
-            info('Command ' + fn + ': expected ' + opSpec.numArgs +
-                 ' args, but received ' + args.length + ' args');
           }
+        } else if (args.length > numArgs) {
+          info('Command ' + fn + ': expected [0,' + numArgs +
+               '] args, but received ' + args.length + ' args');
         }
 
         // TODO figure out how to type-check vararg functions