annotation.js 33.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define('pdfjs/core/annotation', ['exports', 'pdfjs/shared/util',
      'pdfjs/core/primitives', 'pdfjs/core/stream', 'pdfjs/core/colorspace',
      'pdfjs/core/obj', 'pdfjs/core/evaluator'], factory);
  } else if (typeof exports !== 'undefined') {
    factory(exports, require('../shared/util.js'), require('./primitives.js'),
      require('./stream.js'), require('./colorspace.js'), require('./obj.js'),
      require('./evaluator.js'));
  } else {
    factory((root.pdfjsCoreAnnotation = {}), root.pdfjsSharedUtil,
      root.pdfjsCorePrimitives, root.pdfjsCoreStream, root.pdfjsCoreColorSpace,
      root.pdfjsCoreObj, root.pdfjsCoreEvaluator);
  }
}(this, function (exports, sharedUtil, corePrimitives, coreStream,
                  coreColorSpace, coreObj, coreEvaluator) {

var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
var AnnotationFieldFlag = sharedUtil.AnnotationFieldFlag;
var AnnotationFlag = sharedUtil.AnnotationFlag;
var AnnotationType = sharedUtil.AnnotationType;
var OPS = sharedUtil.OPS;
var Util = sharedUtil.Util;
var isString = sharedUtil.isString;
var isArray = sharedUtil.isArray;
var isInt = sharedUtil.isInt;
var stringToBytes = sharedUtil.stringToBytes;
var stringToPDFString = sharedUtil.stringToPDFString;
var warn = sharedUtil.warn;
var Dict = corePrimitives.Dict;
var isDict = corePrimitives.isDict;
var isName = corePrimitives.isName;
var isRef = corePrimitives.isRef;
var Stream = coreStream.Stream;
var ColorSpace = coreColorSpace.ColorSpace;
var Catalog = coreObj.Catalog;
var ObjectLoader = coreObj.ObjectLoader;
var FileSpec = coreObj.FileSpec;
var OperatorList = coreEvaluator.OperatorList;

/**
 * @class
 * @alias AnnotationFactory
 */
function AnnotationFactory() {}
AnnotationFactory.prototype = /** @lends AnnotationFactory.prototype */ {
  /**
   * @param {XRef} xref
   * @param {Object} ref
   * @param {PDFManager} pdfManager
   * @param {string} uniquePrefix
   * @param {Object} idCounters
   * @returns {Annotation}
   */
  create: function AnnotationFactory_create(xref, ref, pdfManager,
                                            uniquePrefix, idCounters) {
    var dict = xref.fetchIfRef(ref);
    if (!isDict(dict)) {
      return;
    }
    var id = isRef(ref) ? ref.toString() :
                          'annot_' + (uniquePrefix || '') + (++idCounters.obj);

    // Determine the annotation's subtype.
    var subtype = dict.get('Subtype');
    subtype = isName(subtype) ? subtype.name : null;

    // Return the right annotation object based on the subtype and field type.
    var parameters = {
      xref: xref,
      dict: dict,
      ref: isRef(ref) ? ref : null,
      subtype: subtype,
      id: id,
      pdfManager: pdfManager,
    };

    switch (subtype) {
      case 'Link':
        return new LinkAnnotation(parameters);

      case 'Text':
        return new TextAnnotation(parameters);

      case 'Widget':
        var fieldType = Util.getInheritableProperty(dict, 'FT');
        fieldType = isName(fieldType) ? fieldType.name : null;

        switch (fieldType) {
          case 'Tx':
            return new TextWidgetAnnotation(parameters);
          case 'Btn':
            return new ButtonWidgetAnnotation(parameters);
          case 'Ch':
            return new ChoiceWidgetAnnotation(parameters);
        }
        warn('Unimplemented widget field type "' + fieldType + '", ' +
             'falling back to base field type.');
        return new WidgetAnnotation(parameters);

      case 'Popup':
        return new PopupAnnotation(parameters);

      case 'Highlight':
        return new HighlightAnnotation(parameters);

      case 'Underline':
        return new UnderlineAnnotation(parameters);

      case 'Squiggly':
        return new SquigglyAnnotation(parameters);

      case 'StrikeOut':
        return new StrikeOutAnnotation(parameters);

      case 'FileAttachment':
        return new FileAttachmentAnnotation(parameters);

      default:
        if (!subtype) {
          warn('Annotation is missing the required /Subtype.');
        } else {
          warn('Unimplemented annotation type "' + subtype + '", ' +
               'falling back to base annotation.');
        }
        return new Annotation(parameters);
    }
  }
};

var Annotation = (function AnnotationClosure() {
  // 12.5.5: Algorithm: Appearance streams
  function getTransformMatrix(rect, bbox, matrix) {
    var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);
    var minX = bounds[0];
    var minY = bounds[1];
    var maxX = bounds[2];
    var maxY = bounds[3];

    if (minX === maxX || minY === maxY) {
      // From real-life file, bbox was [0, 0, 0, 0]. In this case,
      // just apply the transform for rect
      return [1, 0, 0, 1, rect[0], rect[1]];
    }

    var xRatio = (rect[2] - rect[0]) / (maxX - minX);
    var yRatio = (rect[3] - rect[1]) / (maxY - minY);
    return [
      xRatio,
      0,
      0,
      yRatio,
      rect[0] - minX * xRatio,
      rect[1] - minY * yRatio
    ];
  }

  function getDefaultAppearance(dict) {
    var appearanceState = dict.get('AP');
    if (!isDict(appearanceState)) {
      return;
    }

    var appearance;
    var appearances = appearanceState.get('N');
    if (isDict(appearances)) {
      var as = dict.get('AS');
      if (as && appearances.has(as.name)) {
        appearance = appearances.get(as.name);
      }
    } else {
      appearance = appearances;
    }
    return appearance;
  }

  function Annotation(params) {
    var dict = params.dict;

    this.setFlags(dict.get('F'));
    this.setRectangle(dict.getArray('Rect'));
    this.setColor(dict.getArray('C'));
    this.setBorderStyle(dict);
    this.appearance = getDefaultAppearance(dict);

    // Expose public properties using a data object.
    this.data = {};
    this.data.id = params.id;
    this.data.subtype = params.subtype;
    this.data.annotationFlags = this.flags;
    this.data.rect = this.rectangle;
    this.data.color = this.color;
    this.data.borderStyle = this.borderStyle;
    this.data.hasAppearance = !!this.appearance;
  }

  Annotation.prototype = {
    /**
     * @private
     */
    _hasFlag: function Annotation_hasFlag(flags, flag) {
      return !!(flags & flag);
    },

    /**
     * @private
     */
    _isViewable: function Annotation_isViewable(flags) {
      return !this._hasFlag(flags, AnnotationFlag.INVISIBLE) &&
             !this._hasFlag(flags, AnnotationFlag.HIDDEN) &&
             !this._hasFlag(flags, AnnotationFlag.NOVIEW);
    },

    /**
     * @private
     */
    _isPrintable: function AnnotationFlag_isPrintable(flags) {
      return this._hasFlag(flags, AnnotationFlag.PRINT) &&
             !this._hasFlag(flags, AnnotationFlag.INVISIBLE) &&
             !this._hasFlag(flags, AnnotationFlag.HIDDEN);
    },

    /**
     * @return {boolean}
     */
    get viewable() {
      if (this.flags === 0) {
        return true;
      }
      return this._isViewable(this.flags);
    },

    /**
     * @return {boolean}
     */
    get printable() {
      if (this.flags === 0) {
        return false;
      }
      return this._isPrintable(this.flags);
    },

    /**
     * Set the flags.
     *
     * @public
     * @memberof Annotation
     * @param {number} flags - Unsigned 32-bit integer specifying annotation
     *                         characteristics
     * @see {@link shared/util.js}
     */
    setFlags: function Annotation_setFlags(flags) {
      this.flags = (isInt(flags) && flags > 0) ? flags : 0;
    },

    /**
     * Check if a provided flag is set.
     *
     * @public
     * @memberof Annotation
     * @param {number} flag - Hexadecimal representation for an annotation
     *                        characteristic
     * @return {boolean}
     * @see {@link shared/util.js}
     */
    hasFlag: function Annotation_hasFlag(flag) {
      return this._hasFlag(this.flags, flag);
    },

    /**
     * Set the rectangle.
     *
     * @public
     * @memberof Annotation
     * @param {Array} rectangle - The rectangle array with exactly four entries
     */
    setRectangle: function Annotation_setRectangle(rectangle) {
      if (isArray(rectangle) && rectangle.length === 4) {
        this.rectangle = Util.normalizeRect(rectangle);
      } else {
        this.rectangle = [0, 0, 0, 0];
      }
    },

    /**
     * Set the color and take care of color space conversion.
     *
     * @public
     * @memberof Annotation
     * @param {Array} color - The color array containing either 0
     *                        (transparent), 1 (grayscale), 3 (RGB) or
     *                        4 (CMYK) elements
     */
    setColor: function Annotation_setColor(color) {
      var rgbColor = new Uint8Array(3); // Black in RGB color space (default)
      if (!isArray(color)) {
        this.color = rgbColor;
        return;
      }

      switch (color.length) {
        case 0: // Transparent, which we indicate with a null value
          this.color = null;
          break;

        case 1: // Convert grayscale to RGB
          ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
          this.color = rgbColor;
          break;

        case 3: // Convert RGB percentages to RGB
          ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
          this.color = rgbColor;
          break;

        case 4: // Convert CMYK to RGB
          ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
          this.color = rgbColor;
          break;

        default:
          this.color = rgbColor;
          break;
      }
    },

    /**
     * Set the border style (as AnnotationBorderStyle object).
     *
     * @public
     * @memberof Annotation
     * @param {Dict} borderStyle - The border style dictionary
     */
    setBorderStyle: function Annotation_setBorderStyle(borderStyle) {
      this.borderStyle = new AnnotationBorderStyle();
      if (!isDict(borderStyle)) {
        return;
      }
      if (borderStyle.has('BS')) {
        var dict = borderStyle.get('BS');
        var dictType = dict.get('Type');

        if (!dictType || isName(dictType, 'Border')) {
          this.borderStyle.setWidth(dict.get('W'));
          this.borderStyle.setStyle(dict.get('S'));
          this.borderStyle.setDashArray(dict.getArray('D'));
        }
      } else if (borderStyle.has('Border')) {
        var array = borderStyle.getArray('Border');
        if (isArray(array) && array.length >= 3) {
          this.borderStyle.setHorizontalCornerRadius(array[0]);
          this.borderStyle.setVerticalCornerRadius(array[1]);
          this.borderStyle.setWidth(array[2]);

          if (array.length === 4) { // Dash array available
            this.borderStyle.setDashArray(array[3]);
          }
        }
      } else {
        // There are no border entries in the dictionary. According to the
        // specification, we should draw a solid border of width 1 in that
        // case, but Adobe Reader did not implement that part of the
        // specification and instead draws no border at all, so we do the same.
        // See also https://github.com/mozilla/pdf.js/issues/6179.
        this.borderStyle.setWidth(0);
      }
    },

    /**
     * Prepare the annotation for working with a popup in the display layer.
     *
     * @private
     * @memberof Annotation
     * @param {Dict} dict - The annotation's data dictionary
     */
    _preparePopup: function Annotation_preparePopup(dict) {
      if (!dict.has('C')) {
        // Fall back to the default background color.
        this.data.color = null;
      }

      this.data.hasPopup = dict.has('Popup');
      this.data.title = stringToPDFString(dict.get('T') || '');
      this.data.contents = stringToPDFString(dict.get('Contents') || '');
    },

    loadResources: function Annotation_loadResources(keys) {
      return new Promise(function (resolve, reject) {
        this.appearance.dict.getAsync('Resources').then(function (resources) {
          if (!resources) {
            resolve();
            return;
          }
          var objectLoader = new ObjectLoader(resources.map,
                                              keys,
                                              resources.xref);
          objectLoader.load().then(function() {
            resolve(resources);
          }, reject);
        }, reject);
      }.bind(this));
    },

    getOperatorList: function Annotation_getOperatorList(evaluator, task,
                                                         renderForms) {
      if (!this.appearance) {
        return Promise.resolve(new OperatorList());
      }

      var data = this.data;
      var appearanceDict = this.appearance.dict;
      var resourcesPromise = this.loadResources([
        'ExtGState',
        'ColorSpace',
        'Pattern',
        'Shading',
        'XObject',
        'Font'
        // ProcSet
        // Properties
      ]);
      var bbox = appearanceDict.getArray('BBox') || [0, 0, 1, 1];
      var matrix = appearanceDict.getArray('Matrix') || [1, 0, 0, 1, 0, 0];
      var transform = getTransformMatrix(data.rect, bbox, matrix);
      var self = this;

      return resourcesPromise.then(function(resources) {
          var opList = new OperatorList();
          opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);
          return evaluator.getOperatorList(self.appearance, task,
                                           resources, opList).
            then(function () {
              opList.addOp(OPS.endAnnotation, []);
              self.appearance.reset();
              return opList;
            });
        });
    }
  };

  Annotation.appendToOperatorList = function Annotation_appendToOperatorList(
      annotations, opList, partialEvaluator, task, intent, renderForms) {
    var annotationPromises = [];
    for (var i = 0, n = annotations.length; i < n; ++i) {
      if ((intent === 'display' && annotations[i].viewable) ||
          (intent === 'print' && annotations[i].printable)) {
        annotationPromises.push(
          annotations[i].getOperatorList(partialEvaluator, task, renderForms));
      }
    }
    return Promise.all(annotationPromises).then(function(operatorLists) {
      opList.addOp(OPS.beginAnnotations, []);
      for (var i = 0, n = operatorLists.length; i < n; ++i) {
        opList.addOpList(operatorLists[i]);
      }
      opList.addOp(OPS.endAnnotations, []);
    });
  };

  return Annotation;
})();

/**
 * Contains all data regarding an annotation's border style.
 *
 * @class
 */
var AnnotationBorderStyle = (function AnnotationBorderStyleClosure() {
  /**
   * @constructor
   * @private
   */
  function AnnotationBorderStyle() {
    this.width = 1;
    this.style = AnnotationBorderStyleType.SOLID;
    this.dashArray = [3];
    this.horizontalCornerRadius = 0;
    this.verticalCornerRadius = 0;
  }

  AnnotationBorderStyle.prototype = {
    /**
     * Set the width.
     *
     * @public
     * @memberof AnnotationBorderStyle
     * @param {integer} width - The width
     */
    setWidth: function AnnotationBorderStyle_setWidth(width) {
      if (width === (width | 0)) {
        this.width = width;
      }
    },

    /**
     * Set the style.
     *
     * @public
     * @memberof AnnotationBorderStyle
     * @param {Object} style - The style object
     * @see {@link shared/util.js}
     */
    setStyle: function AnnotationBorderStyle_setStyle(style) {
      if (!style) {
        return;
      }
      switch (style.name) {
        case 'S':
          this.style = AnnotationBorderStyleType.SOLID;
          break;

        case 'D':
          this.style = AnnotationBorderStyleType.DASHED;
          break;

        case 'B':
          this.style = AnnotationBorderStyleType.BEVELED;
          break;

        case 'I':
          this.style = AnnotationBorderStyleType.INSET;
          break;

        case 'U':
          this.style = AnnotationBorderStyleType.UNDERLINE;
          break;

        default:
          break;
      }
    },

    /**
     * Set the dash array.
     *
     * @public
     * @memberof AnnotationBorderStyle
     * @param {Array} dashArray - The dash array with at least one element
     */
    setDashArray: function AnnotationBorderStyle_setDashArray(dashArray) {
      // We validate the dash array, but we do not use it because CSS does not
      // allow us to change spacing of dashes. For more information, visit
      // http://www.w3.org/TR/css3-background/#the-border-style.
      if (isArray(dashArray) && dashArray.length > 0) {
        // According to the PDF specification: the elements in a dashArray
        // shall be numbers that are nonnegative and not all equal to zero.
        var isValid = true;
        var allZeros = true;
        for (var i = 0, len = dashArray.length; i < len; i++) {
          var element = dashArray[i];
          var validNumber = (+element >= 0);
          if (!validNumber) {
            isValid = false;
            break;
          } else if (element > 0) {
            allZeros = false;
          }
        }
        if (isValid && !allZeros) {
          this.dashArray = dashArray;
        } else {
          this.width = 0; // Adobe behavior when the array is invalid.
        }
      } else if (dashArray) {
        this.width = 0; // Adobe behavior when the array is invalid.
      }
    },

    /**
     * Set the horizontal corner radius (from a Border dictionary).
     *
     * @public
     * @memberof AnnotationBorderStyle
     * @param {integer} radius - The horizontal corner radius
     */
    setHorizontalCornerRadius:
        function AnnotationBorderStyle_setHorizontalCornerRadius(radius) {
      if (radius === (radius | 0)) {
        this.horizontalCornerRadius = radius;
      }
    },

    /**
     * Set the vertical corner radius (from a Border dictionary).
     *
     * @public
     * @memberof AnnotationBorderStyle
     * @param {integer} radius - The vertical corner radius
     */
    setVerticalCornerRadius:
        function AnnotationBorderStyle_setVerticalCornerRadius(radius) {
      if (radius === (radius | 0)) {
        this.verticalCornerRadius = radius;
      }
    }
  };

  return AnnotationBorderStyle;
})();

var WidgetAnnotation = (function WidgetAnnotationClosure() {
  function WidgetAnnotation(params) {
    Annotation.call(this, params);

    var dict = params.dict;
    var data = this.data;

    data.annotationType = AnnotationType.WIDGET;
    data.fieldName = this._constructFieldName(dict);
    data.fieldValue = Util.getInheritableProperty(dict, 'V',
                                                  /* getArray = */ true);
    data.alternativeText = stringToPDFString(dict.get('TU') || '');
    data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';
    var fieldType = Util.getInheritableProperty(dict, 'FT');
    data.fieldType = isName(fieldType) ? fieldType.name : null;
    this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;

    data.fieldFlags = Util.getInheritableProperty(dict, 'Ff');
    if (!isInt(data.fieldFlags) || data.fieldFlags < 0) {
      data.fieldFlags = 0;
    }

    data.readOnly = this.hasFieldFlag(AnnotationFieldFlag.READONLY);

    // Hide signatures because we cannot validate them.
    if (data.fieldType === 'Sig') {
      this.setFlags(AnnotationFlag.HIDDEN);
    }
  }

  Util.inherit(WidgetAnnotation, Annotation, {
    /**
     * Construct the (fully qualified) field name from the (partial) field
     * names of the field and its ancestors.
     *
     * @private
     * @memberof WidgetAnnotation
     * @param {Dict} dict - Complete widget annotation dictionary
     * @return {string}
     */
    _constructFieldName: function WidgetAnnotation_constructFieldName(dict) {
      // Both the `Parent` and `T` fields are optional. While at least one of
      // them should be provided, bad PDF generators may fail to do so.
      if (!dict.has('T') && !dict.has('Parent')) {
        warn('Unknown field name, falling back to empty field name.');
        return '';
      }

      // If no parent exists, the partial and fully qualified names are equal.
      if (!dict.has('Parent')) {
        return stringToPDFString(dict.get('T'));
      }

      // Form the fully qualified field name by appending the partial name to
      // the parent's fully qualified name, separated by a period.
      var fieldName = [];
      if (dict.has('T')) {
        fieldName.unshift(stringToPDFString(dict.get('T')));
      }

      var loopDict = dict;
      while (loopDict.has('Parent')) {
        loopDict = loopDict.get('Parent');

        if (loopDict.has('T')) {
          fieldName.unshift(stringToPDFString(loopDict.get('T')));
        }
      }
      return fieldName.join('.');
    },

    /**
     * Check if a provided field flag is set.
     *
     * @public
     * @memberof WidgetAnnotation
     * @param {number} flag - Hexadecimal representation for an annotation
     *                        field characteristic
     * @return {boolean}
     * @see {@link shared/util.js}
     */
    hasFieldFlag: function WidgetAnnotation_hasFieldFlag(flag) {
      return !!(this.data.fieldFlags & flag);
    },
  });

  return WidgetAnnotation;
})();

var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {
  function TextWidgetAnnotation(params) {
    WidgetAnnotation.call(this, params);

    // The field value is always a string.
    this.data.fieldValue = stringToPDFString(this.data.fieldValue || '');

    // Determine the alignment of text in the field.
    var alignment = Util.getInheritableProperty(params.dict, 'Q');
    if (!isInt(alignment) || alignment < 0 || alignment > 2) {
      alignment = null;
    }
    this.data.textAlignment = alignment;

    // Determine the maximum length of text in the field.
    var maximumLength = Util.getInheritableProperty(params.dict, 'MaxLen');
    if (!isInt(maximumLength) || maximumLength < 0) {
      maximumLength = null;
    }
    this.data.maxLen = maximumLength;

    // Process field flags for the display layer.
    this.data.multiLine = this.hasFieldFlag(AnnotationFieldFlag.MULTILINE);
    this.data.comb = this.hasFieldFlag(AnnotationFieldFlag.COMB) &&
                     !this.hasFieldFlag(AnnotationFieldFlag.MULTILINE) &&
                     !this.hasFieldFlag(AnnotationFieldFlag.PASSWORD) &&
                     !this.hasFieldFlag(AnnotationFieldFlag.FILESELECT) &&
                     this.data.maxLen !== null;
  }

  Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
    getOperatorList:
        function TextWidgetAnnotation_getOperatorList(evaluator, task,
                                                      renderForms) {
      var operatorList = new OperatorList();

      // Do not render form elements on the canvas when interactive forms are
      // enabled. The display layer is responsible for rendering them instead.
      if (renderForms) {
        return Promise.resolve(operatorList);
      }

      if (this.appearance) {
        return Annotation.prototype.getOperatorList.call(this, evaluator, task,
                                                         renderForms);
      }

      // Even if there is an appearance stream, ignore it. This is the
      // behaviour used by Adobe Reader.
      if (!this.data.defaultAppearance) {
        return Promise.resolve(operatorList);
      }

      var stream = new Stream(stringToBytes(this.data.defaultAppearance));
      return evaluator.getOperatorList(stream, task, this.fieldResources,
                                       operatorList).
        then(function () {
          return operatorList;
        });
    }
  });

  return TextWidgetAnnotation;
})();

var ButtonWidgetAnnotation = (function ButtonWidgetAnnotationClosure() {
  function ButtonWidgetAnnotation(params) {
    WidgetAnnotation.call(this, params);

    this.data.checkBox = !this.hasFieldFlag(AnnotationFieldFlag.RADIO) &&
                         !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
    if (this.data.checkBox) {
      if (!isName(this.data.fieldValue)) {
        return;
      }
      this.data.fieldValue = this.data.fieldValue.name;
    }

    this.data.radioButton = this.hasFieldFlag(AnnotationFieldFlag.RADIO) &&
                            !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON);
    if (this.data.radioButton) {
      this.data.fieldValue = this.data.buttonValue = null;

      // The parent field's `V` entry holds a `Name` object with the appearance
      // state of whichever child field is currently in the "on" state.
      var fieldParent = params.dict.get('Parent');
      if (!isDict(fieldParent) || !fieldParent.has('V')) {
        return;
      }
      var fieldParentValue = fieldParent.get('V');
      if (!isName(fieldParentValue)) {
        return;
      }
      this.data.fieldValue = fieldParentValue.name;

      // The button's value corresponds to its appearance state.
      var appearanceStates = params.dict.get('AP');
      if (!isDict(appearanceStates)) {
        return;
      }
      var normalAppearanceState = appearanceStates.get('N');
      if (!isDict(normalAppearanceState)) {
        return;
      }
      var keys = normalAppearanceState.getKeys();
      for (var i = 0, ii = keys.length; i < ii; i++) {
        if (keys[i] !== 'Off') {
          this.data.buttonValue = keys[i];
          break;
        }
      }
    }
  }

  Util.inherit(ButtonWidgetAnnotation, WidgetAnnotation, {
    getOperatorList:
        function ButtonWidgetAnnotation_getOperatorList(evaluator, task,
                                                        renderForms) {
      var operatorList = new OperatorList();

      // Do not render form elements on the canvas when interactive forms are
      // enabled. The display layer is responsible for rendering them instead.
      if (renderForms) {
        return Promise.resolve(operatorList);
      }

      if (this.appearance) {
        return Annotation.prototype.getOperatorList.call(this, evaluator, task,
                                                         renderForms);
      }
      return Promise.resolve(operatorList);
    }
  });

  return ButtonWidgetAnnotation;
})();

var ChoiceWidgetAnnotation = (function ChoiceWidgetAnnotationClosure() {
  function ChoiceWidgetAnnotation(params) {
    WidgetAnnotation.call(this, params);

    // Determine the options. The options array may consist of strings or
    // arrays. If the array consists of arrays, then the first element of
    // each array is the export value and the second element of each array is
    // the display value. If the array consists of strings, then these
    // represent both the export and display value. In this case, we convert
    // it to an array of arrays as well for convenience in the display layer.
    this.data.options = [];

    var options = params.dict.get('Opt');
    if (isArray(options)) {
      var xref = params.xref;
      for (var i = 0, ii = options.length; i < ii; i++) {
        var option = xref.fetchIfRef(options[i]);
        var isOptionArray = isArray(option);

        this.data.options[i] = {
          exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option,
          displayValue: isOptionArray ? xref.fetchIfRef(option[1]) : option,
        };
      }
    }

    // Determine the field value. In this case, it may be a string or an
    // array of strings. For convenience in the display layer, convert the
    // string to an array of one string as well.
    if (!isArray(this.data.fieldValue)) {
      this.data.fieldValue = [this.data.fieldValue];
    }

    // Process field flags for the display layer.
    this.data.combo = this.hasFieldFlag(AnnotationFieldFlag.COMBO);
    this.data.multiSelect = this.hasFieldFlag(AnnotationFieldFlag.MULTISELECT);
  }

  Util.inherit(ChoiceWidgetAnnotation, WidgetAnnotation, {
    getOperatorList:
        function ChoiceWidgetAnnotation_getOperatorList(evaluator, task,
                                                        renderForms) {
      var operatorList = new OperatorList();

      // Do not render form elements on the canvas when interactive forms are
      // enabled. The display layer is responsible for rendering them instead.
      if (renderForms) {
        return Promise.resolve(operatorList);
      }

      return Annotation.prototype.getOperatorList.call(this, evaluator, task,
                                                       renderForms);
    }
  });

  return ChoiceWidgetAnnotation;
})();

var TextAnnotation = (function TextAnnotationClosure() {
  var DEFAULT_ICON_SIZE = 22; // px

  function TextAnnotation(parameters) {
    Annotation.call(this, parameters);

    this.data.annotationType = AnnotationType.TEXT;

    if (this.data.hasAppearance) {
      this.data.name = 'NoIcon';
    } else {
      this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
      this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
      this.data.name = parameters.dict.has('Name') ?
                       parameters.dict.get('Name').name : 'Note';
    }
    this._preparePopup(parameters.dict);
  }

  Util.inherit(TextAnnotation, Annotation, {});

  return TextAnnotation;
})();

var LinkAnnotation = (function LinkAnnotationClosure() {
  function LinkAnnotation(params) {
    Annotation.call(this, params);

    var data = this.data;
    data.annotationType = AnnotationType.LINK;

    Catalog.parseDestDictionary({
      destDict: params.dict,
      resultObj: data,
      docBaseUrl: params.pdfManager.docBaseUrl,
    });
  }

  Util.inherit(LinkAnnotation, Annotation, {});

  return LinkAnnotation;
})();

var PopupAnnotation = (function PopupAnnotationClosure() {
  function PopupAnnotation(parameters) {
    Annotation.call(this, parameters);

    this.data.annotationType = AnnotationType.POPUP;

    var dict = parameters.dict;
    var parentItem = dict.get('Parent');
    if (!parentItem) {
      warn('Popup annotation has a missing or invalid parent annotation.');
      return;
    }

    this.data.parentId = dict.getRaw('Parent').toString();
    this.data.title = stringToPDFString(parentItem.get('T') || '');
    this.data.contents = stringToPDFString(parentItem.get('Contents') || '');

    if (!parentItem.has('C')) {
      // Fall back to the default background color.
      this.data.color = null;
    } else {
      this.setColor(parentItem.getArray('C'));
      this.data.color = this.color;
    }

    // If the Popup annotation is not viewable, but the parent annotation is,
    // that is most likely a bug. Fallback to inherit the flags from the parent
    // annotation (this is consistent with the behaviour in Adobe Reader).
    if (!this.viewable) {
      var parentFlags = parentItem.get('F');
      if (this._isViewable(parentFlags)) {
        this.setFlags(parentFlags);
      }
    }
  }

  Util.inherit(PopupAnnotation, Annotation, {});

  return PopupAnnotation;
})();

var HighlightAnnotation = (function HighlightAnnotationClosure() {
  function HighlightAnnotation(parameters) {
    Annotation.call(this, parameters);

    this.data.annotationType = AnnotationType.HIGHLIGHT;
    this._preparePopup(parameters.dict);

    // PDF viewers completely ignore any border styles.
    this.data.borderStyle.setWidth(0);
  }

  Util.inherit(HighlightAnnotation, Annotation, {});

  return HighlightAnnotation;
})();

var UnderlineAnnotation = (function UnderlineAnnotationClosure() {
  function UnderlineAnnotation(parameters) {
    Annotation.call(this, parameters);

    this.data.annotationType = AnnotationType.UNDERLINE;
    this._preparePopup(parameters.dict);

    // PDF viewers completely ignore any border styles.
    this.data.borderStyle.setWidth(0);
  }

  Util.inherit(UnderlineAnnotation, Annotation, {});

  return UnderlineAnnotation;
})();

var SquigglyAnnotation = (function SquigglyAnnotationClosure() {
  function SquigglyAnnotation(parameters) {
    Annotation.call(this, parameters);

    this.data.annotationType = AnnotationType.SQUIGGLY;
    this._preparePopup(parameters.dict);

    // PDF viewers completely ignore any border styles.
    this.data.borderStyle.setWidth(0);
  }

  Util.inherit(SquigglyAnnotation, Annotation, {});

  return SquigglyAnnotation;
})();

var StrikeOutAnnotation = (function StrikeOutAnnotationClosure() {
  function StrikeOutAnnotation(parameters) {
    Annotation.call(this, parameters);

    this.data.annotationType = AnnotationType.STRIKEOUT;
    this._preparePopup(parameters.dict);

    // PDF viewers completely ignore any border styles.
    this.data.borderStyle.setWidth(0);
  }

  Util.inherit(StrikeOutAnnotation, Annotation, {});

  return StrikeOutAnnotation;
})();

var FileAttachmentAnnotation = (function FileAttachmentAnnotationClosure() {
  function FileAttachmentAnnotation(parameters) {
    Annotation.call(this, parameters);

    var file = new FileSpec(parameters.dict.get('FS'), parameters.xref);

    this.data.annotationType = AnnotationType.FILEATTACHMENT;
    this.data.file = file.serializable;
    this._preparePopup(parameters.dict);
  }

  Util.inherit(FileAttachmentAnnotation, Annotation, {});

  return FileAttachmentAnnotation;
})();

exports.Annotation = Annotation;
exports.AnnotationBorderStyle = AnnotationBorderStyle;
exports.AnnotationFactory = AnnotationFactory;
}));