Make WordPress Core

Ticket #21785: 21785-05.patch

File 21785-05.patch, 221.7 KB (added by kirasong, 11 years ago)

Code formatting cleanup; mostly brackets.

  • src/wp-admin/css/customize-controls.css

    diff --git src/wp-admin/css/customize-controls.css src/wp-admin/css/customize-controls.css
    index c76a6e5..448f1b5 100644
    body { 
    455455        -webkit-overflow-scrolling: touch;
    456456}
    457457
     458/** Header control **/
     459
     460#customize-control-header_image .current {
     461        margin-bottom: 8px;
     462}
     463
     464#customize-control-header_image .uploaded {
     465        margin-bottom: 18px;
     466}
     467
     468/* Header control: current image container */
     469
     470#customize-control-header_image .current .container {
     471        overflow: hidden;
     472        border-radius: 2px;
     473}
     474
     475#customize-control-header_image .placeholder {
     476        width: 100%;
     477        position: relative;
     478        background: #262626;
     479        text-align: center;
     480        cursor: default;
     481}
     482
     483#customize-control-header_image .inner {
     484        display: none;
     485        position: absolute;
     486        width: 100%;
     487        height: 18px;
     488        margin-top: -9px;
     489        top: 50%;
     490        color: #eee;
     491}
     492
     493/* Header control: overlay "close" button */
     494
     495#customize-control-header_image .header-view {
     496        position: relative;
     497}
     498
     499#customize-control-header_image .uploaded .header-view .close {
     500        font-size: 2em;
     501        color: grey;
     502        position: absolute;
     503        visibility: hidden;
     504        top: 10px;
     505        right: 10px;
     506        z-index: 1;
     507        width: 20px;
     508        height: 20px;
     509        cursor: pointer;
     510}
     511
     512#customize-control-header_image .uploaded .header-view .close:hover {
     513 color: black;
     514 text-shadow:
     515    -1px -1px 0 #fff,
     516    1px -1px 0 #fff,
     517    -1px 1px 0 #fff,
     518    1px 1px 0 #fff;
     519}
     520
     521#customize-control-header_image .header-view:hover .close {
     522        visibility: visible;
     523}
     524
     525/* Header control: randomiz(s)er */
     526
     527#customize-control-header_image .random.placeholder {
     528        cursor: pointer;
     529        border-radius: 2px;
     530        height: 40px;
     531}
     532
     533#customize-control-header_image .random .inner {
     534        display: block;
     535}
     536
     537#customize-control-header_image .dice {
     538        font-size: 16px;
     539        vertical-align: -1px;
     540}
     541
     542#customize-control-header_image .placeholder:hover .dice {
     543        -webkit-animation: dice-color-change 3s infinite;
     544        -moz-animation: dice-color-change 3s infinite;
     545        -ms-animation: dice-color-change 3s infinite;
     546        animation: dice-color-change 3s infinite;
     547}
     548
     549@-webkit-keyframes dice-color-change {
     550        0% { color: #d4b146; }
     551        50% { color: #ef54b0; }
     552        75% { color: #7190d3; }
     553        100% { color: #d4b146; }
     554}
     555
     556@-moz-keyframes dice-color-change {
     557        0% { color: #d4b146; }
     558        50% { color: #ef54b0; }
     559        75% { color: #7190d3; }
     560        100% { color: #d4b146; }
     561}
     562
     563@-ms-keyframes dice-color-change {
     564        0% { color: #d4b146; }
     565        50% { color: #ef54b0; }
     566        75% { color: #7190d3; }
     567        100% { color: #d4b146; }
     568}
     569
     570@keyframes dice-color-change {
     571        0% { color: #d4b146; }
     572        50% { color: #ef54b0; }
     573        75% { color: #7190d3; }
     574        100% { color: #d4b146; }
     575}
     576
     577/* Header control: actions and choices */
     578
     579#customize-control-header_image .actions {
     580        margin-bottom: 32px;
     581}
     582
     583#customize-control-header_image .choice {
     584        position: relative;
     585        display: block;
     586        margin-bottom: 9px;
     587}
     588
     589#customize-control-header_image .choice.random:before {
     590        position: absolute;
     591        content: attr(data-label);
     592        left: 0;
     593        top: 0;
     594}
     595
     596#customize-control-header_image .uploaded div:last-child > .choice {
     597        margin-bottom: 0;
     598}
     599
     600#customize-control-header_image .choices hr {
     601        visibility: hidden;
     602}
     603
     604#customize-control-header_image img {
     605        width: 100%;
     606        border-radius: 2px;
     607}
     608
     609#customize-control-header_image .remove {
     610        float: left;
     611        margin-right: 3px;
     612}
     613
     614#customize-control-header_image .new {
     615        float: right;
     616}
     617
     618
    458619/** Handle cheaters. */
    459620body.cheatin {
    460621        min-width: 0;
  • src/wp-admin/custom-header.php

    diff --git src/wp-admin/custom-header.php src/wp-admin/custom-header.php
    index 633dc65..f0b8c62 100644
    class Custom_Image_Header { 
    4343        var $default_headers = array();
    4444
    4545        /**
    46          * Holds custom headers uploaded by the user
     46         * Holds custom headers uploaded by the user.
    4747         *
    4848         * @var array
    4949         * @since 3.2.0
    class Custom_Image_Header { 
    7272                $this->admin_header_callback = $admin_header_callback;
    7373                $this->admin_image_div_callback = $admin_image_div_callback;
    7474
     75                if ( current_theme_supports( 'custom-header' ) ) {
     76                        add_action( 'customize_save_after', array( $this, 'set_last_used' ) );
     77                        add_action( 'wp_ajax_header_crop', array( $this, 'ajax_header_crop' ) );
     78                        add_action( 'wp_ajax_header_add', array( $this, 'ajax_header_add' ) );
     79                        add_action( 'wp_ajax_header_remove', array( $this, 'ajax_header_remove' ) );
     80                }
     81
    7582                add_action( 'admin_menu', array( $this, 'init' ) );
    7683        }
    7784
    class Custom_Image_Header { 
    93100                add_action("admin_head-$page", array($this, 'js'), 50);
    94101                if ( $this->admin_header_callback )
    95102                        add_action("admin_head-$page", $this->admin_header_callback, 51);
     103
    96104        }
    97105
    98106        /**
    wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?> 
    819827                $attachment_id = absint( $_POST['attachment_id'] );
    820828                $original = get_attached_file($attachment_id);
    821829
    822 
    823                 $max_width = 0;
    824                 // For flex, limit size of image displayed to 1500px unless theme says otherwise
    825                 if ( current_theme_supports( 'custom-header', 'flex-width' ) )
    826                         $max_width = 1500;
    827 
    828                 if ( current_theme_supports( 'custom-header', 'max-width' ) )
    829                         $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) );
    830                 $max_width = max( $max_width, get_theme_support( 'custom-header', 'width' ) );
    831 
    832                 if ( ( current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) ) || $_POST['width'] > $max_width )
    833                         $dst_height = absint( $_POST['height'] * ( $max_width / $_POST['width'] ) );
    834                 elseif ( current_theme_supports( 'custom-header', 'flex-height' ) && current_theme_supports( 'custom-header', 'flex-width' ) )
    835                         $dst_height = absint( $_POST['height'] );
    836                 else
    837                         $dst_height = get_theme_support( 'custom-header', 'height' );
    838 
    839                 if ( ( current_theme_supports( 'custom-header', 'flex-width' ) && ! current_theme_supports( 'custom-header', 'flex-height' ) ) || $_POST['width'] > $max_width )
    840                         $dst_width = absint( $_POST['width'] * ( $max_width / $_POST['width'] ) );
    841                 elseif ( current_theme_supports( 'custom-header', 'flex-width' ) && current_theme_supports( 'custom-header', 'flex-height' ) )
    842                         $dst_width = absint( $_POST['width'] );
    843                 else
    844                         $dst_width = get_theme_support( 'custom-header', 'width' );
     830                extract( $this->get_header_dimensions( array(
     831                        'width' => $_POST['width'],
     832                        'height' => $_POST['height'],
     833                ) ) );
    845834
    846835                if ( empty( $_POST['skip-cropping'] ) )
    847836                        $cropped = wp_crop_image( $attachment_id, (int) $_POST['x1'], (int) $_POST['y1'], (int) $_POST['width'], (int) $_POST['height'], $dst_width, $dst_height );
    wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?> 
    856845                /** This filter is documented in wp-admin/custom-header.php */
    857846                $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication
    858847
    859                 $parent = get_post($attachment_id);
    860                 $parent_url = $parent->guid;
    861                 $url = str_replace( basename( $parent_url ), basename( $cropped ), $parent_url );
    862 
    863                 $size = @getimagesize( $cropped );
    864                 $image_type = ( $size ) ? $size['mime'] : 'image/jpeg';
     848                $object = $this->create_attachment_object( $cropped, $attachment_id );
    865849
    866                 // Construct the object array
    867                 $object = array(
    868                         'ID' => $attachment_id,
    869                         'post_title' => basename($cropped),
    870                         'post_content' => $url,
    871                         'post_mime_type' => $image_type,
    872                         'guid' => $url,
    873                         'context' => 'custom-header'
    874                 );
    875850                if ( ! empty( $_POST['create-new-attachment'] ) )
    876851                        unset( $object['ID'] );
    877852
    878853                // Update the attachment
    879                 $attachment_id = wp_insert_attachment( $object, $cropped );
    880                 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $cropped ) );
     854                $attachment_id = $this->insert_attachment( $object, $cropped );
    881855
    882856                $width = $dst_width;
    883857                $height = $dst_height;
     858                $url = $object['guid'];
    884859                $this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) );
    885860
    886861                // cleanup
    wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?> 
    10411016                set_theme_mod( 'header_image', $default );
    10421017                set_theme_mod( 'header_image_data', (object) $default_data );
    10431018        }
     1019
     1020        /**
     1021         * Calculate dst_width and dst_height based on what the currently selected theme supports.
     1022         *
     1023         * @return array dst_height and dst_width of header image.
     1024         */
     1025        final public function get_header_dimensions( $dimensions ) {
     1026                $max_width = 0;
     1027                $width = absint( $dimensions['width'] );
     1028                $height = absint( $dimensions['height'] );
     1029                $theme_height = get_theme_support( 'custom-header', 'height' );
     1030                $theme_width = get_theme_support( 'custom-header', 'width' );
     1031                $has_flex_width = current_theme_supports( 'custom-header', 'flex-width' );
     1032                $has_flex_height = current_theme_supports( 'custom-header', 'flex-height' );
     1033                $has_max_width = current_theme_supports( 'custom-header', 'max-width' ) ;
     1034                $dst = array();
     1035
     1036                // For flex, limit size of image displayed to 1500px unless theme says otherwise
     1037                if ( $has_flex_width ) {
     1038                        $max_width = 1500;
     1039                }
     1040
     1041                if ( $has_max_width ) {
     1042                        $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) );
     1043                }
     1044                $max_width = max( $max_width, $theme_width );
     1045
     1046                if ( $has_flex_height && ( ! $has_flex_width || $width > $max_width ) ) {
     1047                        $dst['dst_height'] = absint( $height * ( $max_width / $width ) );
     1048                }
     1049                elseif ( $has_flex_height && $has_flex_width ) {
     1050                        $dst['dst_height'] = $height;
     1051                }
     1052                else {
     1053                        $dst['dst_height'] = $theme_height;
     1054                }
     1055
     1056                if ( $has_flex_width && ( ! $has_flex_height || $width > $max_width ) ) {
     1057                        $dst['dst_width'] = absint( $width * ( $max_width / $width ) );
     1058                }
     1059                elseif ( $has_flex_width && $has_flex_height ) {
     1060                        $dst['dst_width'] = $width;
     1061                }
     1062                else {
     1063                        $dst['dst_width'] = $theme_width;
     1064                }
     1065
     1066                return $dst;
     1067        }
     1068
     1069        /**
     1070         * Create an attachment 'object'.
     1071         *
     1072         * @param string $cropped Cropped image URL.
     1073         * @param int $parent_attachment_id Attachment ID of parent image.
     1074         *
     1075         * @return array Attachment object.
     1076         */
     1077        final public function create_attachment_object( $cropped, $parent_attachment_id ) {
     1078                $parent = get_post( $parent_attachment_id );
     1079                $parent_url = $parent->guid;
     1080                $url = str_replace( basename( $parent_url ), basename( $cropped ), $parent_url );
     1081
     1082                $size = @getimagesize( $cropped );
     1083                $image_type = ( $size ) ? $size['mime'] : 'image/jpeg';
     1084
     1085                $object = array(
     1086                        'ID' => $parent_attachment_id,
     1087                        'post_title' => basename($cropped),
     1088                        'post_content' => $url,
     1089                        'post_mime_type' => $image_type,
     1090                        'guid' => $url,
     1091                        'context' => 'custom-header'
     1092                );
     1093
     1094                return $object;
     1095        }
     1096
     1097        /**
     1098         * Insert an attachment & its metadata.
     1099         *
     1100         * @param array $object Attachment object.
     1101         * @param string $cropped Cropped image URL.
     1102         *
     1103         * @return int Attachment ID.
     1104         */
     1105        final public function insert_attachment( $object, $cropped ) {
     1106                $attachment_id = wp_insert_attachment( $object, $cropped );
     1107                $metadata = wp_generate_attachment_metadata( $attachment_id, $cropped );
     1108                /**
     1109                 * Allows us to insert custom meta data for an attachment.
     1110                 *
     1111                 */
     1112                $metadata = apply_filters( 'wp_header_image_attachment_metadata', $metadata );
     1113                wp_update_attachment_metadata( $attachment_id, $metadata );
     1114                return $attachment_id;
     1115        }
     1116
     1117        function ajax_check_permission( $name, $nonce, $attachment_id = null ) {
     1118                $name = $attachment_id === null ? $name : "${name}_${attachment_id}";
     1119                if ( ! isset( $nonce ) || ! wp_verify_nonce( $nonce, $name ) ||
     1120                                ! current_user_can( 'edit_theme_options' ) ) {
     1121                        wp_die( __( 'Cheatin’ uh?' ) );
     1122                }
     1123        }
     1124
     1125        /**
     1126         * Gets attachment uploaded by Media Manager, crops it, then saves it as a
     1127         * new object. Returns JSON-encoded object details.
     1128         */
     1129        function ajax_header_crop() {
     1130                $data = $_POST['data'];
     1131                $this->ajax_check_permission( 'crop-image', $data['nonces']['crop'], $data['id'] );
     1132
     1133                if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) {
     1134                        wp_die( __( 'Cheatin’ uh?' ) );
     1135                }
     1136
     1137                if ( ! empty( $data['skip-cropping'] ) &&
     1138                                ! ( current_theme_supports( 'custom-header', 'flex-height' ) ||
     1139                                        current_theme_supports( 'custom-header', 'flex-width' ) ) ) {
     1140                        wp_die( __( 'Cheatin’ uh?' ) );
     1141                }
     1142
     1143                $crop_details = $data['cropDetails'];
     1144
     1145                $dimensions = $this->get_header_dimensions( array(
     1146                        'width' => $crop_details['width'],
     1147                        'height' => $crop_details['height'],
     1148                ) );
     1149
     1150                $attachment_id = absint( $data['id'] );
     1151
     1152                $cropped = wp_crop_image(
     1153                        $attachment_id,
     1154                        (int) $crop_details['x1'],
     1155                        (int) $crop_details['y1'],
     1156                        (int) $crop_details['width'],
     1157                        (int) $crop_details['height'],
     1158                        (int) $dimensions['dst_width'],
     1159                        (int) $dimensions['dst_height']
     1160                );
     1161
     1162                if ( ! $cropped || is_wp_error( $cropped ) ) {
     1163                        wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) );
     1164                }
     1165
     1166                $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication
     1167
     1168                $object = $this->create_attachment_object( $cropped, $attachment_id );
     1169
     1170                unset( $object['ID'] );
     1171
     1172                $new_attachment_id = $this->insert_attachment( $object, $cropped );
     1173
     1174                $object['attachment_id'] = $new_attachment_id;
     1175                $object['width']         = $dimensions['dst_width'];
     1176                $object['height']        = $dimensions['dst_height'];
     1177
     1178                echo json_encode($object);
     1179                wp_die();
     1180        }
     1181
     1182        /**
     1183         * Given an attachment ID for a header image, updates its "last used"
     1184         * timestamp to now.
     1185         *
     1186         * Triggered when the user tries adds a new header image from the
     1187         * Media Manager, even if s/he doesn't save that change.
     1188         */
     1189        function ajax_header_add() {
     1190                $data = $_POST['data'];
     1191                $this->ajax_check_permission( 'header-add', $_POST['nonce'] );
     1192
     1193                $attachment_id = absint( $data['attachment_id'] );
     1194                if ( $attachment_id < 1 ) {
     1195                        return;
     1196                }
     1197
     1198                $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
     1199                update_post_meta( $attachment_id, $key, time() );
     1200                update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
     1201
     1202                wp_die();
     1203        }
     1204
     1205        /**
     1206         * Given an attachment ID for a header image, unsets it as a user-uploaded
     1207         * header image for the current theme.
     1208         *
     1209         * Triggered when the user clicks the overlay "X" button next to each image
     1210         * choice in the Customizer's Header tool.
     1211         */
     1212        function ajax_header_remove() {
     1213                $this->ajax_check_permission( 'header-remove', $_POST['nonce'] );
     1214
     1215                $attachment_id = absint( $_POST['attachment_id'] );
     1216                if ( $attachment_id < 1 ) {
     1217                        return;
     1218                }
     1219
     1220                $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
     1221                delete_post_meta( $attachment_id, $key );
     1222                delete_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
     1223
     1224                wp_die();
     1225        }
     1226
     1227        function set_last_used( $manager ) {
     1228                $data = $manager->get_setting( 'header_image_data' )->post_value();
     1229
     1230                if ( !isset( $data['attachment_id'] ) ) {
     1231                        return;
     1232                }
     1233
     1234                $attachment_id = $data['attachment_id'];
     1235                $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
     1236                update_post_meta( $attachment_id, $key, time() );
     1237        }
    10441238}
  • src/wp-admin/js/customize-controls.js

    diff --git src/wp-admin/js/customize-controls.js src/wp-admin/js/customize-controls.js
    index 3a05ad4..aed0f6d 100644
     
     1/* globals _wpCustomizeHeader, _wpMediaViewsL10n */
    12(function( exports, $ ){
    23        var api = wp.customize;
    34
     
    306307                }
    307308        });
    308309
     310        api.HeaderControl = api.Control.extend({
     311                ready: function() {
     312                        this.btnRemove        = $('.actions .remove');
     313                        this.btnNew           = $('.actions .new');
     314
     315                        _.bindAll(this, 'openMM', 'removeImage');
     316
     317                        this.btnNew.on( 'click', this.openMM );
     318                        this.btnRemove.on( 'click', this.removeImage );
     319
     320                        api.HeaderTool.currentHeader = new api.HeaderTool.ImageModel();
     321
     322                        new api.HeaderTool.CurrentView({
     323                                model: api.HeaderTool.currentHeader,
     324                                el: '.current .container'
     325                        });
     326
     327                        new api.HeaderTool.ChoiceListView({
     328                                collection: api.HeaderTool.UploadsList = new api.HeaderTool.ChoiceList(),
     329                                el: '.choices .uploaded .list'
     330                        });
     331
     332                        new api.HeaderTool.ChoiceListView({
     333                                collection: api.HeaderTool.DefaultsList = new api.HeaderTool.DefaultsList(),
     334                                el: '.choices .default .list'
     335                        });
     336
     337                        api.HeaderTool.combinedList = api.HeaderTool.CombinedList = new api.HeaderTool.CombinedList([
     338                                api.HeaderTool.UploadsList,
     339                                api.HeaderTool.DefaultsList
     340                        ]);
     341                },
     342
     343                /**
     344                 * Returns a set of options, computed from the attached image data and
     345                 * theme-specific data, to be fed to the imgAreaSelect plugin in
     346                 * wp.media.view.Cropper.
     347                 *
     348                 * @param {wp.media.model.Attachment} attachment
     349                 * @param {wp.media.controller.Cropper} controller
     350                 * @returns {Object} Options
     351                 */
     352                calculateImageSelectOptions: function(attachment, controller) {
     353                        var xInit = parseInt(_wpCustomizeHeader.data.width, 10),
     354                                yInit = parseInt(_wpCustomizeHeader.data.height, 10),
     355                                flexWidth = !! parseInt(_wpCustomizeHeader.data['flex-width'], 10),
     356                                flexHeight = !! parseInt(_wpCustomizeHeader.data['flex-height'], 10),
     357                                ratio, xImg, yImg, realHeight, realWidth,
     358                                imgSelectOptions;
     359
     360                        realWidth = attachment.get('width');
     361                        realHeight = attachment.get('height');
     362
     363                        this.headerImage = new api.HeaderTool.ImageModel();
     364                        this.headerImage.set({
     365                                themeWidth: xInit,
     366                                themeHeight: yInit,
     367                                themeFlexWidth: flexWidth,
     368                                themeFlexHeight: flexHeight,
     369                                imageWidth: realWidth,
     370                                imageHeight: realHeight
     371                        });
     372
     373                        controller.set( 'canSkipCrop', ! this.headerImage.shouldBeCropped() );
     374
     375                        ratio = xInit / yInit;
     376                        xImg = realWidth;
     377                        yImg = realHeight;
     378
     379                        if ( xImg / yImg > ratio ) {
     380                                yInit = yImg;
     381                                xInit = yInit * ratio;
     382                        } else {
     383                                xInit = xImg;
     384                                yInit = xInit / ratio;
     385                        }
     386
     387                        imgSelectOptions = {
     388                                handles: true,
     389                                keys: true,
     390                                instance: true,
     391                                persistent: true,
     392                                parent: this.$el,
     393                                imageWidth: realWidth,
     394                                imageHeight: realHeight,
     395                                x1: 0,
     396                                y1: 0,
     397                                x2: xInit,
     398                                y2: yInit
     399                        };
     400
     401                        if (flexHeight === false && flexWidth === false) {
     402                                imgSelectOptions.aspectRatio = xInit + ':' + yInit;
     403                        }
     404                        if (flexHeight === false ) {
     405                                imgSelectOptions.maxHeight = yInit;
     406                        }
     407                        if (flexWidth === false ) {
     408                                imgSelectOptions.maxWidth = xInit;
     409                        }
     410
     411                        return imgSelectOptions;
     412                },
     413
     414                /**
     415                 * Sets up and opens the Media Manager in order to select an image.
     416                 * Depending on both the size of the image and the properties of the
     417                 * current theme, a cropping step after selection may be required or
     418                 * skippable.
     419                 *
     420                 * @param {event} event
     421                 */
     422                openMM: function(event) {
     423                        var title, suggestedWidth, suggestedHeight,
     424                                l10n = _wpMediaViewsL10n;
     425
     426                        event.preventDefault();
     427
     428                        suggestedWidth = l10n.suggestedWidth.replace('%d', _wpCustomizeHeader.data.width);
     429                        suggestedHeight = l10n.suggestedHeight.replace('%d', _wpCustomizeHeader.data.height);
     430
     431                        title = {
     432                                html: l10n.chooseImage + ' <span class="suggested-dimensions">' +
     433                                                        suggestedWidth + ' ' + suggestedHeight +'</span>',
     434                                text: l10n.chooseImage
     435                        };
     436
     437                        this.frame = wp.media({
     438                                title: title,
     439                                library: {
     440                                        type: 'image'
     441                                },
     442                                button: {
     443                                        text: l10n.selectAndCrop,
     444                                        close: false
     445                                },
     446                                multiple: false,
     447                                imgSelectOptions: this.calculateImageSelectOptions
     448                        });
     449
     450                        this.frame.states.add([new wp.media.controller.Cropper()]);
     451
     452                        this.frame.on('select', this.onSelect, this);
     453                        this.frame.on('cropped', this.onCropped, this);
     454                        this.frame.on('skippedcrop', this.onSkippedCrop, this);
     455
     456                        this.frame.open();
     457                },
     458
     459                onSelect: function() {
     460                        this.frame.setState('cropper');
     461                },
     462                onCropped: function(croppedImage) {
     463                        var url = croppedImage.post_content,
     464                                attachmentId = croppedImage.attachment_id,
     465                                w = croppedImage.width,
     466                                h = croppedImage.height;
     467                        this.setImageFromURL(url, attachmentId, w, h);
     468                },
     469                onSkippedCrop: function(selection) {
     470                        var url = selection.get('url'),
     471                                w = selection.get('width'),
     472                                h = selection.get('height');
     473                        this.setImageFromURL(url, selection.id, w, h);
     474                },
     475
     476                /**
     477                 * Creates a new wp.customize.HeaderTool.ImageModel from provided
     478                 * header image data and inserts it into the user-uploaded headers
     479                 * collection.
     480                 *
     481                 * @param {String} url
     482                 * @param {Number} attachmentId
     483                 * @param {Number} width
     484                 * @param {Number} height
     485                 */
     486                setImageFromURL: function(url, attachmentId, width, height) {
     487                        var choice, data = {};
     488
     489                        data.url = url;
     490                        data.thumbnail_url = url;
     491
     492                        if (attachmentId) {
     493                                data.attachment_id = attachmentId;
     494                        }
     495
     496                        if (width) {
     497                                data.width = width;
     498                        }
     499
     500                        if (height) {
     501                                data.height = height;
     502                        }
     503
     504                        choice = new api.HeaderTool.ImageModel({
     505                                header: data,
     506                                choice: url.split('/').pop()
     507                        });
     508                        api.HeaderTool.UploadsList.add(choice);
     509                        api.HeaderTool.currentHeader.set(choice.toJSON());
     510                        choice.save();
     511                        choice.importImage();
     512                },
     513
     514                /**
     515                 * Triggers the necessary events to deselect an image which was set as
     516                 * the currently selected one.
     517                 */
     518                removeImage: function() {
     519                        api.HeaderTool.currentHeader.trigger('hide');
     520                        api.HeaderTool.CombinedList.trigger('control:removeImage');
     521                }
     522
     523        });
     524
    309525        // Change objects contained within the main customize object to Settings.
    310526        api.defaultConstructor = api.Setting;
    311527
     
    686902        api.controlConstructor = {
    687903                color:  api.ColorControl,
    688904                upload: api.UploadControl,
    689                 image:  api.ImageControl
     905                image:  api.ImageControl,
     906                header: api.HeaderControl
    690907        };
    691908
    692909        $( function() {
     
    9611178                        });
    9621179                });
    9631180
    964                 // Handle header image data
    965                 api.control( 'header_image', function( control ) {
    966                         control.setting.bind( function( to ) {
    967                                 if ( to === control.params.removed )
    968                                         control.settings.data.set( false );
    969                         });
    970 
    971                         control.library.on( 'click', 'a', function() {
    972                                 control.settings.data.set( $(this).data('customizeHeaderImageData') );
    973                         });
    974 
    975                         control.uploader.success = function( attachment ) {
    976                                 var data;
    977 
    978                                 api.ImageControl.prototype.success.call( control, attachment );
    979 
    980                                 data = {
    981                                         attachment_id: attachment.get('id'),
    982                                         url:           attachment.get('url'),
    983                                         thumbnail_url: attachment.get('url'),
    984                                         height:        attachment.get('height'),
    985                                         width:         attachment.get('width')
    986                                 };
    987 
    988                                 attachment.element.data( 'customizeHeaderImageData', data );
    989                                 control.settings.data.set( data );
    990                         };
    991                 });
    992 
    9931181                api.trigger( 'ready' );
    9941182
    9951183                // Make sure left column gets focus
  • src/wp-includes/class-wp-customize-control.php

    diff --git src/wp-includes/class-wp-customize-control.php src/wp-includes/class-wp-customize-control.php
    index 8dedf10..e3ce08c 100644
    class WP_Customize_Background_Image_Control extends WP_Customize_Image_Control { 
    708708        }
    709709}
    710710
    711 /**
    712  * Customize Header Image Control Class
    713  *
    714  * @package WordPress
    715  * @subpackage Customize
    716  * @since 3.4.0
    717  */
    718711class WP_Customize_Header_Image_Control extends WP_Customize_Image_Control {
    719         /**
    720          * The processed default headers.
    721          * @since 3.4.2
    722          * @var array
    723          */
    724         protected $default_headers;
    725 
    726         /**
    727          * The uploaded headers.
    728          * @since 3.4.2
    729          * @var array
    730          */
    731         protected $uploaded_headers;
     712        public $type = 'header';
    732713
    733         /**
    734          * Constructor.
    735          *
    736          * @since 3.4.0
    737          * @uses WP_Customize_Image_Control::__construct()
    738          * @uses WP_Customize_Image_Control::add_tab()
    739          *
    740          * @param WP_Customize_Manager $manager
    741          */
    742714        public function __construct( $manager ) {
    743715                parent::__construct( $manager, 'header_image', array(
    744716                        'label'    => __( 'Header Image' ),
    class WP_Customize_Header_Image_Control extends WP_Customize_Image_Control { 
    750722                        'context'  => 'custom-header',
    751723                        'removed'  => 'remove-header',
    752724                        'get_url'  => 'get_header_image',
    753                         'statuses' => array(
    754                                 ''                      => __('Default'),
    755                                 'remove-header'         => __('No Image'),
    756                                 'random-default-image'  => __('Random Default Image'),
    757                                 'random-uploaded-image' => __('Random Uploaded Image'),
     725                ) );
     726
     727        }
     728
     729        public function to_json() {
     730                parent::to_json();
     731        }
     732
     733        public function enqueue() {
     734                wp_enqueue_media();
     735                wp_enqueue_script( 'customize-views' );
     736
     737                $this->prepare_control();
     738
     739                wp_localize_script( 'customize-views', '_wpCustomizeHeader', array(
     740                        'data' => array(
     741                                'width' => absint( get_theme_support( 'custom-header', 'width' ) ),
     742                                'height' => absint( get_theme_support( 'custom-header', 'height' ) ),
     743                                'flex-width' => absint( get_theme_support( 'custom-header', 'flex-width' ) ),
     744                                'flex-height' => absint( get_theme_support( 'custom-header', 'flex-height' ) ),
     745                                'currentImgSrc' => $this->get_current_image_src(),
     746                        ),
     747                        'nonces' => array(
     748                                'add' => wp_create_nonce( 'header-add' ),
     749                                'remove' => wp_create_nonce( 'header-remove' ),
     750                        ),
     751                        'l10n' => array(
     752                                /* translators: header images uploaded by user */
     753                                'uploaded' => __( 'uploaded' ),
     754                                /* translators: header images suggested by the current theme */
     755                                'default' => __( 'suggested' )
     756                        ),
     757                        'uploads' => $this->uploaded_headers,
     758                        'defaults' => $this->default_headers
     759                ) );
     760
     761                parent::enqueue();
     762        }
     763
     764        public function get_default_header_images() {
     765                global $custom_image_header;
     766
     767                // Get *the* default image if there is one
     768                $default = get_theme_support( 'custom-header', 'default-image' );
     769
     770                if ( ! $default ) { // If not,
     771                        return $custom_image_header->default_headers; // easy peasy.
     772                }
     773
     774                $default = sprintf( $default,
     775                        get_template_directory_uri(),
     776                        get_stylesheet_directory_uri() );
     777
     778                $header_images = array();
     779                $already_has_default = false;
     780
     781                // Get the whole set of default images
     782                $default_header_images = $custom_image_header->default_headers;
     783                foreach ( $default_header_images as $k => $h ) {
     784                        if ( $h['url'] == $default ) {
     785                                $already_has_default = true;
     786                                break;
     787                        }
     788                }
     789
     790                // If *the one true image* isn't included in the default set, add it in
     791                // first position
     792                if ( ! $already_has_default ) {
     793                        $header_images['default'] = array(
     794                                'url' => $default,
     795                                'thumbnail_url' => $default,
     796                                'description' => 'Default'
     797                        );
     798                }
     799
     800                // The rest of the set comes after
     801                $header_images = array_merge( $header_images, $default_header_images );
     802
     803                return $header_images;
     804        }
     805
     806        public function get_uploaded_header_images() {
     807                $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet();
     808                $header_images = array();
     809
     810                $headers_not_dated = get_posts( array(
     811                        'post_type' => 'attachment',
     812                        'meta_key' => '_wp_attachment_is_custom_header',
     813                        'meta_value' => get_option('stylesheet'),
     814                        'orderby' => 'none',
     815                        'nopaging' => true,
     816                        'meta_query' => array(
     817                                array(
     818                                        'key' => '_wp_attachment_is_custom_header',
     819                                        'value' => get_option( 'stylesheet' ),
     820                                        'compare' => 'LIKE'
     821                                ),
     822                                array(
     823                                        'key' => $key,
     824                                        'value' => 'this string must not be empty',
     825                                        'compare' => 'NOT EXISTS'
     826                                ),
    758827                        )
    759828                ) );
    760829
    761                 // Remove the upload tab.
    762                 $this->remove_tab( 'upload-new' );
     830                $headers_dated = get_posts( array(
     831                        'post_type' => 'attachment',
     832                        'meta_key' => $key,
     833                        'orderby' => 'meta_value_num',
     834                        'order' => 'DESC',
     835                        'nopaging' => true,
     836                        'meta_query' => array(
     837                                array(
     838                                        'key' => '_wp_attachment_is_custom_header',
     839                                        'value' => get_option( 'stylesheet' ),
     840                                        'compare' => 'LIKE'
     841                                ),
     842                        ),
     843                ) );
     844
     845                $limit = apply_filters( 'custom_header_uploaded_limit', 15 );
     846                $headers = array_merge( $headers_dated, $headers_not_dated );
     847                $headers = array_slice( $headers, 0, $limit );
     848
     849                foreach ( (array) $headers as $header ) {
     850                        $url = esc_url_raw( $header->guid );
     851                        $header_data = wp_get_attachment_metadata( $header->ID );
     852                        $timestamp = get_post_meta( $header->ID,
     853                                '_wp_attachment_custom_header_last_used_' . get_stylesheet(),
     854                                true );
     855
     856                        $h = array(
     857                                'attachment_id' => $header->ID,
     858                                'url'           => $url,
     859                                'thumbnail_url' => $url,
     860                                'timestamp'     => $timestamp ? $timestamp : 0,
     861                        );
     862
     863                        if ( isset( $header_data['width'] ) ) {
     864                                $h['width'] = $header_data['width'];
     865                        }
     866                        if ( isset( $header_data['height'] ) ) {
     867                                $h['height'] = $header_data['height'];
     868                        }
     869
     870                        $header_images[] = $h;
     871                }
     872
     873                return $header_images;
    763874        }
    764875
    765         /**
    766          * Prepares the control.
    767          *
    768          * If no tabs exist, removes the control from the manager.
    769          *
    770          * @since 3.4.2
    771          */
    772876        public function prepare_control() {
    773877                global $custom_image_header;
    774                 if ( empty( $custom_image_header ) )
    775                         return parent::prepare_control();
     878                if ( empty( $custom_image_header ) ) {
     879                        return;
     880                }
    776881
    777882                // Process default headers and uploaded headers.
    778883                $custom_image_header->process_default_headers();
    779                 $this->default_headers = $custom_image_header->default_headers;
    780                 $this->uploaded_headers = get_uploaded_header_images();
     884                $this->default_headers = $this->get_default_header_images();
     885                $this->uploaded_headers = $this->get_uploaded_header_images();
     886        }
    781887
    782                 if ( $this->default_headers )
    783                         $this->add_tab( 'default',  __('Default'),  array( $this, 'tab_default_headers' ) );
     888        function print_header_image_template() {
     889                ?>
     890                <script type="text/template" id="tmpl-header-choice">
     891                        <# if (data.random) { #>
     892
     893                        <div class="placeholder random">
     894                                <div class="inner">
     895                                        <span><span class="dice">&#9860;</span>
     896                                                <?php /* translators: "nImages" is a number, "type" is either "uploaded" or "suggested" */ ?>
     897                                                <?php _e( 'Randomize {{{data.nImages}}} {{{data.type}}} headers' ); ?>
     898                                        </span>
     899                                </div>
     900                        </div>
    784901
    785                 if ( ! $this->uploaded_headers )
    786                         $this->remove_tab( 'uploaded' );
     902                        <# } else { #>
    787903
    788                 return parent::prepare_control();
    789         }
     904                        <# if (data.type == 'uploaded') { #>
     905                        <div class="dashicons dashicons-no close"></div>
     906                        <# } #>
    790907
    791         /**
    792          * @since 3.4.0
    793          *
    794          * @param mixed $choice Which header image to select. (@see Custom_Image_Header::get_header_image() )
    795          * @param array $header
    796          */
    797         public function print_header_image( $choice, $header ) {
    798                 $header['url']           = set_url_scheme( $header['url'] );
    799                 $header['thumbnail_url'] = set_url_scheme( $header['thumbnail_url'] );
     908                        <a href="#" class="choice thumbnail #>"
     909                                data-customize-image-value="{{{data.header.url}}}"
     910                                data-customize-header-image-data="{{JSON.stringify(data.header)}}">
     911                                <img src="{{{data.header.thumbnail_url}}}">
     912                        </a>
    800913
    801                 $header_image_data = array( 'choice' => $choice );
    802                 foreach ( array( 'attachment_id', 'width', 'height', 'url', 'thumbnail_url' ) as $key ) {
    803                         if ( isset( $header[ $key ] ) )
    804                                 $header_image_data[ $key ] = $header[ $key ];
    805                 }
     914                        <# } #>
     915                </script>
    806916
     917                <script type="text/template" id="tmpl-header-current">
     918                        <# if (data.choice) { #>
     919                                <# if (data.random) { #>
    807920
    808                 ?>
    809                 <a href="#" class="thumbnail"
    810                         data-customize-image-value="<?php echo esc_url( $header['url'] ); ?>"
    811                         data-customize-header-image-data="<?php echo esc_attr( json_encode( $header_image_data ) ); ?>">
    812                         <img src="<?php echo esc_url( $header['thumbnail_url'] ); ?>" />
    813                 </a>
     921                        <div class="placeholder">
     922                                <div class="inner">
     923                                        <span><span class="dice">&#9860;</span>
     924                                                <?php /* translators: "nImages" is a number, "type" is either "uploaded" or "suggested" */ ?>
     925                                                <?php _e( 'Randomizing {{{data.nImages}}} {{{data.type}}} headers' ); ?>
     926                                        </span>
     927                                </div>
     928                        </div>
     929
     930                                <# } else { #>
     931
     932                        <img src="{{{data.header.thumbnail_url}}}" />
     933
     934                                <# } #>
     935                        <# } else { #>
     936
     937                        <div class="placeholder">
     938                                <div class="inner">
     939                                        <span>
     940                                                <?php _e( 'No image set' ); ?>
     941                                        </span>
     942                                </div>
     943                        </div>
     944
     945                        <# } #>
     946                </script>
    814947                <?php
    815948        }
    816949
    817         /**
    818          * @since 3.4.0
    819          */
    820         public function tab_uploaded() {
    821                 ?><div class="uploaded-target"></div><?php
    822 
    823                 foreach ( $this->uploaded_headers as $choice => $header )
    824                         $this->print_header_image( $choice, $header );
     950        public function get_current_image_src() {
     951                $src = $this->value();
     952                if ( isset( $this->get_url ) ) {
     953                        $src = call_user_func( $this->get_url, $src );
     954                        return $src;
     955                }
     956                return null;
    825957        }
    826958
    827         /**
    828          * @since 3.4.0
    829          */
    830         public function tab_default_headers() {
    831                 foreach ( $this->default_headers as $choice => $header )
    832                         $this->print_header_image( $choice, $header );
     959        public function render_content() {
     960                $this->print_header_image_template();
     961                $visibility = $this->get_current_image_src() ? '' : ' style="display:none" ';
     962                $width = absint( get_theme_support( 'custom-header', 'width' ) );
     963                $height = absint( get_theme_support( 'custom-header', 'height' ) );
     964                ?>
     965
     966
     967                <div class="customize-control-content">
     968                        <p class="customizer-section-intro">
     969                                <?php _e( 'Personalize your blog with your own header image.' ); ?>
     970                                <?php
     971                                if ( $width && $height ) {
     972                                        printf( __( 'While you can crop images to your liking after clicking <strong>%s</strong>, your theme recommends a header size of <strong>%dx%d</strong> pixels.' ),
     973                                                _x( 'Add new', 'new image', 'custom-header' ), $width, $height );
     974                                } else {
     975                                        if ( $width ) {
     976                                                printf( __( 'While you can crop images to your liking after clicking <strong>%s</strong>, your theme recommends a header width of <strong>%d</strong> pixels.' ),
     977                                                        _x( 'Add new', 'new image', 'custom-header' ), $width );
     978                                        }
     979                                        if ( $height ) {
     980                                                printf( __( 'While you can crop images to your liking after clicking <strong>%s</strong>, your theme recommends a header height of <strong>%d</strong> pixels.' ),
     981                                                        _x( 'Add new', 'new image', 'custom-header' ), $height );
     982                                        }
     983                                }
     984                                ?>
     985                        </p>
     986                        <div class="current">
     987                                <span class="customize-control-title">
     988                                        <?php _e( 'Current header', 'custom-header' ); ?>
     989                                </span>
     990                                <div class="container">
     991                                </div>
     992                        </div>
     993                        <div class="actions">
     994                                <?php /* translators: Hide as in hide header image via the Customizer */ ?>
     995                                <a href="#" <?php echo $visibility ?> class="button remove"><?php _e( 'Hide', 'custom-header' ); ?></a>
     996                                <?php /* translators: New as in add new header image via the Customizer */ ?>
     997                                <a href="#" class="button new"><?php _ex( 'Add new', 'new image', 'custom-header' ); ?></a>
     998                                <div style="clear:both"></div>
     999                        </div>
     1000                        <div class="choices">
     1001                                <span class="customize-control-title header-previously-uploaded">
     1002                                        <?php _e( 'Previously uploaded', 'custom-header' ); ?>
     1003                                </span>
     1004                                <div class="uploaded">
     1005                                        <div class="list">
     1006                                        </div>
     1007                                </div>
     1008                                <span class="customize-control-title header-default">
     1009                                        <?php _e( 'Suggested', 'custom-header' ); ?>
     1010                                </span>
     1011                                <div class="default">
     1012                                        <div class="list">
     1013                                        </div>
     1014                                </div>
     1015                        </div>
     1016                </div>
     1017                <?php
    8331018        }
    8341019}
    8351020
  • src/wp-includes/css/media-views.css

    diff --git src/wp-includes/css/media-views.css src/wp-includes/css/media-views.css
    index c86edcc..bb89c77 100644
     
    602602        margin: 0;
    603603}
    604604
     605.media-frame-title .suggested-dimensions {
     606        font-size: 14px;
     607        float: right;
     608        margin-right: 20px;
     609}
     610
     611.media-frame-content .crop-content {
     612        display: block;
     613        margin: auto;
     614        max-width: 100%;
     615        max-height: 100%;
     616}
     617
    605618/**
    606619 * Iframes
    607620 */
  • new file src/wp-includes/js/customize-models.js

    diff --git src/wp-includes/js/customize-models.js src/wp-includes/js/customize-models.js
    new file mode 100644
    index 0000000..01d73fb
    - +  
     1/* globals jQuery, _wpCustomizeHeader, _wpCustomizeSettings */
     2;( function( $, wp ) {
     3        var api = wp.customize;
     4        api.HeaderTool = {};
     5
     6
     7        /**
     8         * wp.customize.HeaderTool.ImageModel
     9         *
     10         * A header image. This is where saves via the Customizer API are
     11         * abstracted away, plus our own AJAX calls to add images to and remove
     12         * images from the user's recently uploaded images setting on the server.
     13         * These calls are made regardless of whether the user actually saves new
     14         * Customizer settings.
     15         *
     16         * @constructor
     17         * @augments Backbone.Model
     18         */
     19        api.HeaderTool.ImageModel = Backbone.Model.extend({
     20                defaults: function() {
     21                        return {
     22                                header: {
     23                                        attachment_id: 0,
     24                                        url: '',
     25                                        timestamp: Date.now(),
     26                                        thumbnail_url: ''
     27                                },
     28                                choice: '',
     29                                hidden: false,
     30                                random: false
     31                        };
     32                },
     33
     34                initialize: function() {
     35                        this.on('hide', this.hide, this);
     36                },
     37
     38                hide: function() {
     39                        this.set('choice', '');
     40                        api('header_image').set('remove-header');
     41                        api('header_image_data').set('remove-header');
     42                },
     43
     44                destroy: function() {
     45                        var data = this.get('header'),
     46                                curr = api.HeaderTool.currentHeader.get('header').attachment_id;
     47
     48                        // If the image we're removing is also the current header, unset
     49                        // the latter
     50                        if (curr && data.attachment_id === curr) {
     51                                api.HeaderTool.currentHeader.trigger('hide');
     52                        }
     53
     54                        $.post(_wpCustomizeSettings.url.ajax, {
     55                                wp_customize: 'on',
     56                                theme: api.settings.theme.stylesheet,
     57                                dataType: 'json',
     58                                action: 'header_remove',
     59                                nonce: _wpCustomizeHeader.nonces.remove,
     60                                attachment_id: data.attachment_id
     61                        });
     62
     63                        this.trigger('destroy', this, this.collection);
     64                },
     65
     66                save: function() {
     67                        if (this.get('random')) {
     68                                api('header_image').set(this.get('header').random);
     69                                api('header_image_data').set(this.get('header').random);
     70                        } else {
     71                                if (this.get('header').defaultName) {
     72                                        api('header_image').set(this.get('header').url);
     73                                        api('header_image_data').set(this.get('header').defaultName);
     74                                } else {
     75                                        api('header_image').set(this.get('header').url);
     76                                        api('header_image_data').set(this.get('header'));
     77                                }
     78                        }
     79
     80                        api.HeaderTool.combinedList.trigger('control:setImage', this);
     81                },
     82
     83                importImage: function() {
     84                        var data = this.get('header');
     85                        if (data.attachment_id === undefined) {
     86                                return;
     87                        }
     88
     89                        $.post(_wpCustomizeSettings.url.ajax, {
     90                                wp_customize: 'on',
     91                                theme: api.settings.theme.stylesheet,
     92                                dataType: 'json',
     93                                action: 'header_add',
     94                                nonce: _wpCustomizeHeader.nonces.add,
     95                                data: data
     96                        });
     97                },
     98
     99                shouldBeCropped: function() {
     100                        if (this.get('themeFlexWidth') === true &&
     101                                                this.get('themeFlexHeight') === true) {
     102                                return false;
     103                        }
     104
     105                        if (this.get('themeFlexWidth') === true &&
     106                                this.get('themeHeight') === this.get('imageHeight')) {
     107                                return false;
     108                        }
     109
     110                        if (this.get('themeFlexHeight') === true &&
     111                                this.get('themeWidth') === this.get('imageWidth')) {
     112                                return false;
     113                        }
     114
     115                        if (this.get('themeWidth') === this.get('imageWidth') &&
     116                                this.get('themeHeight') === this.get('imageHeight')) {
     117                                return false;
     118                        }
     119
     120                        return true;
     121                }
     122        });
     123
     124
     125        /**
     126         * wp.customize.HeaderTool.ChoiceList
     127         *
     128         * @constructor
     129         * @augments Backbone.Collection
     130         */
     131        api.HeaderTool.ChoiceList = Backbone.Collection.extend({
     132                model: api.HeaderTool.ImageModel,
     133
     134                // Ordered from most recently used to least
     135                comparator: function(model) {
     136                        return -model.get('header').timestamp;
     137                },
     138
     139                initialize: function() {
     140                        var current = api.HeaderTool.currentHeader.get('choice').replace(/^https?:\/\//, ''),
     141                                isRandom = this.isRandomChoice(api.get().header_image);
     142
     143                        // Overridable by an extending class
     144                        if (!this.type) {
     145                                this.type = 'uploaded';
     146                        }
     147
     148                        // Overridable by an extending class
     149                        if (!this.data) {
     150                                this.data = _wpCustomizeHeader.uploads;
     151                        }
     152
     153                        if (isRandom) {
     154                                // So that when adding data we don't hide regular images
     155                                current = api.get().header_image;
     156                        }
     157
     158                        this.on('control:setImage', this.setImage, this);
     159                        this.on('control:removeImage', this.removeImage, this);
     160                        this.on('add', this.maybeAddRandomChoice, this);
     161
     162                        _.each(this.data, function(elt, index) {
     163                                if (!elt.attachment_id) {
     164                                        elt.defaultName = index;
     165                                }
     166
     167                                this.add({
     168                                        header: elt,
     169                                        choice: elt.url.split('/').pop(),
     170                                        hidden: current === elt.url.replace(/^https?:\/\//, '')
     171                                }, { silent: true });
     172                        }, this);
     173
     174                        if (this.size() > 0) {
     175                                this.addRandomChoice(current);
     176                        }
     177                },
     178
     179                maybeAddRandomChoice: function() {
     180                        if (this.size() === 1) {
     181                                this.addRandomChoice();
     182                        }
     183                },
     184
     185                addRandomChoice: function(initialChoice) {
     186                        var isRandomSameType = RegExp(this.type).test(initialChoice),
     187                                randomChoice = 'random-' + this.type + '-image';
     188
     189                        this.add({
     190                                header: {
     191                                        timestamp: 0,
     192                                        random: randomChoice,
     193                                        width: 245,
     194                                        height: 41
     195                                },
     196                                choice: randomChoice,
     197                                random: true,
     198                                hidden: isRandomSameType
     199                        });
     200                },
     201
     202                isRandomChoice: function(choice) {
     203                        return (/^random-(uploaded|default)-image$/).test(choice);
     204                },
     205
     206                shouldHideTitle: function() {
     207                        return _.every(this.pluck('hidden'));
     208                },
     209
     210                setImage: function(model) {
     211                        this.each(function(m) {
     212                                m.set('hidden', false);
     213                        });
     214
     215                        if (model) {
     216                                model.set('hidden', true);
     217                                // Bump images to top except for special "Randomize" images
     218                                if (!model.get('random')) {
     219                                        model.get('header').timestamp = Date.now();
     220                                        this.sort();
     221                                }
     222                        }
     223                },
     224
     225                removeImage: function() {
     226                        this.each(function(m) {
     227                                m.set('hidden', false);
     228                        });
     229                },
     230
     231                shown: function() {
     232                        var filtered = this.where({ hidden: false });
     233                        return new api.HeaderTool.ChoiceList( filtered );
     234                }
     235        });
     236
     237
     238        /**
     239         * wp.customize.HeaderTool.DefaultsList
     240         *
     241         * @constructor
     242         * @augments wp.customize.HeaderTool.ChoiceList
     243         * @augments Backbone.Collection
     244         */
     245        api.HeaderTool.DefaultsList = api.HeaderTool.ChoiceList.extend({
     246                initialize: function() {
     247                        this.type = 'default';
     248                        this.data = _wpCustomizeHeader.defaults;
     249                        api.HeaderTool.ChoiceList.prototype.initialize.apply(this);
     250                }
     251        });
     252
     253})( jQuery, this.wp );
  • new file src/wp-includes/js/customize-views.js

    diff --git src/wp-includes/js/customize-views.js src/wp-includes/js/customize-views.js
    new file mode 100644
    index 0000000..bb0b4d4
    - +  
     1/* globals jQuery, _, Backbone, _wpCustomizeHeader */
     2;( function( $, wp, _ ) {
     3        if ( ! wp || ! wp.customize ) { return; }
     4        var api = wp.customize;
     5
     6
     7        /**
     8         * wp.customize.HeaderTool.CurrentView
     9         *
     10         * Displays the currently selected header image, or a placeholder in lack
     11         * thereof.
     12         *
     13         * Instantiate with model wp.customize.HeaderTool.currentHeader.
     14         *
     15         * @constructor
     16         * @augments wp.Backbone.View
     17         */
     18        api.HeaderTool.CurrentView = wp.Backbone.View.extend({
     19                template: wp.template('header-current'),
     20
     21                initialize: function() {
     22                        this.listenTo(this.model, 'change', this.render);
     23                        this.render();
     24                },
     25
     26                render: function() {
     27                        this.$el.html(this.template(this.model.toJSON()));
     28                        this.setPlaceholder();
     29                        this.setButtons();
     30                        return this;
     31                },
     32
     33                getHeight: function() {
     34                        var image = this.$el.find('img'),
     35                                saved = this.model.get('savedHeight'),
     36                                height = image.height() || saved,
     37                                headerImageData;
     38
     39                        if (image.length) {
     40                                this.$el.find('.inner').hide();
     41                        } else {
     42                                this.$el.find('.inner').show();
     43                        }
     44
     45                        // happens at ready
     46                        if (!height) {
     47                                headerImageData = api.get().header_image_data;
     48
     49                                if (headerImageData && headerImageData.width && headerImageData.height) {
     50                                        // hardcoded container width
     51                                        height = 260 / headerImageData.width * headerImageData.height;
     52                                }
     53                                else {
     54                                        // fallback for when no image is set
     55                                        height = 40;
     56                                }
     57                        }
     58
     59                        return height;
     60                },
     61
     62                setPlaceholder: function(_height) {
     63                        var height = _height || this.getHeight();
     64                        this.model.set('savedHeight', height);
     65                        this.$el
     66                                .add(this.$el.find('.placeholder'))
     67                                .height(height);
     68                },
     69
     70                setButtons: function() {
     71                        var elements = $('.actions .remove');
     72                        if (this.model.get('choice')) {
     73                                elements.show();
     74                        } else {
     75                                elements.hide();
     76                        }
     77                }
     78        });
     79
     80
     81        /**
     82         * wp.customize.HeaderTool.ChoiceView
     83         *
     84         * Represents a choosable header image, be it user-uploaded,
     85         * theme-suggested or a special Randomize choice.
     86         *
     87         * Takes a wp.customize.HeaderTool.ImageModel.
     88         *
     89         * Manually changes model wp.customize.HeaderTool.currentHeader via the
     90         * `select` method.
     91         *
     92         * @constructor
     93         * @augments wp.Backbone.View
     94         */
     95        (function () { // closures FTW
     96        var lastHeight = 0;
     97        api.HeaderTool.ChoiceView = wp.Backbone.View.extend({
     98                template: wp.template('header-choice'),
     99
     100                className: 'header-view',
     101
     102                events: {
     103                        'click .choice,.random': 'select',
     104                        'click .close': 'removeImage'
     105                },
     106
     107                initialize: function() {
     108                        var properties = [
     109                                this.model.get('header').url,
     110                                this.model.get('choice')
     111                        ];
     112
     113                        this.listenTo(this.model, 'change', this.render);
     114
     115                        if (_.contains(properties, api.get().header_image)) {
     116                                api.HeaderTool.currentHeader.set(this.extendedModel());
     117                        }
     118                },
     119
     120                render: function() {
     121                        var model = this.model;
     122
     123                        this.$el.html(this.template(this.extendedModel()));
     124
     125                        if (model.get('random')) {
     126                                this.setPlaceholder(40);
     127                        }
     128                        else {
     129                                lastHeight = this.getHeight();
     130                        }
     131
     132                        this.$el.toggleClass('hidden', model.get('hidden'));
     133                        return this;
     134                },
     135
     136                extendedModel: function() {
     137                        var c = this.model.get('collection'),
     138                                t = _wpCustomizeHeader.l10n[c.type] || '';
     139
     140                        return _.extend(this.model.toJSON(), {
     141                                // -1 to exclude the randomize button
     142                                nImages: c.size() - 1,
     143                                type: t
     144                        });
     145                },
     146
     147                getHeight: api.HeaderTool.CurrentView.prototype.getHeight,
     148
     149                setPlaceholder: api.HeaderTool.CurrentView.prototype.setPlaceholder,
     150
     151                select: function() {
     152                        this.model.save();
     153                        api.HeaderTool.currentHeader.set(this.extendedModel());
     154                },
     155
     156                removeImage: function(e) {
     157                        e.stopPropagation();
     158                        this.model.destroy();
     159                        this.remove();
     160                }
     161        });
     162        })();
     163
     164
     165        /**
     166         * wp.customize.HeaderTool.ChoiceListView
     167         *
     168         * A container for ChoiceViews. These choices should be of one same type:
     169         * user-uploaded headers or theme-defined ones.
     170         *
     171         * Takes a wp.customize.HeaderTool.ChoiceList.
     172         *
     173         * @constructor
     174         * @augments wp.Backbone.View
     175         */
     176        api.HeaderTool.ChoiceListView = wp.Backbone.View.extend({
     177                initialize: function() {
     178                        this.listenTo(this.collection, 'add', this.addOne);
     179                        this.listenTo(this.collection, 'remove', this.render);
     180                        this.listenTo(this.collection, 'sort', this.render);
     181                        this.listenTo(this.collection, 'change:hidden', this.toggleTitle);
     182                        this.listenTo(this.collection, 'change:hidden', this.setMaxListHeight);
     183                        this.render();
     184                },
     185
     186                render: function() {
     187                        this.$el.empty();
     188                        this.collection.each(this.addOne, this);
     189                        this.toggleTitle();
     190                },
     191
     192                addOne: function(choice) {
     193                        var view;
     194                        choice.set({ collection: this.collection });
     195                        view = new api.HeaderTool.ChoiceView({ model: choice });
     196                        this.$el.append(view.render().el);
     197                },
     198
     199                toggleTitle: function() {
     200                        var title = this.$el.parents().prev('.customize-control-title');
     201                        if (this.collection.shouldHideTitle()) {
     202                                title.hide();
     203                        } else {
     204                                title.show();
     205                        }
     206                }
     207        });
     208
     209
     210        /**
     211         * wp.customize.HeaderTool.CombinedList
     212         *
     213         * Aggregates wp.customize.HeaderTool.ChoiceList collections (or any
     214         * Backbone object, really) and acts as a bus to feed them events.
     215         *
     216         * @constructor
     217         * @augments wp.Backbone.View
     218         */
     219        api.HeaderTool.CombinedList = wp.Backbone.View.extend({
     220                initialize: function(collections) {
     221                        this.collections = collections;
     222                        this.on('all', this.propagate, this);
     223                },
     224                propagate: function(event, arg) {
     225                        _.each(this.collections, function(collection) {
     226                                collection.trigger(event, arg);
     227                        });
     228                }
     229        });
     230
     231})( jQuery, this.wp, _ );
  • src/wp-includes/js/media-views.js

    diff --git src/wp-includes/js/media-views.js src/wp-includes/js/media-views.js
    index 76f689b..cb6b9da 100644
     
    11/* global _wpMediaViewsL10n, _wpmejsSettings, MediaElementPlayer,
    22        confirm, getUserSetting, setUserSetting */
    3 (function($, _){
     3(function($, _, wp){
    44        var media = wp.media, l10n;
    55
    66        // Link any localized strings.
     
    391391                 * @access private
    392392                 */
    393393                _renderTitle: function( view ) {
    394                         view.$el.text( this.get('title') || '' );
     394                        var title = this.get('title');
     395                        view.$el.html( title.html || title || '' );
    395396                },
    396397                /**
    397398                 * @access private
     
    456457                                priority = this.get('priority');
    457458
    458459                        if ( ! menuItem && title ) {
    459                                 menuItem = { text: title };
     460                                if ( title.text !== undefined ) {
     461                                        menuItem = { text: title.text };
     462                                } else {
     463                                        menuItem = { text: title };
     464                                }
    460465
    461466                                if ( priority ) {
    462467                                        menuItem.priority = priority;
     
    468473                        }
    469474
    470475                        view.set( this.id, menuItem );
    471                 }
     476                        }
    472477        });
    473478
    474479        _.each(['toolbar','content'], function( region ) {
     
    14291434        });
    14301435
    14311436        /**
     1437         * wp.media.controller.Cropper
     1438         *
     1439         * Allows for a cropping step.
     1440         *
     1441         * @constructor
     1442         * @augments wp.media.controller.State
     1443         * @augments Backbone.Model
     1444         */
     1445        media.controller.Cropper = media.controller.State.extend({
     1446                defaults: {
     1447                        id: 'cropper',
     1448                        title: l10n.cropImage,
     1449                        toolbar: 'crop',
     1450                        content: 'crop',
     1451                        router: false,
     1452                        canSkipCrop: false
     1453                },
     1454
     1455                activate: function() {
     1456                        this.frame.on( 'content:create:crop', this.createCropContent, this );
     1457                        this.frame.on( 'close', this.removeCropper, this );
     1458                        this.set('selection', new Backbone.Collection(this.frame._selection.single));
     1459                },
     1460
     1461                deactivate: function() {
     1462                        this.frame.toolbar.mode('browse');
     1463                },
     1464
     1465                createCropContent: function() {
     1466                        this.cropperView = new wp.media.view.Cropper({controller: this,
     1467                                        attachment: this.get('selection').first() });
     1468                        this.cropperView.on('image-loaded', this.createCropToolbar, this);
     1469                        this.frame.content.set(this.cropperView);
     1470
     1471                },
     1472                removeCropper: function() {
     1473                        this.imgSelect.cancelSelection();
     1474                        this.imgSelect.setOptions({remove: true});
     1475                        this.imgSelect.update();
     1476                        this.cropperView.remove();
     1477                },
     1478                createCropToolbar: function() {
     1479                        var canSkipCrop, toolbarOptions;
     1480
     1481                        canSkipCrop = this.get('canSkipCrop') || false;
     1482
     1483                        toolbarOptions = {
     1484                                controller: this.frame,
     1485                                items: {
     1486                                        insert: {
     1487                                                style:    'primary',
     1488                                                text:     l10n.cropImage,
     1489                                                priority: 80,
     1490                                                requires: { library: false, selection: false },
     1491
     1492                                                click: function() {
     1493                                                        var self = this,
     1494                                                                selection = this.controller.state().get('selection').first();
     1495
     1496                                                        selection.set({cropDetails: this.controller.state().imgSelect.getSelection()});
     1497
     1498                                                        this.$el.text(l10n.cropping);
     1499                                                        this.$el.attr('disabled', true);
     1500                                                        this.controller.state().doCrop(selection, function(croppedImage) {
     1501                                                                var img = JSON.parse(croppedImage);
     1502
     1503                                                                self.controller.trigger('cropped', img);
     1504                                                                self.controller.close();
     1505                                                        });
     1506                                                }
     1507                                        }
     1508                                }
     1509                        };
     1510
     1511                        if ( canSkipCrop ) {
     1512                                _.extend( toolbarOptions.items, {
     1513                                        skip: {
     1514                                                style:      'secondary',
     1515                                                text:       l10n.skipCropping,
     1516                                                priority:   70,
     1517                                                requires:   { library: false, selection: false },
     1518                                                click:      function() {
     1519                                                        var selection = this.controller.state().get('selection').first();
     1520                                                        this.controller.state().cropperView.remove();
     1521                                                        this.controller.trigger('skippedcrop', selection);
     1522                                                        this.controller.close();
     1523                                                }
     1524                                        }
     1525                                });
     1526                        }
     1527
     1528                        this.frame.toolbar.set( new wp.media.view.Toolbar(toolbarOptions) );
     1529                },
     1530
     1531                doCrop: function(attachment, callback) {
     1532                        $.post(wp.ajax.settings.url, {
     1533                                dataType: 'json',
     1534                                action: 'header_crop',
     1535                                data: attachment.toJSON()
     1536                        }, callback);
     1537                }
     1538        });
     1539
     1540        /**
    14321541         * ========================================================================
    14331542         * VIEWS
    14341543         * ========================================================================
     
    63356444                }
    63366445        });
    63376446
     6447        /**
     6448         * wp.media.view.Cropper
     6449         *
     6450         * Uses the imgAreaSelect plugin to allow a user to crop an image.
     6451         *
     6452         * Takes imgAreaSelect options from
     6453         * wp.customize.HeaderControl.calculateImageSelectOptions via
     6454         * wp.customize.HeaderControl.openMM.
     6455         *
     6456         * @constructor
     6457         * @augments wp.media.View
     6458         * @augments wp.Backbone.View
     6459         * @augments Backbone.View
     6460         */
     6461        media.view.Cropper = media.View.extend({
     6462                tagName: 'img',
     6463                className: 'crop-content',
     6464                initialize: function() {
     6465                        _.bindAll(this, 'onImageLoad');
     6466                        this.$el.attr('src', this.options.attachment.get('url'));
     6467                },
     6468                ready: function() {
     6469                        this.$el.on('load', this.onImageLoad);
     6470                        $(window).on('resize.cropper', _.debounce(this.onImageLoad, 250));
     6471                },
     6472                remove: function() {
     6473                        $(window).off('resize.cropper');
     6474                        this.$el.remove();
     6475                        this.$el.off();
     6476                        wp.media.View.prototype.remove.apply(this, arguments);
     6477                },
     6478                prepare: function() {
     6479                        return {
     6480                                title: l10n.cropYourImage,
     6481                                url: this.options.attachment.get('url')
     6482                        };
     6483                },
     6484                onImageLoad: function() {
     6485                        var imgOptions = this.controller.frame.options.imgSelectOptions;
     6486                        if (typeof imgOptions === 'function') {
     6487                                imgOptions = imgOptions(this.options.attachment, this.controller);
     6488                        }
     6489                        this.trigger('image-loaded');
     6490                        this.controller.imgSelect = this.$el.imgAreaSelect(imgOptions);
     6491                }
     6492
     6493        });
    63386494
    63396495        media.view.EditImage = media.View.extend({
    63406496
     
    65886744                        return this;
    65896745                }
    65906746        });
    6591 }(jQuery, _));
     6747}(jQuery, _, wp));
  • src/wp-includes/media.php

    diff --git src/wp-includes/media.php src/wp-includes/media.php
    index e62753a..87293ac 100644
    add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' 
    21372137 * @return array Array of attachment details.
    21382138 */
    21392139function wp_prepare_attachment_for_js( $attachment ) {
    2140         if ( ! $attachment = get_post( $attachment ) )
     2140        if ( ! $attachment = get_post( $attachment ) ) {
    21412141                return;
     2142        }
    21422143
    2143         if ( 'attachment' != $attachment->post_type )
     2144        if ( 'attachment' != $attachment->post_type ) {
    21442145                return;
     2146        }
    21452147
    21462148        $meta = wp_get_attachment_metadata( $attachment->ID );
    2147         if ( false !== strpos( $attachment->post_mime_type, '/' ) )
     2149        if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
    21482150                list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
    2149         else
     2151        } else {
    21502152                list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
     2153        }
    21512154
    21522155        $attachment_url = wp_get_attachment_url( $attachment->ID );
    21532156
    function wp_prepare_attachment_for_js( $attachment ) { 
    21732176                'icon'        => wp_mime_type_icon( $attachment->ID ),
    21742177                'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
    21752178                'nonces'      => array(
    2176                         'update' => false,
    2177                         'delete' => false,
    2178                         'edit'   => false
     2179                        'update'  => false,
     2180                        'delete'  => false,
     2181                        'edit'    => false,
     2182                        'crop'    => false,
    21792183                ),
    21802184                'editLink'   => false,
    21812185        );
    function wp_prepare_attachment_for_js( $attachment ) { 
    21862190                $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
    21872191        }
    21882192
    2189         if ( current_user_can( 'delete_post', $attachment->ID ) )
     2193        if ( current_user_can( 'delete_post', $attachment->ID ) ) {
    21902194                $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
     2195        }
     2196
     2197        if ( current_user_can( 'edit_post', $attachment->ID ) ) {
     2198                $response['nonces']['crop'] = wp_create_nonce( 'crop-image_' . $attachment->ID );
     2199        }
    21912200
    21922201        if ( $meta && 'image' === $type ) {
    21932202                $sizes = array();
    function wp_prepare_attachment_for_js( $attachment ) { 
    22152224                                        'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
    22162225                                );
    22172226                        } elseif ( isset( $meta['sizes'][ $size ] ) ) {
    2218                                 if ( ! isset( $base_url ) )
     2227                                if ( ! isset( $base_url ) ) {
    22192228                                        $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
     2229                                }
    22202230
    22212231                                // Nothing from the filter, so consult image metadata if we have it.
    22222232                                $size_meta = $meta['sizes'][ $size ];
    function wp_prepare_attachment_for_js( $attachment ) { 
    22442254
    22452255                $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
    22462256        } elseif ( $meta && 'video' === $type ) {
    2247                 if ( isset( $meta['width'] ) )
     2257                if ( isset( $meta['width'] ) ) {
    22482258                        $response['width'] = (int) $meta['width'];
    2249                 if ( isset( $meta['height'] ) )
     2259                }
     2260                if ( isset( $meta['height'] ) ) {
    22502261                        $response['height'] = (int) $meta['height'];
     2262                }
    22512263        }
    22522264
    22532265        if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
    2254                 if ( isset( $meta['length_formatted'] ) )
     2266                if ( isset( $meta['length_formatted'] ) ) {
    22552267                        $response['fileLength'] = $meta['length_formatted'];
     2268                }
    22562269        }
    22572270
    2258         if ( function_exists('get_compat_media_markup') )
     2271        if ( function_exists('get_compat_media_markup') ) {
    22592272                $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
     2273        }
    22602274
    22612275        return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
    22622276}
    function wp_enqueue_media( $args = array() ) { 
    23852399                'imageDetailsCancel'    => __( 'Cancel Edit' ),
    23862400                'editImage'             => __( 'Edit Image' ),
    23872401
    2388                 // Edit Image
     2402                // Crop Image
     2403                /* translators: title for Media Manager library view */
     2404                'chooseImage' => __( 'Choose Image' ),
     2405                /* translators: button to select an image from the MM library to crop */
     2406                'selectAndCrop' => __( 'Select and Crop' ),
     2407                /* translators: button to choose not to crop the selected image */
     2408                'skipCropping' => __( 'Skip Cropping' ),
     2409                /* translators: button to choose to crop the selected image */
     2410                'cropImage' => __( 'Crop Image' ),
     2411                'cropYourImage' => __( 'Crop your image' ),
     2412                /* translators: button label changes to this while the image is being cropped server-side */
     2413                'cropping' => __( 'Cropping...' ),
     2414                /* translators: suggested width of header image in pixels */
     2415                'suggestedWidth' => __( 'Suggested width is %d pixels.' ),
     2416                /* translators: suggested height of header image in pixels */
     2417                'suggestedHeight' => __( 'Suggested height is %d pixels.' ),
     2418
     2419                // Audio Details
    23892420                'audioDetailsTitle'     => __( 'Audio Details' ),
    23902421                'audioReplaceTitle'     => __( 'Replace Audio' ),
    23912422                'audioDetailsCancel'    => __( 'Cancel Edit' ),
    23922423
    2393                 // Edit Image
     2424                // Video Details
    23942425                'videoDetailsTitle'     => __( 'Video Details' ),
    23952426                'videoReplaceTitle'     => __( 'Replace Video' ),
    23962427                'videoDetailsCancel'    => __( 'Cancel Edit' ),
  • src/wp-includes/script-loader.php

    diff --git src/wp-includes/script-loader.php src/wp-includes/script-loader.php
    index 9c7787f..254bab5 100644
    function wp_default_scripts( &$scripts ) { 
    376376                'allowedFiles' => __( 'Allowed Files' ),
    377377        ) );
    378378
     379        $scripts->add( 'customize-models',  "/wp-includes/js/customize-models.js",  array( 'underscore', 'backbone' ), false, 1 );
     380        $scripts->add( 'customize-views',  "/wp-includes/js/customize-views.js",  array( 'jquery', 'underscore', 'imgareaselect', 'customize-models' ), false, 1 );
     381
    379382        $scripts->add( 'accordion', "/wp-admin/js/accordion$suffix.js", array( 'jquery' ), false, 1 );
    380383
    381384        $scripts->add( 'shortcode', "/wp-includes/js/shortcode$suffix.js", array( 'underscore' ), false, 1 );
    function wp_default_styles( &$styles ) { 
    600603        $styles->add( 'login',              "/wp-admin/css/login$suffix.css", array( 'buttons', 'open-sans', 'dashicons' ) );
    601604        $styles->add( 'install',            "/wp-admin/css/install$suffix.css", array( 'buttons', 'open-sans' ) );
    602605        $styles->add( 'wp-color-picker',    "/wp-admin/css/color-picker$suffix.css" );
    603         $styles->add( 'customize-controls', "/wp-admin/css/customize-controls$suffix.css", array( 'wp-admin', 'colors', 'ie' ) );
     606        $styles->add( 'customize-controls', "/wp-admin/css/customize-controls$suffix.css", array( 'wp-admin', 'colors', 'ie', 'imgareaselect' ) );
    604607        $styles->add( 'ie',                 "/wp-admin/css/ie$suffix.css" );
    605608
    606609        $styles->add_data( 'ie', 'conditional', 'lte IE 7' );
  • new file tests/phpunit/tests/image/header_image.php

    diff --git tests/phpunit/tests/image/header_image.php tests/phpunit/tests/image/header_image.php
    new file mode 100644
    index 0000000..3c76e18
    - +  
     1<?php
     2require_once( ABSPATH . 'wp-admin/custom-header.php');
     3
     4class Test_Header_Image_Cropping extends WP_UnitTestCase {
     5        var $custom_image_header;
     6
     7        function setUp() {
     8                parent::setUp();
     9                $this->custom_image_header = new Custom_Image_Header( 'admin_header_callback_stub' );
     10        }
     11
     12        function admin_header_callback_stub() {}
     13
     14        function test_header_image_has_correct_dimensions_with_max_width() {
     15                global $_wp_theme_features;
     16
     17                $_wp_theme_features['custom-header'][0]['max-width'] = 1600;
     18                $_wp_theme_features['custom-header'][0]['width'] = 1200;
     19                $_wp_theme_features['custom-header'][0]['height'] = 230;
     20                $_wp_theme_features['custom-header'][0]['flex-width'] = false;
     21                $_wp_theme_features['custom-header'][0]['flex-height'] = false;
     22
     23                $dimensions = $this->custom_image_header->get_header_dimensions( array(
     24                        'width' => 1600,
     25                        'height' => 1200,
     26                ) );
     27                $this->assertEquals( $dimensions['dst_width'], 1200);
     28                $this->assertEquals( $dimensions['dst_height'], 230);
     29
     30        }
     31
     32        function test_header_image_has_correct_dimensions_with_fixed() {
     33                global $_wp_theme_features;
     34
     35                unset( $_wp_theme_features['custom-header'][0]['max-width'] );
     36                $_wp_theme_features['custom-header'][0]['width'] = 1200;
     37                $_wp_theme_features['custom-header'][0]['height'] = 230;
     38                $_wp_theme_features['custom-header'][0]['flex-width'] = false;
     39                $_wp_theme_features['custom-header'][0]['flex-height'] = false;
     40
     41                $dimensions = $this->custom_image_header->get_header_dimensions( array(
     42                        'width' => 1600,
     43                        'height' => 1200,
     44                ) );
     45                $this->assertEquals( $dimensions['dst_width'], 1200);
     46                $this->assertEquals( $dimensions['dst_height'], 230);
     47
     48        }
     49
     50        function test_header_image_has_correct_dimensions_with_flex_height() {
     51                global $_wp_theme_features;
     52
     53                unset( $_wp_theme_features['custom-header'][0]['max-width'] );
     54                $_wp_theme_features['custom-header'][0]['width'] = 1200;
     55                $_wp_theme_features['custom-header'][0]['height'] = 230;
     56                $_wp_theme_features['custom-header'][0]['flex-width'] = false;
     57                $_wp_theme_features['custom-header'][0]['flex-height'] = true;
     58
     59                $dimensions = $this->custom_image_header->get_header_dimensions( array(
     60                        'width' => 1600,
     61                        'height' => 1200,
     62                ) );
     63                $this->assertEquals( $dimensions['dst_width'], 1200);
     64                $this->assertEquals( $dimensions['dst_height'], 900);
     65
     66        }
     67
     68        function test_header_image_has_correct_dimensions_with_flex_width() {
     69                global $_wp_theme_features;
     70
     71                unset( $_wp_theme_features['custom-header'][0]['max-width'] );
     72                $_wp_theme_features['custom-header'][0]['width'] = 1200;
     73                $_wp_theme_features['custom-header'][0]['height'] = 230;
     74                $_wp_theme_features['custom-header'][0]['flex-width'] = true;
     75                $_wp_theme_features['custom-header'][0]['flex-height'] = false;
     76
     77                $dimensions = $this->custom_image_header->get_header_dimensions( array(
     78                        'width' => 1600,
     79                        'height' => 1200,
     80                ) );
     81                $this->assertEquals( $dimensions['dst_width'], 1500); // max width
     82                $this->assertEquals( $dimensions['dst_height'], 230);
     83
     84        }
     85
     86        function test_header_image_has_correct_dimensions_with_flex_width_and_height() {
     87                global $_wp_theme_features;
     88
     89                $_wp_theme_features['custom-header'][0]['max-width'] = 1800;
     90                $_wp_theme_features['custom-header'][0]['width'] = 1200;
     91                $_wp_theme_features['custom-header'][0]['height'] = 230;
     92                $_wp_theme_features['custom-header'][0]['flex-width'] = true;
     93                $_wp_theme_features['custom-header'][0]['flex-height'] = true;
     94
     95                $dimensions = $this->custom_image_header->get_header_dimensions( array(
     96                        'width' => 1600,
     97                        'height' => 1200,
     98                ) );
     99                $this->assertEquals( $dimensions['dst_width'], 1600);
     100                $this->assertEquals( $dimensions['dst_height'], 1200);
     101
     102        }
     103
     104        function test_create_attachment_object() {
     105                global $custom_image_header;
     106
     107                $id = wp_insert_attachment( array(
     108                        'post_status' => 'publish',
     109                        'post_title' => 'foo.png',
     110                        'post_type' => 'post',
     111                        'guid' => 'http://localhost/foo.png'
     112                ) );
     113
     114                $cropped = 'http://localhost/foo-cropped.png';
     115
     116                $object = $this->custom_image_header->create_attachment_object( $cropped, $id );
     117                $this->assertEquals( $object['post_title'], 'foo-cropped.png' );
     118                $this->assertEquals( $object['guid'], $cropped );
     119                $this->assertEquals( $object['context'], 'custom-header' );
     120                $this->assertEquals( $object['post_mime_type'], 'image/jpeg' );
     121                $this->assertEquals( $object['post_content'], $cropped );
     122        }
     123
     124        function test_insert_cropped_attachment() {
     125                global $custom_image_header;
     126
     127                $id = wp_insert_attachment( array(
     128                        'post_status' => 'publish',
     129                        'post_title' => 'foo.png',
     130                        'post_type' => 'post',
     131                        'guid' => 'http://localhost/foo.png'
     132                ) );
     133
     134                $cropped = 'http://localhost/foo-cropped.png';
     135                $object = $this->custom_image_header->create_attachment_object( $cropped, $id );
     136
     137                $cropped_id = $this->custom_image_header->insert_attachment( $object, $cropped );
     138
     139                $this->assertInternalType( 'int', $cropped_id );
     140                $this->assertGreaterThan( 0, $cropped_id );
     141        }
     142
     143}
  • new file tests/qunit/fixtures/customize-header.js

    diff --git tests/qunit/fixtures/customize-header.js tests/qunit/fixtures/customize-header.js
    new file mode 100644
    index 0000000..6a1ecc8
    - +  
     1window.wp = window.wp || {};
     2window.wp.customize = window.wp.customize || { get: function(){}  };
     3window._wpCustomizeHeader = {};
     4window._wpCustomizeHeader.uploads = {
     5        "cropped-abstract_00601126.jpg": {
     6                "attachment_id": 1,
     7                "url": "http://dev.local/2013/11/cropped-abstract_00601126.jpg",
     8                "thumbnail_url": "http://dev.local/2013/11/cropped-abstract_00601126.jpg",
     9                "width": 1600,
     10                "height": 230,
     11                "timestamp": 1385045565
     12        },
     13        "cropped-cropped-miniature-golden-retriever-puppies-for-sale01127.jpg": {
     14                "attachment_id": 2,
     15                "url": "http://dev.local/2013/11/cropped-cropped-miniature-golden-retriever-puppies-for-sale01127.jpg",
     16                "thumbnail_url": "http://dev.local/2013/11/cropped-cropped-miniature-golden-retriever-puppies-for-sale01127.jpg",
     17                "width": 1600,
     18                "height": 230,
     19                "timestamp": 1385045566
     20        },
     21        "cropped-tumblr_m20paq9cjn1qbkdcro1_5003.png": {
     22                "attachment_id": 3,
     23                "url": "http://dev.local/2013/11/cropped-tumblr_m20paq9cjn1qbkdcro1_5003.png",
     24                "thumbnail_url": "http://dev.local/2013/11/cropped-tumblr_m20paq9cjn1qbkdcro1_5003.png",
     25                "width": 1600,
     26                "height": 230,
     27                "timestamp": 1385045567
     28        }
     29};
     30window._wpCustomizeHeader.defaults = {
     31        "circle": {
     32                "url": "https://dev.local/wp-content/themes/pub/twentythirteen/images/headers/circle.png",
     33                "thumbnail_url": "https://dev.local/wp-content/themes/pub/twentythirteen/images/headers/circle-thumbnail.png",
     34                "description": "Circle"
     35        },
     36        "diamond": {
     37                "url": "https://dev.local/wp-content/themes/pub/twentythirteen/images/headers/diamond.png",
     38                "thumbnail_url": "https://dev.local/wp-content/themes/pub/twentythirteen/images/headers/diamond-thumbnail.png",
     39                "description": "Diamond"
     40        },
     41        "star": {
     42                "url": "https://dev.local/wp-content/themes/pub/twentythirteen/images/headers/star.png",
     43                "thumbnail_url": "https://dev.local/wp-content/themes/pub/twentythirteen/images/headers/star-thumbnail.png",
     44                "description": "Star"
     45        }
     46};
  • tests/qunit/index.html

    diff --git tests/qunit/index.html tests/qunit/index.html
    index 92a2d75..c4f492d 100644
     
    66  <!-- Dependencies -->
    77  <script src="../../src/wp-includes/js/jquery/jquery.js"></script>
    88  <script src="../../src/wp-includes/js/underscore.min.js"></script>
     9  <script src="../../src/wp-includes/js/backbone.min.js"></script>
    910  <script src="../../src/wp-includes/js/zxcvbn.min.js"></script>
    1011       
    1112  <!-- QUnit -->
    1213  <link rel="stylesheet" href="vendor/qunit.css" type="text/css" media="screen" />
    1314  <script src="vendor/qunit.js"></script>
    14 
    15   <!-- Tested files -->
    16   <script src="../../src/wp-admin/js/password-strength-meter.js"></script>
    17   <script src="../../src/wp-includes/js/shortcode.js"></script>
    18 
    19   <!-- Unit tests -->
    20   <script src="wp-admin/js/password-strength-meter.js"></script>
    21   <script src="wp-includes/js/shortcode.js"></script>
    22 
     15  <script src="vendor/sinon-1.8.2.js"></script>
     16  <script src="vendor/sinon-qunit-1.0.0.js"></script>
    2317</head>
    2418<body>
    2519  <div>
     
    2721    <h2 id="qunit-banner"></h2>
    2822    <h2 id="qunit-userAgent"></h2>
    2923    <ol id="qunit-tests"></ol>
    30     <div id="qunit-fixture"></div>
     24    <div id="qunit-fixture">
     25      <script src="fixtures/customize-header.js"></script>
     26    </div>
    3127    <p><a href="editor">TinyMCE tests</a></p>
     28    <!-- Tested files -->
     29    <script src="../../src/wp-admin/js/password-strength-meter.js"></script>
     30    <script src="../../src/wp-includes/js/customize-models.js"></script>
     31    <script src="../../src/wp-includes/js/shortcode.js"></script>
     32
     33    <!-- Unit tests -->
     34    <script src="wp-admin/js/password-strength-meter.js"></script>
     35    <script src="wp-admin/js/customize-header.js"></script>
     36    <script src="wp-includes/js/shortcode.js"></script>
    3237  </div>
    3338</body>
    3439</html>
  • new file tests/qunit/vendor/sinon-1.8.2.js

    diff --git tests/qunit/vendor/sinon-1.8.2.js tests/qunit/vendor/sinon-1.8.2.js
    new file mode 100644
    index 0000000..27a7ab4
    - +  
     1/**
     2 * Sinon.JS 1.8.2, 2014/02/11
     3 *
     4 * @author Christian Johansen (christian@cjohansen.no)
     5 * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
     6 *
     7 * (The BSD License)
     8 *
     9 * Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no
     10 * All rights reserved.
     11 *
     12 * Redistribution and use in source and binary forms, with or without modification,
     13 * are permitted provided that the following conditions are met:
     14 *
     15 *     * Redistributions of source code must retain the above copyright notice,
     16 *       this list of conditions and the following disclaimer.
     17 *     * Redistributions in binary form must reproduce the above copyright notice,
     18 *       this list of conditions and the following disclaimer in the documentation
     19 *       and/or other materials provided with the distribution.
     20 *     * Neither the name of Christian Johansen nor the names of his contributors
     21 *       may be used to endorse or promote products derived from this software
     22 *       without specific prior written permission.
     23 *
     24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
     25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
     28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     31 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     34 */
     35
     36this.sinon = (function () {
     37var samsam, formatio;
     38function define(mod, deps, fn) { if (mod == "samsam") { samsam = deps(); } else { formatio = fn(samsam); } }
     39define.amd = true;
     40((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) ||
     41 (typeof module === "object" &&
     42      function (m) { module.exports = m(); }) || // Node
     43 function (m) { this.samsam = m(); } // Browser globals
     44)(function () {
     45    var o = Object.prototype;
     46    var div = typeof document !== "undefined" && document.createElement("div");
     47
     48    function isNaN(value) {
     49        // Unlike global isNaN, this avoids type coercion
     50        // typeof check avoids IE host object issues, hat tip to
     51        // lodash
     52        var val = value; // JsLint thinks value !== value is "weird"
     53        return typeof value === "number" && value !== val;
     54    }
     55
     56    function getClass(value) {
     57        // Returns the internal [[Class]] by calling Object.prototype.toString
     58        // with the provided value as this. Return value is a string, naming the
     59        // internal class, e.g. "Array"
     60        return o.toString.call(value).split(/[ \]]/)[1];
     61    }
     62
     63    /**
     64     * @name samsam.isArguments
     65     * @param Object object
     66     *
     67     * Returns ``true`` if ``object`` is an ``arguments`` object,
     68     * ``false`` otherwise.
     69     */
     70    function isArguments(object) {
     71        if (typeof object !== "object" || typeof object.length !== "number" ||
     72                getClass(object) === "Array") {
     73            return false;
     74        }
     75        if (typeof object.callee == "function") { return true; }
     76        try {
     77            object[object.length] = 6;
     78            delete object[object.length];
     79        } catch (e) {
     80            return true;
     81        }
     82        return false;
     83    }
     84
     85    /**
     86     * @name samsam.isElement
     87     * @param Object object
     88     *
     89     * Returns ``true`` if ``object`` is a DOM element node. Unlike
     90     * Underscore.js/lodash, this function will return ``false`` if ``object``
     91     * is an *element-like* object, i.e. a regular object with a ``nodeType``
     92     * property that holds the value ``1``.
     93     */
     94    function isElement(object) {
     95        if (!object || object.nodeType !== 1 || !div) { return false; }
     96        try {
     97            object.appendChild(div);
     98            object.removeChild(div);
     99        } catch (e) {
     100            return false;
     101        }
     102        return true;
     103    }
     104
     105    /**
     106     * @name samsam.keys
     107     * @param Object object
     108     *
     109     * Return an array of own property names.
     110     */
     111    function keys(object) {
     112        var ks = [], prop;
     113        for (prop in object) {
     114            if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); }
     115        }
     116        return ks;
     117    }
     118
     119    /**
     120     * @name samsam.isDate
     121     * @param Object value
     122     *
     123     * Returns true if the object is a ``Date``, or *date-like*. Duck typing
     124     * of date objects work by checking that the object has a ``getTime``
     125     * function whose return value equals the return value from the object's
     126     * ``valueOf``.
     127     */
     128    function isDate(value) {
     129        return typeof value.getTime == "function" &&
     130            value.getTime() == value.valueOf();
     131    }
     132
     133    /**
     134     * @name samsam.isNegZero
     135     * @param Object value
     136     *
     137     * Returns ``true`` if ``value`` is ``-0``.
     138     */
     139    function isNegZero(value) {
     140        return value === 0 && 1 / value === -Infinity;
     141    }
     142
     143    /**
     144     * @name samsam.equal
     145     * @param Object obj1
     146     * @param Object obj2
     147     *
     148     * Returns ``true`` if two objects are strictly equal. Compared to
     149     * ``===`` there are two exceptions:
     150     *
     151     *   - NaN is considered equal to NaN
     152     *   - -0 and +0 are not considered equal
     153     */
     154    function identical(obj1, obj2) {
     155        if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) {
     156            return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2);
     157        }
     158    }
     159
     160
     161    /**
     162     * @name samsam.deepEqual
     163     * @param Object obj1
     164     * @param Object obj2
     165     *
     166     * Deep equal comparison. Two values are "deep equal" if:
     167     *
     168     *   - They are equal, according to samsam.identical
     169     *   - They are both date objects representing the same time
     170     *   - They are both arrays containing elements that are all deepEqual
     171     *   - They are objects with the same set of properties, and each property
     172     *     in ``obj1`` is deepEqual to the corresponding property in ``obj2``
     173     *
     174     * Supports cyclic objects.
     175     */
     176    function deepEqualCyclic(obj1, obj2) {
     177
     178        // used for cyclic comparison
     179        // contain already visited objects
     180        var objects1 = [],
     181            objects2 = [],
     182        // contain pathes (position in the object structure)
     183        // of the already visited objects
     184        // indexes same as in objects arrays
     185            paths1 = [],
     186            paths2 = [],
     187        // contains combinations of already compared objects
     188        // in the manner: { "$1['ref']$2['ref']": true }
     189            compared = {};
     190
     191        /**
     192         * used to check, if the value of a property is an object
     193         * (cyclic logic is only needed for objects)
     194         * only needed for cyclic logic
     195         */
     196        function isObject(value) {
     197
     198            if (typeof value === 'object' && value !== null &&
     199                    !(value instanceof Boolean) &&
     200                    !(value instanceof Date)    &&
     201                    !(value instanceof Number)  &&
     202                    !(value instanceof RegExp)  &&
     203                    !(value instanceof String)) {
     204
     205                return true;
     206            }
     207
     208            return false;
     209        }
     210
     211        /**
     212         * returns the index of the given object in the
     213         * given objects array, -1 if not contained
     214         * only needed for cyclic logic
     215         */
     216        function getIndex(objects, obj) {
     217
     218            var i;
     219            for (i = 0; i < objects.length; i++) {
     220                if (objects[i] === obj) {
     221                    return i;
     222                }
     223            }
     224
     225            return -1;
     226        }
     227
     228        // does the recursion for the deep equal check
     229        return (function deepEqual(obj1, obj2, path1, path2) {
     230            var type1 = typeof obj1;
     231            var type2 = typeof obj2;
     232
     233            // == null also matches undefined
     234            if (obj1 === obj2 ||
     235                    isNaN(obj1) || isNaN(obj2) ||
     236                    obj1 == null || obj2 == null ||
     237                    type1 !== "object" || type2 !== "object") {
     238
     239                return identical(obj1, obj2);
     240            }
     241
     242            // Elements are only equal if identical(expected, actual)
     243            if (isElement(obj1) || isElement(obj2)) { return false; }
     244
     245            var isDate1 = isDate(obj1), isDate2 = isDate(obj2);
     246            if (isDate1 || isDate2) {
     247                if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) {
     248                    return false;
     249                }
     250            }
     251
     252            if (obj1 instanceof RegExp && obj2 instanceof RegExp) {
     253                if (obj1.toString() !== obj2.toString()) { return false; }
     254            }
     255
     256            var class1 = getClass(obj1);
     257            var class2 = getClass(obj2);
     258            var keys1 = keys(obj1);
     259            var keys2 = keys(obj2);
     260
     261            if (isArguments(obj1) || isArguments(obj2)) {
     262                if (obj1.length !== obj2.length) { return false; }
     263            } else {
     264                if (type1 !== type2 || class1 !== class2 ||
     265                        keys1.length !== keys2.length) {
     266                    return false;
     267                }
     268            }
     269
     270            var key, i, l,
     271                // following vars are used for the cyclic logic
     272                value1, value2,
     273                isObject1, isObject2,
     274                index1, index2,
     275                newPath1, newPath2;
     276
     277            for (i = 0, l = keys1.length; i < l; i++) {
     278                key = keys1[i];
     279                if (!o.hasOwnProperty.call(obj2, key)) {
     280                    return false;
     281                }
     282
     283                // Start of the cyclic logic
     284
     285                value1 = obj1[key];
     286                value2 = obj2[key];
     287
     288                isObject1 = isObject(value1);
     289                isObject2 = isObject(value2);
     290
     291                // determine, if the objects were already visited
     292                // (it's faster to check for isObject first, than to
     293                // get -1 from getIndex for non objects)
     294                index1 = isObject1 ? getIndex(objects1, value1) : -1;
     295                index2 = isObject2 ? getIndex(objects2, value2) : -1;
     296
     297                // determine the new pathes of the objects
     298                // - for non cyclic objects the current path will be extended
     299                //   by current property name
     300                // - for cyclic objects the stored path is taken
     301                newPath1 = index1 !== -1
     302                    ? paths1[index1]
     303                    : path1 + '[' + JSON.stringify(key) + ']';
     304                newPath2 = index2 !== -1
     305                    ? paths2[index2]
     306                    : path2 + '[' + JSON.stringify(key) + ']';
     307
     308                // stop recursion if current objects are already compared
     309                if (compared[newPath1 + newPath2]) {
     310                    return true;
     311                }
     312
     313                // remember the current objects and their pathes
     314                if (index1 === -1 && isObject1) {
     315                    objects1.push(value1);
     316                    paths1.push(newPath1);
     317                }
     318                if (index2 === -1 && isObject2) {
     319                    objects2.push(value2);
     320                    paths2.push(newPath2);
     321                }
     322
     323                // remember that the current objects are already compared
     324                if (isObject1 && isObject2) {
     325                    compared[newPath1 + newPath2] = true;
     326                }
     327
     328                // End of cyclic logic
     329
     330                // neither value1 nor value2 is a cycle
     331                // continue with next level
     332                if (!deepEqual(value1, value2, newPath1, newPath2)) {
     333                    return false;
     334                }
     335            }
     336
     337            return true;
     338
     339        }(obj1, obj2, '$1', '$2'));
     340    }
     341
     342    var match;
     343
     344    function arrayContains(array, subset) {
     345        if (subset.length === 0) { return true; }
     346        var i, l, j, k;
     347        for (i = 0, l = array.length; i < l; ++i) {
     348            if (match(array[i], subset[0])) {
     349                for (j = 0, k = subset.length; j < k; ++j) {
     350                    if (!match(array[i + j], subset[j])) { return false; }
     351                }
     352                return true;
     353            }
     354        }
     355        return false;
     356    }
     357
     358    /**
     359     * @name samsam.match
     360     * @param Object object
     361     * @param Object matcher
     362     *
     363     * Compare arbitrary value ``object`` with matcher.
     364     */
     365    match = function match(object, matcher) {
     366        if (matcher && typeof matcher.test === "function") {
     367            return matcher.test(object);
     368        }
     369
     370        if (typeof matcher === "function") {
     371            return matcher(object) === true;
     372        }
     373
     374        if (typeof matcher === "string") {
     375            matcher = matcher.toLowerCase();
     376            var notNull = typeof object === "string" || !!object;
     377            return notNull &&
     378                (String(object)).toLowerCase().indexOf(matcher) >= 0;
     379        }
     380
     381        if (typeof matcher === "number") {
     382            return matcher === object;
     383        }
     384
     385        if (typeof matcher === "boolean") {
     386            return matcher === object;
     387        }
     388
     389        if (getClass(object) === "Array" && getClass(matcher) === "Array") {
     390            return arrayContains(object, matcher);
     391        }
     392
     393        if (matcher && typeof matcher === "object") {
     394            var prop;
     395            for (prop in matcher) {
     396                if (!match(object[prop], matcher[prop])) {
     397                    return false;
     398                }
     399            }
     400            return true;
     401        }
     402
     403        throw new Error("Matcher was not a string, a number, a " +
     404                        "function, a boolean or an object");
     405    };
     406
     407    return {
     408        isArguments: isArguments,
     409        isElement: isElement,
     410        isDate: isDate,
     411        isNegZero: isNegZero,
     412        identical: identical,
     413        deepEqual: deepEqualCyclic,
     414        match: match,
     415        keys: keys
     416    };
     417});
     418((typeof define === "function" && define.amd && function (m) {
     419    define("formatio", ["samsam"], m);
     420}) || (typeof module === "object" && function (m) {
     421    module.exports = m(require("samsam"));
     422}) || function (m) { this.formatio = m(this.samsam); }
     423)(function (samsam) {
     424   
     425    var formatio = {
     426        excludeConstructors: ["Object", /^.$/],
     427        quoteStrings: true
     428    };
     429
     430    var hasOwn = Object.prototype.hasOwnProperty;
     431
     432    var specialObjects = [];
     433    if (typeof global !== "undefined") {
     434        specialObjects.push({ object: global, value: "[object global]" });
     435    }
     436    if (typeof document !== "undefined") {
     437        specialObjects.push({
     438            object: document,
     439            value: "[object HTMLDocument]"
     440        });
     441    }
     442    if (typeof window !== "undefined") {
     443        specialObjects.push({ object: window, value: "[object Window]" });
     444    }
     445
     446    function functionName(func) {
     447        if (!func) { return ""; }
     448        if (func.displayName) { return func.displayName; }
     449        if (func.name) { return func.name; }
     450        var matches = func.toString().match(/function\s+([^\(]+)/m);
     451        return (matches && matches[1]) || "";
     452    }
     453
     454    function constructorName(f, object) {
     455        var name = functionName(object && object.constructor);
     456        var excludes = f.excludeConstructors ||
     457                formatio.excludeConstructors || [];
     458
     459        var i, l;
     460        for (i = 0, l = excludes.length; i < l; ++i) {
     461            if (typeof excludes[i] === "string" && excludes[i] === name) {
     462                return "";
     463            } else if (excludes[i].test && excludes[i].test(name)) {
     464                return "";
     465            }
     466        }
     467
     468        return name;
     469    }
     470
     471    function isCircular(object, objects) {
     472        if (typeof object !== "object") { return false; }
     473        var i, l;
     474        for (i = 0, l = objects.length; i < l; ++i) {
     475            if (objects[i] === object) { return true; }
     476        }
     477        return false;
     478    }
     479
     480    function ascii(f, object, processed, indent) {
     481        if (typeof object === "string") {
     482            var qs = f.quoteStrings;
     483            var quote = typeof qs !== "boolean" || qs;
     484            return processed || quote ? '"' + object + '"' : object;
     485        }
     486
     487        if (typeof object === "function" && !(object instanceof RegExp)) {
     488            return ascii.func(object);
     489        }
     490
     491        processed = processed || [];
     492
     493        if (isCircular(object, processed)) { return "[Circular]"; }
     494
     495        if (Object.prototype.toString.call(object) === "[object Array]") {
     496            return ascii.array.call(f, object, processed);
     497        }
     498
     499        if (!object) { return String((1/object) === -Infinity ? "-0" : object); }
     500        if (samsam.isElement(object)) { return ascii.element(object); }
     501
     502        if (typeof object.toString === "function" &&
     503                object.toString !== Object.prototype.toString) {
     504            return object.toString();
     505        }
     506
     507        var i, l;
     508        for (i = 0, l = specialObjects.length; i < l; i++) {
     509            if (object === specialObjects[i].object) {
     510                return specialObjects[i].value;
     511            }
     512        }
     513
     514        return ascii.object.call(f, object, processed, indent);
     515    }
     516
     517    ascii.func = function (func) {
     518        return "function " + functionName(func) + "() {}";
     519    };
     520
     521    ascii.array = function (array, processed) {
     522        processed = processed || [];
     523        processed.push(array);
     524        var i, l, pieces = [];
     525        for (i = 0, l = array.length; i < l; ++i) {
     526            pieces.push(ascii(this, array[i], processed));
     527        }
     528        return "[" + pieces.join(", ") + "]";
     529    };
     530
     531    ascii.object = function (object, processed, indent) {
     532        processed = processed || [];
     533        processed.push(object);
     534        indent = indent || 0;
     535        var pieces = [], properties = samsam.keys(object).sort();
     536        var length = 3;
     537        var prop, str, obj, i, l;
     538
     539        for (i = 0, l = properties.length; i < l; ++i) {
     540            prop = properties[i];
     541            obj = object[prop];
     542
     543            if (isCircular(obj, processed)) {
     544                str = "[Circular]";
     545            } else {
     546                str = ascii(this, obj, processed, indent + 2);
     547            }
     548
     549            str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
     550            length += str.length;
     551            pieces.push(str);
     552        }
     553
     554        var cons = constructorName(this, object);
     555        var prefix = cons ? "[" + cons + "] " : "";
     556        var is = "";
     557        for (i = 0, l = indent; i < l; ++i) { is += " "; }
     558
     559        if (length + indent > 80) {
     560            return prefix + "{\n  " + is + pieces.join(",\n  " + is) + "\n" +
     561                is + "}";
     562        }
     563        return prefix + "{ " + pieces.join(", ") + " }";
     564    };
     565
     566    ascii.element = function (element) {
     567        var tagName = element.tagName.toLowerCase();
     568        var attrs = element.attributes, attr, pairs = [], attrName, i, l, val;
     569
     570        for (i = 0, l = attrs.length; i < l; ++i) {
     571            attr = attrs.item(i);
     572            attrName = attr.nodeName.toLowerCase().replace("html:", "");
     573            val = attr.nodeValue;
     574            if (attrName !== "contenteditable" || val !== "inherit") {
     575                if (!!val) { pairs.push(attrName + "=\"" + val + "\""); }
     576            }
     577        }
     578
     579        var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
     580        var content = element.innerHTML;
     581
     582        if (content.length > 20) {
     583            content = content.substr(0, 20) + "[...]";
     584        }
     585
     586        var res = formatted + pairs.join(" ") + ">" + content +
     587                "</" + tagName + ">";
     588
     589        return res.replace(/ contentEditable="inherit"/, "");
     590    };
     591
     592    function Formatio(options) {
     593        for (var opt in options) {
     594            this[opt] = options[opt];
     595        }
     596    }
     597
     598    Formatio.prototype = {
     599        functionName: functionName,
     600
     601        configure: function (options) {
     602            return new Formatio(options);
     603        },
     604
     605        constructorName: function (object) {
     606            return constructorName(this, object);
     607        },
     608
     609        ascii: function (object, processed, indent) {
     610            return ascii(this, object, processed, indent);
     611        }
     612    };
     613
     614    return Formatio.prototype;
     615});
     616/*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
     617/*global module, require, __dirname, document*/
     618/**
     619 * Sinon core utilities. For internal use only.
     620 *
     621 * @author Christian Johansen (christian@cjohansen.no)
     622 * @license BSD
     623 *
     624 * Copyright (c) 2010-2013 Christian Johansen
     625 */
     626
     627var sinon = (function (formatio) {
     628    var div = typeof document != "undefined" && document.createElement("div");
     629    var hasOwn = Object.prototype.hasOwnProperty;
     630
     631    function isDOMNode(obj) {
     632        var success = false;
     633
     634        try {
     635            obj.appendChild(div);
     636            success = div.parentNode == obj;
     637        } catch (e) {
     638            return false;
     639        } finally {
     640            try {
     641                obj.removeChild(div);
     642            } catch (e) {
     643                // Remove failed, not much we can do about that
     644            }
     645        }
     646
     647        return success;
     648    }
     649
     650    function isElement(obj) {
     651        return div && obj && obj.nodeType === 1 && isDOMNode(obj);
     652    }
     653
     654    function isFunction(obj) {
     655        return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
     656    }
     657
     658    function mirrorProperties(target, source) {
     659        for (var prop in source) {
     660            if (!hasOwn.call(target, prop)) {
     661                target[prop] = source[prop];
     662            }
     663        }
     664    }
     665
     666    function isRestorable (obj) {
     667        return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
     668    }
     669
     670    var sinon = {
     671        wrapMethod: function wrapMethod(object, property, method) {
     672            if (!object) {
     673                throw new TypeError("Should wrap property of object");
     674            }
     675
     676            if (typeof method != "function") {
     677                throw new TypeError("Method wrapper should be function");
     678            }
     679
     680            var wrappedMethod = object[property],
     681                error;
     682
     683            if (!isFunction(wrappedMethod)) {
     684                error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
     685                                    property + " as function");
     686            }
     687
     688            if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
     689                error = new TypeError("Attempted to wrap " + property + " which is already wrapped");
     690            }
     691
     692            if (wrappedMethod.calledBefore) {
     693                var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
     694                error = new TypeError("Attempted to wrap " + property + " which is already " + verb);
     695            }
     696
     697            if (error) {
     698                if (wrappedMethod._stack) {
     699                    error.stack += '\n--------------\n' + wrappedMethod._stack;
     700                }
     701                throw error;
     702            }
     703
     704            // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem
     705            // when using hasOwn.call on objects from other frames.
     706            var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property);
     707            object[property] = method;
     708            method.displayName = property;
     709            // Set up a stack trace which can be used later to find what line of
     710            // code the original method was created on.
     711            method._stack = (new Error('Stack Trace for original')).stack;
     712
     713            method.restore = function () {
     714                // For prototype properties try to reset by delete first.
     715                // If this fails (ex: localStorage on mobile safari) then force a reset
     716                // via direct assignment.
     717                if (!owned) {
     718                    delete object[property];
     719                }
     720                if (object[property] === method) {
     721                    object[property] = wrappedMethod;
     722                }
     723            };
     724
     725            method.restore.sinon = true;
     726            mirrorProperties(method, wrappedMethod);
     727
     728            return method;
     729        },
     730
     731        extend: function extend(target) {
     732            for (var i = 1, l = arguments.length; i < l; i += 1) {
     733                for (var prop in arguments[i]) {
     734                    if (arguments[i].hasOwnProperty(prop)) {
     735                        target[prop] = arguments[i][prop];
     736                    }
     737
     738                    // DONT ENUM bug, only care about toString
     739                    if (arguments[i].hasOwnProperty("toString") &&
     740                        arguments[i].toString != target.toString) {
     741                        target.toString = arguments[i].toString;
     742                    }
     743                }
     744            }
     745
     746            return target;
     747        },
     748
     749        create: function create(proto) {
     750            var F = function () {};
     751            F.prototype = proto;
     752            return new F();
     753        },
     754
     755        deepEqual: function deepEqual(a, b) {
     756            if (sinon.match && sinon.match.isMatcher(a)) {
     757                return a.test(b);
     758            }
     759            if (typeof a != "object" || typeof b != "object") {
     760                return a === b;
     761            }
     762
     763            if (isElement(a) || isElement(b)) {
     764                return a === b;
     765            }
     766
     767            if (a === b) {
     768                return true;
     769            }
     770
     771            if ((a === null && b !== null) || (a !== null && b === null)) {
     772                return false;
     773            }
     774
     775            var aString = Object.prototype.toString.call(a);
     776            if (aString != Object.prototype.toString.call(b)) {
     777                return false;
     778            }
     779
     780            if (aString == "[object Date]") {
     781                return a.valueOf() === b.valueOf();
     782            }
     783
     784            var prop, aLength = 0, bLength = 0;
     785
     786            if (aString == "[object Array]" && a.length !== b.length) {
     787                return false;
     788            }
     789
     790            for (prop in a) {
     791                aLength += 1;
     792
     793                if (!deepEqual(a[prop], b[prop])) {
     794                    return false;
     795                }
     796            }
     797
     798            for (prop in b) {
     799                bLength += 1;
     800            }
     801
     802            return aLength == bLength;
     803        },
     804
     805        functionName: function functionName(func) {
     806            var name = func.displayName || func.name;
     807
     808            // Use function decomposition as a last resort to get function
     809            // name. Does not rely on function decomposition to work - if it
     810            // doesn't debugging will be slightly less informative
     811            // (i.e. toString will say 'spy' rather than 'myFunc').
     812            if (!name) {
     813                var matches = func.toString().match(/function ([^\s\(]+)/);
     814                name = matches && matches[1];
     815            }
     816
     817            return name;
     818        },
     819
     820        functionToString: function toString() {
     821            if (this.getCall && this.callCount) {
     822                var thisValue, prop, i = this.callCount;
     823
     824                while (i--) {
     825                    thisValue = this.getCall(i).thisValue;
     826
     827                    for (prop in thisValue) {
     828                        if (thisValue[prop] === this) {
     829                            return prop;
     830                        }
     831                    }
     832                }
     833            }
     834
     835            return this.displayName || "sinon fake";
     836        },
     837
     838        getConfig: function (custom) {
     839            var config = {};
     840            custom = custom || {};
     841            var defaults = sinon.defaultConfig;
     842
     843            for (var prop in defaults) {
     844                if (defaults.hasOwnProperty(prop)) {
     845                    config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
     846                }
     847            }
     848
     849            return config;
     850        },
     851
     852        format: function (val) {
     853            return "" + val;
     854        },
     855
     856        defaultConfig: {
     857            injectIntoThis: true,
     858            injectInto: null,
     859            properties: ["spy", "stub", "mock", "clock", "server", "requests"],
     860            useFakeTimers: true,
     861            useFakeServer: true
     862        },
     863
     864        timesInWords: function timesInWords(count) {
     865            return count == 1 && "once" ||
     866                count == 2 && "twice" ||
     867                count == 3 && "thrice" ||
     868                (count || 0) + " times";
     869        },
     870
     871        calledInOrder: function (spies) {
     872            for (var i = 1, l = spies.length; i < l; i++) {
     873                if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
     874                    return false;
     875                }
     876            }
     877
     878            return true;
     879        },
     880
     881        orderByFirstCall: function (spies) {
     882            return spies.sort(function (a, b) {
     883                // uuid, won't ever be equal
     884                var aCall = a.getCall(0);
     885                var bCall = b.getCall(0);
     886                var aId = aCall && aCall.callId || -1;
     887                var bId = bCall && bCall.callId || -1;
     888
     889                return aId < bId ? -1 : 1;
     890            });
     891        },
     892
     893        log: function () {},
     894
     895        logError: function (label, err) {
     896            var msg = label + " threw exception: ";
     897            sinon.log(msg + "[" + err.name + "] " + err.message);
     898            if (err.stack) { sinon.log(err.stack); }
     899
     900            setTimeout(function () {
     901                err.message = msg + err.message;
     902                throw err;
     903            }, 0);
     904        },
     905
     906        typeOf: function (value) {
     907            if (value === null) {
     908                return "null";
     909            }
     910            else if (value === undefined) {
     911                return "undefined";
     912            }
     913            var string = Object.prototype.toString.call(value);
     914            return string.substring(8, string.length - 1).toLowerCase();
     915        },
     916
     917        createStubInstance: function (constructor) {
     918            if (typeof constructor !== "function") {
     919                throw new TypeError("The constructor should be a function.");
     920            }
     921            return sinon.stub(sinon.create(constructor.prototype));
     922        },
     923
     924        restore: function (object) {
     925            if (object !== null && typeof object === "object") {
     926                for (var prop in object) {
     927                    if (isRestorable(object[prop])) {
     928                        object[prop].restore();
     929                    }
     930                }
     931            }
     932            else if (isRestorable(object)) {
     933                object.restore();
     934            }
     935        }
     936    };
     937
     938    var isNode = typeof module !== "undefined" && module.exports;
     939    var isAMD = typeof define === 'function' && typeof define.amd === 'object' && define.amd;
     940
     941    if (isAMD) {
     942        define(function(){
     943            return sinon;
     944        });
     945    } else if (isNode) {
     946        try {
     947            formatio = require("formatio");
     948        } catch (e) {}
     949        module.exports = sinon;
     950        module.exports.spy = require("./sinon/spy");
     951        module.exports.spyCall = require("./sinon/call");
     952        module.exports.behavior = require("./sinon/behavior");
     953        module.exports.stub = require("./sinon/stub");
     954        module.exports.mock = require("./sinon/mock");
     955        module.exports.collection = require("./sinon/collection");
     956        module.exports.assert = require("./sinon/assert");
     957        module.exports.sandbox = require("./sinon/sandbox");
     958        module.exports.test = require("./sinon/test");
     959        module.exports.testCase = require("./sinon/test_case");
     960        module.exports.assert = require("./sinon/assert");
     961        module.exports.match = require("./sinon/match");
     962    }
     963
     964    if (formatio) {
     965        var formatter = formatio.configure({ quoteStrings: false });
     966        sinon.format = function () {
     967            return formatter.ascii.apply(formatter, arguments);
     968        };
     969    } else if (isNode) {
     970        try {
     971            var util = require("util");
     972            sinon.format = function (value) {
     973                return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
     974            };
     975        } catch (e) {
     976            /* Node, but no util module - would be very old, but better safe than
     977             sorry */
     978        }
     979    }
     980
     981    return sinon;
     982}(typeof formatio == "object" && formatio));
     983
     984/* @depend ../sinon.js */
     985/*jslint eqeqeq: false, onevar: false, plusplus: false*/
     986/*global module, require, sinon*/
     987/**
     988 * Match functions
     989 *
     990 * @author Maximilian Antoni (mail@maxantoni.de)
     991 * @license BSD
     992 *
     993 * Copyright (c) 2012 Maximilian Antoni
     994 */
     995
     996(function (sinon) {
     997    var commonJSModule = typeof module !== 'undefined' && module.exports;
     998
     999    if (!sinon && commonJSModule) {
     1000        sinon = require("../sinon");
     1001    }
     1002
     1003    if (!sinon) {
     1004        return;
     1005    }
     1006
     1007    function assertType(value, type, name) {
     1008        var actual = sinon.typeOf(value);
     1009        if (actual !== type) {
     1010            throw new TypeError("Expected type of " + name + " to be " +
     1011                type + ", but was " + actual);
     1012        }
     1013    }
     1014
     1015    var matcher = {
     1016        toString: function () {
     1017            return this.message;
     1018        }
     1019    };
     1020
     1021    function isMatcher(object) {
     1022        return matcher.isPrototypeOf(object);
     1023    }
     1024
     1025    function matchObject(expectation, actual) {
     1026        if (actual === null || actual === undefined) {
     1027            return false;
     1028        }
     1029        for (var key in expectation) {
     1030            if (expectation.hasOwnProperty(key)) {
     1031                var exp = expectation[key];
     1032                var act = actual[key];
     1033                if (match.isMatcher(exp)) {
     1034                    if (!exp.test(act)) {
     1035                        return false;
     1036                    }
     1037                } else if (sinon.typeOf(exp) === "object") {
     1038                    if (!matchObject(exp, act)) {
     1039                        return false;
     1040                    }
     1041                } else if (!sinon.deepEqual(exp, act)) {
     1042                    return false;
     1043                }
     1044            }
     1045        }
     1046        return true;
     1047    }
     1048
     1049    matcher.or = function (m2) {
     1050        if (!isMatcher(m2)) {
     1051            throw new TypeError("Matcher expected");
     1052        }
     1053        var m1 = this;
     1054        var or = sinon.create(matcher);
     1055        or.test = function (actual) {
     1056            return m1.test(actual) || m2.test(actual);
     1057        };
     1058        or.message = m1.message + ".or(" + m2.message + ")";
     1059        return or;
     1060    };
     1061
     1062    matcher.and = function (m2) {
     1063        if (!isMatcher(m2)) {
     1064            throw new TypeError("Matcher expected");
     1065        }
     1066        var m1 = this;
     1067        var and = sinon.create(matcher);
     1068        and.test = function (actual) {
     1069            return m1.test(actual) && m2.test(actual);
     1070        };
     1071        and.message = m1.message + ".and(" + m2.message + ")";
     1072        return and;
     1073    };
     1074
     1075    var match = function (expectation, message) {
     1076        var m = sinon.create(matcher);
     1077        var type = sinon.typeOf(expectation);
     1078        switch (type) {
     1079        case "object":
     1080            if (typeof expectation.test === "function") {
     1081                m.test = function (actual) {
     1082                    return expectation.test(actual) === true;
     1083                };
     1084                m.message = "match(" + sinon.functionName(expectation.test) + ")";
     1085                return m;
     1086            }
     1087            var str = [];
     1088            for (var key in expectation) {
     1089                if (expectation.hasOwnProperty(key)) {
     1090                    str.push(key + ": " + expectation[key]);
     1091                }
     1092            }
     1093            m.test = function (actual) {
     1094                return matchObject(expectation, actual);
     1095            };
     1096            m.message = "match(" + str.join(", ") + ")";
     1097            break;
     1098        case "number":
     1099            m.test = function (actual) {
     1100                return expectation == actual;
     1101            };
     1102            break;
     1103        case "string":
     1104            m.test = function (actual) {
     1105                if (typeof actual !== "string") {
     1106                    return false;
     1107                }
     1108                return actual.indexOf(expectation) !== -1;
     1109            };
     1110            m.message = "match(\"" + expectation + "\")";
     1111            break;
     1112        case "regexp":
     1113            m.test = function (actual) {
     1114                if (typeof actual !== "string") {
     1115                    return false;
     1116                }
     1117                return expectation.test(actual);
     1118            };
     1119            break;
     1120        case "function":
     1121            m.test = expectation;
     1122            if (message) {
     1123                m.message = message;
     1124            } else {
     1125                m.message = "match(" + sinon.functionName(expectation) + ")";
     1126            }
     1127            break;
     1128        default:
     1129            m.test = function (actual) {
     1130              return sinon.deepEqual(expectation, actual);
     1131            };
     1132        }
     1133        if (!m.message) {
     1134            m.message = "match(" + expectation + ")";
     1135        }
     1136        return m;
     1137    };
     1138
     1139    match.isMatcher = isMatcher;
     1140
     1141    match.any = match(function () {
     1142        return true;
     1143    }, "any");
     1144
     1145    match.defined = match(function (actual) {
     1146        return actual !== null && actual !== undefined;
     1147    }, "defined");
     1148
     1149    match.truthy = match(function (actual) {
     1150        return !!actual;
     1151    }, "truthy");
     1152
     1153    match.falsy = match(function (actual) {
     1154        return !actual;
     1155    }, "falsy");
     1156
     1157    match.same = function (expectation) {
     1158        return match(function (actual) {
     1159            return expectation === actual;
     1160        }, "same(" + expectation + ")");
     1161    };
     1162
     1163    match.typeOf = function (type) {
     1164        assertType(type, "string", "type");
     1165        return match(function (actual) {
     1166            return sinon.typeOf(actual) === type;
     1167        }, "typeOf(\"" + type + "\")");
     1168    };
     1169
     1170    match.instanceOf = function (type) {
     1171        assertType(type, "function", "type");
     1172        return match(function (actual) {
     1173            return actual instanceof type;
     1174        }, "instanceOf(" + sinon.functionName(type) + ")");
     1175    };
     1176
     1177    function createPropertyMatcher(propertyTest, messagePrefix) {
     1178        return function (property, value) {
     1179            assertType(property, "string", "property");
     1180            var onlyProperty = arguments.length === 1;
     1181            var message = messagePrefix + "(\"" + property + "\"";
     1182            if (!onlyProperty) {
     1183                message += ", " + value;
     1184            }
     1185            message += ")";
     1186            return match(function (actual) {
     1187                if (actual === undefined || actual === null ||
     1188                        !propertyTest(actual, property)) {
     1189                    return false;
     1190                }
     1191                return onlyProperty || sinon.deepEqual(value, actual[property]);
     1192            }, message);
     1193        };
     1194    }
     1195
     1196    match.has = createPropertyMatcher(function (actual, property) {
     1197        if (typeof actual === "object") {
     1198            return property in actual;
     1199        }
     1200        return actual[property] !== undefined;
     1201    }, "has");
     1202
     1203    match.hasOwn = createPropertyMatcher(function (actual, property) {
     1204        return actual.hasOwnProperty(property);
     1205    }, "hasOwn");
     1206
     1207    match.bool = match.typeOf("boolean");
     1208    match.number = match.typeOf("number");
     1209    match.string = match.typeOf("string");
     1210    match.object = match.typeOf("object");
     1211    match.func = match.typeOf("function");
     1212    match.array = match.typeOf("array");
     1213    match.regexp = match.typeOf("regexp");
     1214    match.date = match.typeOf("date");
     1215
     1216    if (commonJSModule) {
     1217        module.exports = match;
     1218    } else {
     1219        sinon.match = match;
     1220    }
     1221}(typeof sinon == "object" && sinon || null));
     1222
     1223/**
     1224  * @depend ../sinon.js
     1225  * @depend match.js
     1226  */
     1227/*jslint eqeqeq: false, onevar: false, plusplus: false*/
     1228/*global module, require, sinon*/
     1229/**
     1230  * Spy calls
     1231  *
     1232  * @author Christian Johansen (christian@cjohansen.no)
     1233  * @author Maximilian Antoni (mail@maxantoni.de)
     1234  * @license BSD
     1235  *
     1236  * Copyright (c) 2010-2013 Christian Johansen
     1237  * Copyright (c) 2013 Maximilian Antoni
     1238  */
     1239
     1240(function (sinon) {
     1241    var commonJSModule = typeof module !== 'undefined' && module.exports;
     1242    if (!sinon && commonJSModule) {
     1243        sinon = require("../sinon");
     1244    }
     1245
     1246    if (!sinon) {
     1247        return;
     1248    }
     1249
     1250    function throwYieldError(proxy, text, args) {
     1251        var msg = sinon.functionName(proxy) + text;
     1252        if (args.length) {
     1253            msg += " Received [" + slice.call(args).join(", ") + "]";
     1254        }
     1255        throw new Error(msg);
     1256    }
     1257
     1258    var slice = Array.prototype.slice;
     1259
     1260    var callProto = {
     1261        calledOn: function calledOn(thisValue) {
     1262            if (sinon.match && sinon.match.isMatcher(thisValue)) {
     1263                return thisValue.test(this.thisValue);
     1264            }
     1265            return this.thisValue === thisValue;
     1266        },
     1267
     1268        calledWith: function calledWith() {
     1269            for (var i = 0, l = arguments.length; i < l; i += 1) {
     1270                if (!sinon.deepEqual(arguments[i], this.args[i])) {
     1271                    return false;
     1272                }
     1273            }
     1274
     1275            return true;
     1276        },
     1277
     1278        calledWithMatch: function calledWithMatch() {
     1279            for (var i = 0, l = arguments.length; i < l; i += 1) {
     1280                var actual = this.args[i];
     1281                var expectation = arguments[i];
     1282                if (!sinon.match || !sinon.match(expectation).test(actual)) {
     1283                    return false;
     1284                }
     1285            }
     1286            return true;
     1287        },
     1288
     1289        calledWithExactly: function calledWithExactly() {
     1290            return arguments.length == this.args.length &&
     1291                this.calledWith.apply(this, arguments);
     1292        },
     1293
     1294        notCalledWith: function notCalledWith() {
     1295            return !this.calledWith.apply(this, arguments);
     1296        },
     1297
     1298        notCalledWithMatch: function notCalledWithMatch() {
     1299            return !this.calledWithMatch.apply(this, arguments);
     1300        },
     1301
     1302        returned: function returned(value) {
     1303            return sinon.deepEqual(value, this.returnValue);
     1304        },
     1305
     1306        threw: function threw(error) {
     1307            if (typeof error === "undefined" || !this.exception) {
     1308                return !!this.exception;
     1309            }
     1310
     1311            return this.exception === error || this.exception.name === error;
     1312        },
     1313
     1314        calledWithNew: function calledWithNew() {
     1315            return this.proxy.prototype && this.thisValue instanceof this.proxy;
     1316        },
     1317
     1318        calledBefore: function (other) {
     1319            return this.callId < other.callId;
     1320        },
     1321
     1322        calledAfter: function (other) {
     1323            return this.callId > other.callId;
     1324        },
     1325
     1326        callArg: function (pos) {
     1327            this.args[pos]();
     1328        },
     1329
     1330        callArgOn: function (pos, thisValue) {
     1331            this.args[pos].apply(thisValue);
     1332        },
     1333
     1334        callArgWith: function (pos) {
     1335            this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
     1336        },
     1337
     1338        callArgOnWith: function (pos, thisValue) {
     1339            var args = slice.call(arguments, 2);
     1340            this.args[pos].apply(thisValue, args);
     1341        },
     1342
     1343        "yield": function () {
     1344            this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
     1345        },
     1346
     1347        yieldOn: function (thisValue) {
     1348            var args = this.args;
     1349            for (var i = 0, l = args.length; i < l; ++i) {
     1350                if (typeof args[i] === "function") {
     1351                    args[i].apply(thisValue, slice.call(arguments, 1));
     1352                    return;
     1353                }
     1354            }
     1355            throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
     1356        },
     1357
     1358        yieldTo: function (prop) {
     1359            this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
     1360        },
     1361
     1362        yieldToOn: function (prop, thisValue) {
     1363            var args = this.args;
     1364            for (var i = 0, l = args.length; i < l; ++i) {
     1365                if (args[i] && typeof args[i][prop] === "function") {
     1366                    args[i][prop].apply(thisValue, slice.call(arguments, 2));
     1367                    return;
     1368                }
     1369            }
     1370            throwYieldError(this.proxy, " cannot yield to '" + prop +
     1371                "' since no callback was passed.", args);
     1372        },
     1373
     1374        toString: function () {
     1375            var callStr = this.proxy.toString() + "(";
     1376            var args = [];
     1377
     1378            for (var i = 0, l = this.args.length; i < l; ++i) {
     1379                args.push(sinon.format(this.args[i]));
     1380            }
     1381
     1382            callStr = callStr + args.join(", ") + ")";
     1383
     1384            if (typeof this.returnValue != "undefined") {
     1385                callStr += " => " + sinon.format(this.returnValue);
     1386            }
     1387
     1388            if (this.exception) {
     1389                callStr += " !" + this.exception.name;
     1390
     1391                if (this.exception.message) {
     1392                    callStr += "(" + this.exception.message + ")";
     1393                }
     1394            }
     1395
     1396            return callStr;
     1397        }
     1398    };
     1399
     1400    callProto.invokeCallback = callProto.yield;
     1401
     1402    function createSpyCall(spy, thisValue, args, returnValue, exception, id) {
     1403        if (typeof id !== "number") {
     1404            throw new TypeError("Call id is not a number");
     1405        }
     1406        var proxyCall = sinon.create(callProto);
     1407        proxyCall.proxy = spy;
     1408        proxyCall.thisValue = thisValue;
     1409        proxyCall.args = args;
     1410        proxyCall.returnValue = returnValue;
     1411        proxyCall.exception = exception;
     1412        proxyCall.callId = id;
     1413
     1414        return proxyCall;
     1415    }
     1416    createSpyCall.toString = callProto.toString; // used by mocks
     1417
     1418    if (commonJSModule) {
     1419        module.exports = createSpyCall;
     1420    } else {
     1421        sinon.spyCall = createSpyCall;
     1422    }
     1423}(typeof sinon == "object" && sinon || null));
     1424
     1425
     1426/**
     1427  * @depend ../sinon.js
     1428  * @depend call.js
     1429  */
     1430/*jslint eqeqeq: false, onevar: false, plusplus: false*/
     1431/*global module, require, sinon*/
     1432/**
     1433  * Spy functions
     1434  *
     1435  * @author Christian Johansen (christian@cjohansen.no)
     1436  * @license BSD
     1437  *
     1438  * Copyright (c) 2010-2013 Christian Johansen
     1439  */
     1440
     1441(function (sinon) {
     1442    var commonJSModule = typeof module !== 'undefined' && module.exports;
     1443    var push = Array.prototype.push;
     1444    var slice = Array.prototype.slice;
     1445    var callId = 0;
     1446
     1447    if (!sinon && commonJSModule) {
     1448        sinon = require("../sinon");
     1449    }
     1450
     1451    if (!sinon) {
     1452        return;
     1453    }
     1454
     1455    function spy(object, property) {
     1456        if (!property && typeof object == "function") {
     1457            return spy.create(object);
     1458        }
     1459
     1460        if (!object && !property) {
     1461            return spy.create(function () { });
     1462        }
     1463
     1464        var method = object[property];
     1465        return sinon.wrapMethod(object, property, spy.create(method));
     1466    }
     1467
     1468    function matchingFake(fakes, args, strict) {
     1469        if (!fakes) {
     1470            return;
     1471        }
     1472
     1473        for (var i = 0, l = fakes.length; i < l; i++) {
     1474            if (fakes[i].matches(args, strict)) {
     1475                return fakes[i];
     1476            }
     1477        }
     1478    }
     1479
     1480    function incrementCallCount() {
     1481        this.called = true;
     1482        this.callCount += 1;
     1483        this.notCalled = false;
     1484        this.calledOnce = this.callCount == 1;
     1485        this.calledTwice = this.callCount == 2;
     1486        this.calledThrice = this.callCount == 3;
     1487    }
     1488
     1489    function createCallProperties() {
     1490        this.firstCall = this.getCall(0);
     1491        this.secondCall = this.getCall(1);
     1492        this.thirdCall = this.getCall(2);
     1493        this.lastCall = this.getCall(this.callCount - 1);
     1494    }
     1495
     1496    var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
     1497    function createProxy(func) {
     1498        // Retain the function length:
     1499        var p;
     1500        if (func.length) {
     1501            eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +
     1502                ") { return p.invoke(func, this, slice.call(arguments)); });");
     1503        }
     1504        else {
     1505            p = function proxy() {
     1506                return p.invoke(func, this, slice.call(arguments));
     1507            };
     1508        }
     1509        return p;
     1510    }
     1511
     1512    var uuid = 0;
     1513
     1514    // Public API
     1515    var spyApi = {
     1516        reset: function () {
     1517            this.called = false;
     1518            this.notCalled = true;
     1519            this.calledOnce = false;
     1520            this.calledTwice = false;
     1521            this.calledThrice = false;
     1522            this.callCount = 0;
     1523            this.firstCall = null;
     1524            this.secondCall = null;
     1525            this.thirdCall = null;
     1526            this.lastCall = null;
     1527            this.args = [];
     1528            this.returnValues = [];
     1529            this.thisValues = [];
     1530            this.exceptions = [];
     1531            this.callIds = [];
     1532            if (this.fakes) {
     1533                for (var i = 0; i < this.fakes.length; i++) {
     1534                    this.fakes[i].reset();
     1535                }
     1536            }
     1537        },
     1538
     1539        create: function create(func) {
     1540            var name;
     1541
     1542            if (typeof func != "function") {
     1543                func = function () { };
     1544            } else {
     1545                name = sinon.functionName(func);
     1546            }
     1547
     1548            var proxy = createProxy(func);
     1549
     1550            sinon.extend(proxy, spy);
     1551            delete proxy.create;
     1552            sinon.extend(proxy, func);
     1553
     1554            proxy.reset();
     1555            proxy.prototype = func.prototype;
     1556            proxy.displayName = name || "spy";
     1557            proxy.toString = sinon.functionToString;
     1558            proxy._create = sinon.spy.create;
     1559            proxy.id = "spy#" + uuid++;
     1560
     1561            return proxy;
     1562        },
     1563
     1564        invoke: function invoke(func, thisValue, args) {
     1565            var matching = matchingFake(this.fakes, args);
     1566            var exception, returnValue;
     1567
     1568            incrementCallCount.call(this);
     1569            push.call(this.thisValues, thisValue);
     1570            push.call(this.args, args);
     1571            push.call(this.callIds, callId++);
     1572
     1573            try {
     1574                if (matching) {
     1575                    returnValue = matching.invoke(func, thisValue, args);
     1576                } else {
     1577                    returnValue = (this.func || func).apply(thisValue, args);
     1578                }
     1579
     1580                var thisCall = this.getCall(this.callCount - 1);
     1581                if (thisCall.calledWithNew() && typeof returnValue !== 'object') {
     1582                    returnValue = thisValue;
     1583                }
     1584            } catch (e) {
     1585                exception = e;
     1586            }
     1587
     1588            push.call(this.exceptions, exception);
     1589            push.call(this.returnValues, returnValue);
     1590
     1591            createCallProperties.call(this);
     1592
     1593            if (exception !== undefined) {
     1594                throw exception;
     1595            }
     1596
     1597            return returnValue;
     1598        },
     1599
     1600        getCall: function getCall(i) {
     1601            if (i < 0 || i >= this.callCount) {
     1602                return null;
     1603            }
     1604
     1605            return sinon.spyCall(this, this.thisValues[i], this.args[i],
     1606                                    this.returnValues[i], this.exceptions[i],
     1607                                    this.callIds[i]);
     1608        },
     1609
     1610        getCalls: function () {
     1611            var calls = [];
     1612            var i;
     1613
     1614            for (i = 0; i < this.callCount; i++) {
     1615                calls.push(this.getCall(i));
     1616            }
     1617
     1618            return calls;
     1619        },
     1620
     1621        calledBefore: function calledBefore(spyFn) {
     1622            if (!this.called) {
     1623                return false;
     1624            }
     1625
     1626            if (!spyFn.called) {
     1627                return true;
     1628            }
     1629
     1630            return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
     1631        },
     1632
     1633        calledAfter: function calledAfter(spyFn) {
     1634            if (!this.called || !spyFn.called) {
     1635                return false;
     1636            }
     1637
     1638            return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
     1639        },
     1640
     1641        withArgs: function () {
     1642            var args = slice.call(arguments);
     1643
     1644            if (this.fakes) {
     1645                var match = matchingFake(this.fakes, args, true);
     1646
     1647                if (match) {
     1648                    return match;
     1649                }
     1650            } else {
     1651                this.fakes = [];
     1652            }
     1653
     1654            var original = this;
     1655            var fake = this._create();
     1656            fake.matchingAguments = args;
     1657            fake.parent = this;
     1658            push.call(this.fakes, fake);
     1659
     1660            fake.withArgs = function () {
     1661                return original.withArgs.apply(original, arguments);
     1662            };
     1663
     1664            for (var i = 0; i < this.args.length; i++) {
     1665                if (fake.matches(this.args[i])) {
     1666                    incrementCallCount.call(fake);
     1667                    push.call(fake.thisValues, this.thisValues[i]);
     1668                    push.call(fake.args, this.args[i]);
     1669                    push.call(fake.returnValues, this.returnValues[i]);
     1670                    push.call(fake.exceptions, this.exceptions[i]);
     1671                    push.call(fake.callIds, this.callIds[i]);
     1672                }
     1673            }
     1674            createCallProperties.call(fake);
     1675
     1676            return fake;
     1677        },
     1678
     1679        matches: function (args, strict) {
     1680            var margs = this.matchingAguments;
     1681
     1682            if (margs.length <= args.length &&
     1683                sinon.deepEqual(margs, args.slice(0, margs.length))) {
     1684                return !strict || margs.length == args.length;
     1685            }
     1686        },
     1687
     1688        printf: function (format) {
     1689            var spy = this;
     1690            var args = slice.call(arguments, 1);
     1691            var formatter;
     1692
     1693            return (format || "").replace(/%(.)/g, function (match, specifyer) {
     1694                formatter = spyApi.formatters[specifyer];
     1695
     1696                if (typeof formatter == "function") {
     1697                    return formatter.call(null, spy, args);
     1698                } else if (!isNaN(parseInt(specifyer, 10))) {
     1699                    return sinon.format(args[specifyer - 1]);
     1700                }
     1701
     1702                return "%" + specifyer;
     1703            });
     1704        }
     1705    };
     1706
     1707    function delegateToCalls(method, matchAny, actual, notCalled) {
     1708        spyApi[method] = function () {
     1709            if (!this.called) {
     1710                if (notCalled) {
     1711                    return notCalled.apply(this, arguments);
     1712                }
     1713                return false;
     1714            }
     1715
     1716            var currentCall;
     1717            var matches = 0;
     1718
     1719            for (var i = 0, l = this.callCount; i < l; i += 1) {
     1720                currentCall = this.getCall(i);
     1721
     1722                if (currentCall[actual || method].apply(currentCall, arguments)) {
     1723                    matches += 1;
     1724
     1725                    if (matchAny) {
     1726                        return true;
     1727                    }
     1728                }
     1729            }
     1730
     1731            return matches === this.callCount;
     1732        };
     1733    }
     1734
     1735    delegateToCalls("calledOn", true);
     1736    delegateToCalls("alwaysCalledOn", false, "calledOn");
     1737    delegateToCalls("calledWith", true);
     1738    delegateToCalls("calledWithMatch", true);
     1739    delegateToCalls("alwaysCalledWith", false, "calledWith");
     1740    delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
     1741    delegateToCalls("calledWithExactly", true);
     1742    delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
     1743    delegateToCalls("neverCalledWith", false, "notCalledWith",
     1744        function () { return true; });
     1745    delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch",
     1746        function () { return true; });
     1747    delegateToCalls("threw", true);
     1748    delegateToCalls("alwaysThrew", false, "threw");
     1749    delegateToCalls("returned", true);
     1750    delegateToCalls("alwaysReturned", false, "returned");
     1751    delegateToCalls("calledWithNew", true);
     1752    delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
     1753    delegateToCalls("callArg", false, "callArgWith", function () {
     1754        throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
     1755    });
     1756    spyApi.callArgWith = spyApi.callArg;
     1757    delegateToCalls("callArgOn", false, "callArgOnWith", function () {
     1758        throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
     1759    });
     1760    spyApi.callArgOnWith = spyApi.callArgOn;
     1761    delegateToCalls("yield", false, "yield", function () {
     1762        throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
     1763    });
     1764    // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
     1765    spyApi.invokeCallback = spyApi.yield;
     1766    delegateToCalls("yieldOn", false, "yieldOn", function () {
     1767        throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
     1768    });
     1769    delegateToCalls("yieldTo", false, "yieldTo", function (property) {
     1770        throw new Error(this.toString() + " cannot yield to '" + property +
     1771            "' since it was not yet invoked.");
     1772    });
     1773    delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
     1774        throw new Error(this.toString() + " cannot yield to '" + property +
     1775            "' since it was not yet invoked.");
     1776    });
     1777
     1778    spyApi.formatters = {
     1779        "c": function (spy) {
     1780            return sinon.timesInWords(spy.callCount);
     1781        },
     1782
     1783        "n": function (spy) {
     1784            return spy.toString();
     1785        },
     1786
     1787        "C": function (spy) {
     1788            var calls = [];
     1789
     1790            for (var i = 0, l = spy.callCount; i < l; ++i) {
     1791                var stringifiedCall = "    " + spy.getCall(i).toString();
     1792                if (/\n/.test(calls[i - 1])) {
     1793                    stringifiedCall = "\n" + stringifiedCall;
     1794                }
     1795                push.call(calls, stringifiedCall);
     1796            }
     1797
     1798            return calls.length > 0 ? "\n" + calls.join("\n") : "";
     1799        },
     1800
     1801        "t": function (spy) {
     1802            var objects = [];
     1803
     1804            for (var i = 0, l = spy.callCount; i < l; ++i) {
     1805                push.call(objects, sinon.format(spy.thisValues[i]));
     1806            }
     1807
     1808            return objects.join(", ");
     1809        },
     1810
     1811        "*": function (spy, args) {
     1812            var formatted = [];
     1813
     1814            for (var i = 0, l = args.length; i < l; ++i) {
     1815                push.call(formatted, sinon.format(args[i]));
     1816            }
     1817
     1818            return formatted.join(", ");
     1819        }
     1820    };
     1821
     1822    sinon.extend(spy, spyApi);
     1823
     1824    spy.spyCall = sinon.spyCall;
     1825
     1826    if (commonJSModule) {
     1827        module.exports = spy;
     1828    } else {
     1829        sinon.spy = spy;
     1830    }
     1831}(typeof sinon == "object" && sinon || null));
     1832
     1833/**
     1834 * @depend ../sinon.js
     1835 */
     1836/*jslint eqeqeq: false, onevar: false*/
     1837/*global module, require, sinon, process, setImmediate, setTimeout*/
     1838/**
     1839 * Stub behavior
     1840 *
     1841 * @author Christian Johansen (christian@cjohansen.no)
     1842 * @author Tim Fischbach (mail@timfischbach.de)
     1843 * @license BSD
     1844 *
     1845 * Copyright (c) 2010-2013 Christian Johansen
     1846 */
     1847
     1848(function (sinon) {
     1849    var commonJSModule = typeof module !== 'undefined' && module.exports;
     1850
     1851    if (!sinon && commonJSModule) {
     1852        sinon = require("../sinon");
     1853    }
     1854
     1855    if (!sinon) {
     1856        return;
     1857    }
     1858
     1859    var slice = Array.prototype.slice;
     1860    var join = Array.prototype.join;
     1861    var proto;
     1862
     1863    var nextTick = (function () {
     1864        if (typeof process === "object" && typeof process.nextTick === "function") {
     1865            return process.nextTick;
     1866        } else if (typeof setImmediate === "function") {
     1867            return setImmediate;
     1868        } else {
     1869            return function (callback) {
     1870                setTimeout(callback, 0);
     1871            };
     1872        }
     1873    })();
     1874
     1875    function throwsException(error, message) {
     1876        if (typeof error == "string") {
     1877            this.exception = new Error(message || "");
     1878            this.exception.name = error;
     1879        } else if (!error) {
     1880            this.exception = new Error("Error");
     1881        } else {
     1882            this.exception = error;
     1883        }
     1884
     1885        return this;
     1886    }
     1887
     1888    function getCallback(behavior, args) {
     1889        var callArgAt = behavior.callArgAt;
     1890
     1891        if (callArgAt < 0) {
     1892            var callArgProp = behavior.callArgProp;
     1893
     1894            for (var i = 0, l = args.length; i < l; ++i) {
     1895                if (!callArgProp && typeof args[i] == "function") {
     1896                    return args[i];
     1897                }
     1898
     1899                if (callArgProp && args[i] &&
     1900                    typeof args[i][callArgProp] == "function") {
     1901                    return args[i][callArgProp];
     1902                }
     1903            }
     1904
     1905            return null;
     1906        }
     1907
     1908        return args[callArgAt];
     1909    }
     1910
     1911    function getCallbackError(behavior, func, args) {
     1912        if (behavior.callArgAt < 0) {
     1913            var msg;
     1914
     1915            if (behavior.callArgProp) {
     1916                msg = sinon.functionName(behavior.stub) +
     1917                    " expected to yield to '" + behavior.callArgProp +
     1918                    "', but no object with such a property was passed.";
     1919            } else {
     1920                msg = sinon.functionName(behavior.stub) +
     1921                    " expected to yield, but no callback was passed.";
     1922            }
     1923
     1924            if (args.length > 0) {
     1925                msg += " Received [" + join.call(args, ", ") + "]";
     1926            }
     1927
     1928            return msg;
     1929        }
     1930
     1931        return "argument at index " + behavior.callArgAt + " is not a function: " + func;
     1932    }
     1933
     1934    function callCallback(behavior, args) {
     1935        if (typeof behavior.callArgAt == "number") {
     1936            var func = getCallback(behavior, args);
     1937
     1938            if (typeof func != "function") {
     1939                throw new TypeError(getCallbackError(behavior, func, args));
     1940            }
     1941
     1942            if (behavior.callbackAsync) {
     1943                nextTick(function() {
     1944                    func.apply(behavior.callbackContext, behavior.callbackArguments);
     1945                });
     1946            } else {
     1947                func.apply(behavior.callbackContext, behavior.callbackArguments);
     1948            }
     1949        }
     1950    }
     1951
     1952    proto = {
     1953        create: function(stub) {
     1954            var behavior = sinon.extend({}, sinon.behavior);
     1955            delete behavior.create;
     1956            behavior.stub = stub;
     1957
     1958            return behavior;
     1959        },
     1960
     1961        isPresent: function() {
     1962            return (typeof this.callArgAt == 'number' ||
     1963                    this.exception ||
     1964                    typeof this.returnArgAt == 'number' ||
     1965                    this.returnThis ||
     1966                    this.returnValueDefined);
     1967        },
     1968
     1969        invoke: function(context, args) {
     1970            callCallback(this, args);
     1971
     1972            if (this.exception) {
     1973                throw this.exception;
     1974            } else if (typeof this.returnArgAt == 'number') {
     1975                return args[this.returnArgAt];
     1976            } else if (this.returnThis) {
     1977                return context;
     1978            }
     1979
     1980            return this.returnValue;
     1981        },
     1982
     1983        onCall: function(index) {
     1984            return this.stub.onCall(index);
     1985        },
     1986
     1987        onFirstCall: function() {
     1988            return this.stub.onFirstCall();
     1989        },
     1990
     1991        onSecondCall: function() {
     1992            return this.stub.onSecondCall();
     1993        },
     1994
     1995        onThirdCall: function() {
     1996            return this.stub.onThirdCall();
     1997        },
     1998
     1999        withArgs: function(/* arguments */) {
     2000            throw new Error('Defining a stub by invoking "stub.onCall(...).withArgs(...)" is not supported. ' +
     2001                            'Use "stub.withArgs(...).onCall(...)" to define sequential behavior for calls with certain arguments.');
     2002        },
     2003
     2004        callsArg: function callsArg(pos) {
     2005            if (typeof pos != "number") {
     2006                throw new TypeError("argument index is not number");
     2007            }
     2008
     2009            this.callArgAt = pos;
     2010            this.callbackArguments = [];
     2011            this.callbackContext = undefined;
     2012            this.callArgProp = undefined;
     2013            this.callbackAsync = false;
     2014
     2015            return this;
     2016        },
     2017
     2018        callsArgOn: function callsArgOn(pos, context) {
     2019            if (typeof pos != "number") {
     2020                throw new TypeError("argument index is not number");
     2021            }
     2022            if (typeof context != "object") {
     2023                throw new TypeError("argument context is not an object");
     2024            }
     2025
     2026            this.callArgAt = pos;
     2027            this.callbackArguments = [];
     2028            this.callbackContext = context;
     2029            this.callArgProp = undefined;
     2030            this.callbackAsync = false;
     2031
     2032            return this;
     2033        },
     2034
     2035        callsArgWith: function callsArgWith(pos) {
     2036            if (typeof pos != "number") {
     2037                throw new TypeError("argument index is not number");
     2038            }
     2039
     2040            this.callArgAt = pos;
     2041            this.callbackArguments = slice.call(arguments, 1);
     2042            this.callbackContext = undefined;
     2043            this.callArgProp = undefined;
     2044            this.callbackAsync = false;
     2045
     2046            return this;
     2047        },
     2048
     2049        callsArgOnWith: function callsArgWith(pos, context) {
     2050            if (typeof pos != "number") {
     2051                throw new TypeError("argument index is not number");
     2052            }
     2053            if (typeof context != "object") {
     2054                throw new TypeError("argument context is not an object");
     2055            }
     2056
     2057            this.callArgAt = pos;
     2058            this.callbackArguments = slice.call(arguments, 2);
     2059            this.callbackContext = context;
     2060            this.callArgProp = undefined;
     2061            this.callbackAsync = false;
     2062
     2063            return this;
     2064        },
     2065
     2066        yields: function () {
     2067            this.callArgAt = -1;
     2068            this.callbackArguments = slice.call(arguments, 0);
     2069            this.callbackContext = undefined;
     2070            this.callArgProp = undefined;
     2071            this.callbackAsync = false;
     2072
     2073            return this;
     2074        },
     2075
     2076        yieldsOn: function (context) {
     2077            if (typeof context != "object") {
     2078                throw new TypeError("argument context is not an object");
     2079            }
     2080
     2081            this.callArgAt = -1;
     2082            this.callbackArguments = slice.call(arguments, 1);
     2083            this.callbackContext = context;
     2084            this.callArgProp = undefined;
     2085            this.callbackAsync = false;
     2086
     2087            return this;
     2088        },
     2089
     2090        yieldsTo: function (prop) {
     2091            this.callArgAt = -1;
     2092            this.callbackArguments = slice.call(arguments, 1);
     2093            this.callbackContext = undefined;
     2094            this.callArgProp = prop;
     2095            this.callbackAsync = false;
     2096
     2097            return this;
     2098        },
     2099
     2100        yieldsToOn: function (prop, context) {
     2101            if (typeof context != "object") {
     2102                throw new TypeError("argument context is not an object");
     2103            }
     2104
     2105            this.callArgAt = -1;
     2106            this.callbackArguments = slice.call(arguments, 2);
     2107            this.callbackContext = context;
     2108            this.callArgProp = prop;
     2109            this.callbackAsync = false;
     2110
     2111            return this;
     2112        },
     2113
     2114
     2115        "throws": throwsException,
     2116        throwsException: throwsException,
     2117
     2118        returns: function returns(value) {
     2119            this.returnValue = value;
     2120            this.returnValueDefined = true;
     2121
     2122            return this;
     2123        },
     2124
     2125        returnsArg: function returnsArg(pos) {
     2126            if (typeof pos != "number") {
     2127                throw new TypeError("argument index is not number");
     2128            }
     2129
     2130            this.returnArgAt = pos;
     2131
     2132            return this;
     2133        },
     2134
     2135        returnsThis: function returnsThis() {
     2136            this.returnThis = true;
     2137
     2138            return this;
     2139        }
     2140    };
     2141
     2142    // create asynchronous versions of callsArg* and yields* methods
     2143    for (var method in proto) {
     2144        // need to avoid creating anotherasync versions of the newly added async methods
     2145        if (proto.hasOwnProperty(method) &&
     2146            method.match(/^(callsArg|yields)/) &&
     2147            !method.match(/Async/)) {
     2148            proto[method + 'Async'] = (function (syncFnName) {
     2149                return function () {
     2150                    var result = this[syncFnName].apply(this, arguments);
     2151                    this.callbackAsync = true;
     2152                    return result;
     2153                };
     2154            })(method);
     2155        }
     2156    }
     2157
     2158    if (commonJSModule) {
     2159        module.exports = proto;
     2160    } else {
     2161        sinon.behavior = proto;
     2162    }
     2163}(typeof sinon == "object" && sinon || null));
     2164/**
     2165 * @depend ../sinon.js
     2166 * @depend spy.js
     2167 * @depend behavior.js
     2168 */
     2169/*jslint eqeqeq: false, onevar: false*/
     2170/*global module, require, sinon*/
     2171/**
     2172 * Stub functions
     2173 *
     2174 * @author Christian Johansen (christian@cjohansen.no)
     2175 * @license BSD
     2176 *
     2177 * Copyright (c) 2010-2013 Christian Johansen
     2178 */
     2179
     2180(function (sinon) {
     2181    var commonJSModule = typeof module !== 'undefined' && module.exports;
     2182
     2183    if (!sinon && commonJSModule) {
     2184        sinon = require("../sinon");
     2185    }
     2186
     2187    if (!sinon) {
     2188        return;
     2189    }
     2190
     2191    function stub(object, property, func) {
     2192        if (!!func && typeof func != "function") {
     2193            throw new TypeError("Custom stub should be function");
     2194        }
     2195
     2196        var wrapper;
     2197
     2198        if (func) {
     2199            wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
     2200        } else {
     2201            wrapper = stub.create();
     2202        }
     2203
     2204        if (!object && typeof property === "undefined") {
     2205            return sinon.stub.create();
     2206        }
     2207
     2208        if (typeof property === "undefined" && typeof object == "object") {
     2209            for (var prop in object) {
     2210                if (typeof object[prop] === "function") {
     2211                    stub(object, prop);
     2212                }
     2213            }
     2214
     2215            return object;
     2216        }
     2217
     2218        return sinon.wrapMethod(object, property, wrapper);
     2219    }
     2220
     2221    function getDefaultBehavior(stub) {
     2222        return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub);
     2223    }
     2224
     2225    function getParentBehaviour(stub) {
     2226        return (stub.parent && getCurrentBehavior(stub.parent));
     2227    }
     2228
     2229    function getCurrentBehavior(stub) {
     2230        var behavior = stub.behaviors[stub.callCount - 1];
     2231        return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub);
     2232    }
     2233
     2234    var uuid = 0;
     2235
     2236    sinon.extend(stub, (function () {
     2237        var proto = {
     2238            create: function create() {
     2239                var functionStub = function () {
     2240                    return getCurrentBehavior(functionStub).invoke(this, arguments);
     2241                };
     2242
     2243                functionStub.id = "stub#" + uuid++;
     2244                var orig = functionStub;
     2245                functionStub = sinon.spy.create(functionStub);
     2246                functionStub.func = orig;
     2247
     2248                sinon.extend(functionStub, stub);
     2249                functionStub._create = sinon.stub.create;
     2250                functionStub.displayName = "stub";
     2251                functionStub.toString = sinon.functionToString;
     2252
     2253                functionStub.defaultBehavior = null;
     2254                functionStub.behaviors = [];
     2255
     2256                return functionStub;
     2257            },
     2258
     2259            resetBehavior: function () {
     2260                var i;
     2261
     2262                this.defaultBehavior = null;
     2263                this.behaviors = [];
     2264
     2265                delete this.returnValue;
     2266                delete this.returnArgAt;
     2267                this.returnThis = false;
     2268
     2269                if (this.fakes) {
     2270                    for (i = 0; i < this.fakes.length; i++) {
     2271                        this.fakes[i].resetBehavior();
     2272                    }
     2273                }
     2274            },
     2275
     2276            onCall: function(index) {
     2277                if (!this.behaviors[index]) {
     2278                    this.behaviors[index] = sinon.behavior.create(this);
     2279                }
     2280
     2281                return this.behaviors[index];
     2282            },
     2283
     2284            onFirstCall: function() {
     2285                return this.onCall(0);
     2286            },
     2287
     2288            onSecondCall: function() {
     2289                return this.onCall(1);
     2290            },
     2291
     2292            onThirdCall: function() {
     2293                return this.onCall(2);
     2294            }
     2295        };
     2296
     2297        for (var method in sinon.behavior) {
     2298            if (sinon.behavior.hasOwnProperty(method) &&
     2299                !proto.hasOwnProperty(method) &&
     2300                method != 'create' &&
     2301                method != 'withArgs' &&
     2302                method != 'invoke') {
     2303                proto[method] = (function(behaviorMethod) {
     2304                    return function() {
     2305                        this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this);
     2306                        this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments);
     2307                        return this;
     2308                    };
     2309                }(method));
     2310            }
     2311        }
     2312
     2313        return proto;
     2314    }()));
     2315
     2316    if (commonJSModule) {
     2317        module.exports = stub;
     2318    } else {
     2319        sinon.stub = stub;
     2320    }
     2321}(typeof sinon == "object" && sinon || null));
     2322
     2323/**
     2324 * @depend ../sinon.js
     2325 * @depend stub.js
     2326 */
     2327/*jslint eqeqeq: false, onevar: false, nomen: false*/
     2328/*global module, require, sinon*/
     2329/**
     2330 * Mock functions.
     2331 *
     2332 * @author Christian Johansen (christian@cjohansen.no)
     2333 * @license BSD
     2334 *
     2335 * Copyright (c) 2010-2013 Christian Johansen
     2336 */
     2337
     2338(function (sinon) {
     2339    var commonJSModule = typeof module !== 'undefined' && module.exports;
     2340    var push = [].push;
     2341    var match;
     2342
     2343    if (!sinon && commonJSModule) {
     2344        sinon = require("../sinon");
     2345    }
     2346
     2347    if (!sinon) {
     2348        return;
     2349    }
     2350
     2351    match = sinon.match;
     2352
     2353    if (!match && commonJSModule) {
     2354        match = require("./match");
     2355    }
     2356
     2357    function mock(object) {
     2358        if (!object) {
     2359            return sinon.expectation.create("Anonymous mock");
     2360        }
     2361
     2362        return mock.create(object);
     2363    }
     2364
     2365    sinon.mock = mock;
     2366
     2367    sinon.extend(mock, (function () {
     2368        function each(collection, callback) {
     2369            if (!collection) {
     2370                return;
     2371            }
     2372
     2373            for (var i = 0, l = collection.length; i < l; i += 1) {
     2374                callback(collection[i]);
     2375            }
     2376        }
     2377
     2378        return {
     2379            create: function create(object) {
     2380                if (!object) {
     2381                    throw new TypeError("object is null");
     2382                }
     2383
     2384                var mockObject = sinon.extend({}, mock);
     2385                mockObject.object = object;
     2386                delete mockObject.create;
     2387
     2388                return mockObject;
     2389            },
     2390
     2391            expects: function expects(method) {
     2392                if (!method) {
     2393                    throw new TypeError("method is falsy");
     2394                }
     2395
     2396                if (!this.expectations) {
     2397                    this.expectations = {};
     2398                    this.proxies = [];
     2399                }
     2400
     2401                if (!this.expectations[method]) {
     2402                    this.expectations[method] = [];
     2403                    var mockObject = this;
     2404
     2405                    sinon.wrapMethod(this.object, method, function () {
     2406                        return mockObject.invokeMethod(method, this, arguments);
     2407                    });
     2408
     2409                    push.call(this.proxies, method);
     2410                }
     2411
     2412                var expectation = sinon.expectation.create(method);
     2413                push.call(this.expectations[method], expectation);
     2414
     2415                return expectation;
     2416            },
     2417
     2418            restore: function restore() {
     2419                var object = this.object;
     2420
     2421                each(this.proxies, function (proxy) {
     2422                    if (typeof object[proxy].restore == "function") {
     2423                        object[proxy].restore();
     2424                    }
     2425                });
     2426            },
     2427
     2428            verify: function verify() {
     2429                var expectations = this.expectations || {};
     2430                var messages = [], met = [];
     2431
     2432                each(this.proxies, function (proxy) {
     2433                    each(expectations[proxy], function (expectation) {
     2434                        if (!expectation.met()) {
     2435                            push.call(messages, expectation.toString());
     2436                        } else {
     2437                            push.call(met, expectation.toString());
     2438                        }
     2439                    });
     2440                });
     2441
     2442                this.restore();
     2443
     2444                if (messages.length > 0) {
     2445                    sinon.expectation.fail(messages.concat(met).join("\n"));
     2446                } else {
     2447                    sinon.expectation.pass(messages.concat(met).join("\n"));
     2448                }
     2449
     2450                return true;
     2451            },
     2452
     2453            invokeMethod: function invokeMethod(method, thisValue, args) {
     2454                var expectations = this.expectations && this.expectations[method];
     2455                var length = expectations && expectations.length || 0, i;
     2456
     2457                for (i = 0; i < length; i += 1) {
     2458                    if (!expectations[i].met() &&
     2459                        expectations[i].allowsCall(thisValue, args)) {
     2460                        return expectations[i].apply(thisValue, args);
     2461                    }
     2462                }
     2463
     2464                var messages = [], available, exhausted = 0;
     2465
     2466                for (i = 0; i < length; i += 1) {
     2467                    if (expectations[i].allowsCall(thisValue, args)) {
     2468                        available = available || expectations[i];
     2469                    } else {
     2470                        exhausted += 1;
     2471                    }
     2472                    push.call(messages, "    " + expectations[i].toString());
     2473                }
     2474
     2475                if (exhausted === 0) {
     2476                    return available.apply(thisValue, args);
     2477                }
     2478
     2479                messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
     2480                    proxy: method,
     2481                    args: args
     2482                }));
     2483
     2484                sinon.expectation.fail(messages.join("\n"));
     2485            }
     2486        };
     2487    }()));
     2488
     2489    var times = sinon.timesInWords;
     2490
     2491    sinon.expectation = (function () {
     2492        var slice = Array.prototype.slice;
     2493        var _invoke = sinon.spy.invoke;
     2494
     2495        function callCountInWords(callCount) {
     2496            if (callCount == 0) {
     2497                return "never called";
     2498            } else {
     2499                return "called " + times(callCount);
     2500            }
     2501        }
     2502
     2503        function expectedCallCountInWords(expectation) {
     2504            var min = expectation.minCalls;
     2505            var max = expectation.maxCalls;
     2506
     2507            if (typeof min == "number" && typeof max == "number") {
     2508                var str = times(min);
     2509
     2510                if (min != max) {
     2511                    str = "at least " + str + " and at most " + times(max);
     2512                }
     2513
     2514                return str;
     2515            }
     2516
     2517            if (typeof min == "number") {
     2518                return "at least " + times(min);
     2519            }
     2520
     2521            return "at most " + times(max);
     2522        }
     2523
     2524        function receivedMinCalls(expectation) {
     2525            var hasMinLimit = typeof expectation.minCalls == "number";
     2526            return !hasMinLimit || expectation.callCount >= expectation.minCalls;
     2527        }
     2528
     2529        function receivedMaxCalls(expectation) {
     2530            if (typeof expectation.maxCalls != "number") {
     2531                return false;
     2532            }
     2533
     2534            return expectation.callCount == expectation.maxCalls;
     2535        }
     2536
     2537        function verifyMatcher(possibleMatcher, arg){
     2538            if (match && match.isMatcher(possibleMatcher)) {
     2539                return possibleMatcher.test(arg);
     2540            } else {
     2541                return true;
     2542            }
     2543        }
     2544
     2545        return {
     2546            minCalls: 1,
     2547            maxCalls: 1,
     2548
     2549            create: function create(methodName) {
     2550                var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
     2551                delete expectation.create;
     2552                expectation.method = methodName;
     2553
     2554                return expectation;
     2555            },
     2556
     2557            invoke: function invoke(func, thisValue, args) {
     2558                this.verifyCallAllowed(thisValue, args);
     2559
     2560                return _invoke.apply(this, arguments);
     2561            },
     2562
     2563            atLeast: function atLeast(num) {
     2564                if (typeof num != "number") {
     2565                    throw new TypeError("'" + num + "' is not number");
     2566                }
     2567
     2568                if (!this.limitsSet) {
     2569                    this.maxCalls = null;
     2570                    this.limitsSet = true;
     2571                }
     2572
     2573                this.minCalls = num;
     2574
     2575                return this;
     2576            },
     2577
     2578            atMost: function atMost(num) {
     2579                if (typeof num != "number") {
     2580                    throw new TypeError("'" + num + "' is not number");
     2581                }
     2582
     2583                if (!this.limitsSet) {
     2584                    this.minCalls = null;
     2585                    this.limitsSet = true;
     2586                }
     2587
     2588                this.maxCalls = num;
     2589
     2590                return this;
     2591            },
     2592
     2593            never: function never() {
     2594                return this.exactly(0);
     2595            },
     2596
     2597            once: function once() {
     2598                return this.exactly(1);
     2599            },
     2600
     2601            twice: function twice() {
     2602                return this.exactly(2);
     2603            },
     2604
     2605            thrice: function thrice() {
     2606                return this.exactly(3);
     2607            },
     2608
     2609            exactly: function exactly(num) {
     2610                if (typeof num != "number") {
     2611                    throw new TypeError("'" + num + "' is not a number");
     2612                }
     2613
     2614                this.atLeast(num);
     2615                return this.atMost(num);
     2616            },
     2617
     2618            met: function met() {
     2619                return !this.failed && receivedMinCalls(this);
     2620            },
     2621
     2622            verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
     2623                if (receivedMaxCalls(this)) {
     2624                    this.failed = true;
     2625                    sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
     2626                }
     2627
     2628                if ("expectedThis" in this && this.expectedThis !== thisValue) {
     2629                    sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
     2630                        this.expectedThis);
     2631                }
     2632
     2633                if (!("expectedArguments" in this)) {
     2634                    return;
     2635                }
     2636
     2637                if (!args) {
     2638                    sinon.expectation.fail(this.method + " received no arguments, expected " +
     2639                        sinon.format(this.expectedArguments));
     2640                }
     2641
     2642                if (args.length < this.expectedArguments.length) {
     2643                    sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
     2644                        "), expected " + sinon.format(this.expectedArguments));
     2645                }
     2646
     2647                if (this.expectsExactArgCount &&
     2648                    args.length != this.expectedArguments.length) {
     2649                    sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
     2650                        "), expected " + sinon.format(this.expectedArguments));
     2651                }
     2652
     2653                for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
     2654
     2655                    if (!verifyMatcher(this.expectedArguments[i],args[i])) {
     2656                        sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
     2657                            ", didn't match " + this.expectedArguments.toString());
     2658                    }
     2659
     2660                    if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
     2661                        sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
     2662                            ", expected " + sinon.format(this.expectedArguments));
     2663                    }
     2664                }
     2665            },
     2666
     2667            allowsCall: function allowsCall(thisValue, args) {
     2668                if (this.met() && receivedMaxCalls(this)) {
     2669                    return false;
     2670                }
     2671
     2672                if ("expectedThis" in this && this.expectedThis !== thisValue) {
     2673                    return false;
     2674                }
     2675
     2676                if (!("expectedArguments" in this)) {
     2677                    return true;
     2678                }
     2679
     2680                args = args || [];
     2681
     2682                if (args.length < this.expectedArguments.length) {
     2683                    return false;
     2684                }
     2685
     2686                if (this.expectsExactArgCount &&
     2687                    args.length != this.expectedArguments.length) {
     2688                    return false;
     2689                }
     2690
     2691                for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
     2692                    if (!verifyMatcher(this.expectedArguments[i],args[i])) {
     2693                        return false;
     2694                    }
     2695
     2696                    if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
     2697                        return false;
     2698                    }
     2699                }
     2700
     2701                return true;
     2702            },
     2703
     2704            withArgs: function withArgs() {
     2705                this.expectedArguments = slice.call(arguments);
     2706                return this;
     2707            },
     2708
     2709            withExactArgs: function withExactArgs() {
     2710                this.withArgs.apply(this, arguments);
     2711                this.expectsExactArgCount = true;
     2712                return this;
     2713            },
     2714
     2715            on: function on(thisValue) {
     2716                this.expectedThis = thisValue;
     2717                return this;
     2718            },
     2719
     2720            toString: function () {
     2721                var args = (this.expectedArguments || []).slice();
     2722
     2723                if (!this.expectsExactArgCount) {
     2724                    push.call(args, "[...]");
     2725                }
     2726
     2727                var callStr = sinon.spyCall.toString.call({
     2728                    proxy: this.method || "anonymous mock expectation",
     2729                    args: args
     2730                });
     2731
     2732                var message = callStr.replace(", [...", "[, ...") + " " +
     2733                    expectedCallCountInWords(this);
     2734
     2735                if (this.met()) {
     2736                    return "Expectation met: " + message;
     2737                }
     2738
     2739                return "Expected " + message + " (" +
     2740                    callCountInWords(this.callCount) + ")";
     2741            },
     2742
     2743            verify: function verify() {
     2744                if (!this.met()) {
     2745                    sinon.expectation.fail(this.toString());
     2746                } else {
     2747                    sinon.expectation.pass(this.toString());
     2748                }
     2749
     2750                return true;
     2751            },
     2752
     2753            pass: function(message) {
     2754              sinon.assert.pass(message);
     2755            },
     2756            fail: function (message) {
     2757                var exception = new Error(message);
     2758                exception.name = "ExpectationError";
     2759
     2760                throw exception;
     2761            }
     2762        };
     2763    }());
     2764
     2765    if (commonJSModule) {
     2766        module.exports = mock;
     2767    } else {
     2768        sinon.mock = mock;
     2769    }
     2770}(typeof sinon == "object" && sinon || null));
     2771
     2772/**
     2773 * @depend ../sinon.js
     2774 * @depend stub.js
     2775 * @depend mock.js
     2776 */
     2777/*jslint eqeqeq: false, onevar: false, forin: true*/
     2778/*global module, require, sinon*/
     2779/**
     2780 * Collections of stubs, spies and mocks.
     2781 *
     2782 * @author Christian Johansen (christian@cjohansen.no)
     2783 * @license BSD
     2784 *
     2785 * Copyright (c) 2010-2013 Christian Johansen
     2786 */
     2787
     2788(function (sinon) {
     2789    var commonJSModule = typeof module !== 'undefined' && module.exports;
     2790    var push = [].push;
     2791    var hasOwnProperty = Object.prototype.hasOwnProperty;
     2792
     2793    if (!sinon && commonJSModule) {
     2794        sinon = require("../sinon");
     2795    }
     2796
     2797    if (!sinon) {
     2798        return;
     2799    }
     2800
     2801    function getFakes(fakeCollection) {
     2802        if (!fakeCollection.fakes) {
     2803            fakeCollection.fakes = [];
     2804        }
     2805
     2806        return fakeCollection.fakes;
     2807    }
     2808
     2809    function each(fakeCollection, method) {
     2810        var fakes = getFakes(fakeCollection);
     2811
     2812        for (var i = 0, l = fakes.length; i < l; i += 1) {
     2813            if (typeof fakes[i][method] == "function") {
     2814                fakes[i][method]();
     2815            }
     2816        }
     2817    }
     2818
     2819    function compact(fakeCollection) {
     2820        var fakes = getFakes(fakeCollection);
     2821        var i = 0;
     2822        while (i < fakes.length) {
     2823          fakes.splice(i, 1);
     2824        }
     2825    }
     2826
     2827    var collection = {
     2828        verify: function resolve() {
     2829            each(this, "verify");
     2830        },
     2831
     2832        restore: function restore() {
     2833            each(this, "restore");
     2834            compact(this);
     2835        },
     2836
     2837        verifyAndRestore: function verifyAndRestore() {
     2838            var exception;
     2839
     2840            try {
     2841                this.verify();
     2842            } catch (e) {
     2843                exception = e;
     2844            }
     2845
     2846            this.restore();
     2847
     2848            if (exception) {
     2849                throw exception;
     2850            }
     2851        },
     2852
     2853        add: function add(fake) {
     2854            push.call(getFakes(this), fake);
     2855            return fake;
     2856        },
     2857
     2858        spy: function spy() {
     2859            return this.add(sinon.spy.apply(sinon, arguments));
     2860        },
     2861
     2862        stub: function stub(object, property, value) {
     2863            if (property) {
     2864                var original = object[property];
     2865
     2866                if (typeof original != "function") {
     2867                    if (!hasOwnProperty.call(object, property)) {
     2868                        throw new TypeError("Cannot stub non-existent own property " + property);
     2869                    }
     2870
     2871                    object[property] = value;
     2872
     2873                    return this.add({
     2874                        restore: function () {
     2875                            object[property] = original;
     2876                        }
     2877                    });
     2878                }
     2879            }
     2880            if (!property && !!object && typeof object == "object") {
     2881                var stubbedObj = sinon.stub.apply(sinon, arguments);
     2882
     2883                for (var prop in stubbedObj) {
     2884                    if (typeof stubbedObj[prop] === "function") {
     2885                        this.add(stubbedObj[prop]);
     2886                    }
     2887                }
     2888
     2889                return stubbedObj;
     2890            }
     2891
     2892            return this.add(sinon.stub.apply(sinon, arguments));
     2893        },
     2894
     2895        mock: function mock() {
     2896            return this.add(sinon.mock.apply(sinon, arguments));
     2897        },
     2898
     2899        inject: function inject(obj) {
     2900            var col = this;
     2901
     2902            obj.spy = function () {
     2903                return col.spy.apply(col, arguments);
     2904            };
     2905
     2906            obj.stub = function () {
     2907                return col.stub.apply(col, arguments);
     2908            };
     2909
     2910            obj.mock = function () {
     2911                return col.mock.apply(col, arguments);
     2912            };
     2913
     2914            return obj;
     2915        }
     2916    };
     2917
     2918    if (commonJSModule) {
     2919        module.exports = collection;
     2920    } else {
     2921        sinon.collection = collection;
     2922    }
     2923}(typeof sinon == "object" && sinon || null));
     2924
     2925/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
     2926/*global module, require, window*/
     2927/**
     2928 * Fake timer API
     2929 * setTimeout
     2930 * setInterval
     2931 * clearTimeout
     2932 * clearInterval
     2933 * tick
     2934 * reset
     2935 * Date
     2936 *
     2937 * Inspired by jsUnitMockTimeOut from JsUnit
     2938 *
     2939 * @author Christian Johansen (christian@cjohansen.no)
     2940 * @license BSD
     2941 *
     2942 * Copyright (c) 2010-2013 Christian Johansen
     2943 */
     2944
     2945if (typeof sinon == "undefined") {
     2946    var sinon = {};
     2947}
     2948
     2949(function (global) {
     2950    var id = 1;
     2951
     2952    function addTimer(args, recurring) {
     2953        if (args.length === 0) {
     2954            throw new Error("Function requires at least 1 parameter");
     2955        }
     2956
     2957        if (typeof args[0] === "undefined") {
     2958            throw new Error("Callback must be provided to timer calls");
     2959        }
     2960
     2961        var toId = id++;
     2962        var delay = args[1] || 0;
     2963
     2964        if (!this.timeouts) {
     2965            this.timeouts = {};
     2966        }
     2967
     2968        this.timeouts[toId] = {
     2969            id: toId,
     2970            func: args[0],
     2971            callAt: this.now + delay,
     2972            invokeArgs: Array.prototype.slice.call(args, 2)
     2973        };
     2974
     2975        if (recurring === true) {
     2976            this.timeouts[toId].interval = delay;
     2977        }
     2978
     2979        return toId;
     2980    }
     2981
     2982    function parseTime(str) {
     2983        if (!str) {
     2984            return 0;
     2985        }
     2986
     2987        var strings = str.split(":");
     2988        var l = strings.length, i = l;
     2989        var ms = 0, parsed;
     2990
     2991        if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
     2992            throw new Error("tick only understands numbers and 'h:m:s'");
     2993        }
     2994
     2995        while (i--) {
     2996            parsed = parseInt(strings[i], 10);
     2997
     2998            if (parsed >= 60) {
     2999                throw new Error("Invalid time " + str);
     3000            }
     3001
     3002            ms += parsed * Math.pow(60, (l - i - 1));
     3003        }
     3004
     3005        return ms * 1000;
     3006    }
     3007
     3008    function createObject(object) {
     3009        var newObject;
     3010
     3011        if (Object.create) {
     3012            newObject = Object.create(object);
     3013        } else {
     3014            var F = function () {};
     3015            F.prototype = object;
     3016            newObject = new F();
     3017        }
     3018
     3019        newObject.Date.clock = newObject;
     3020        return newObject;
     3021    }
     3022
     3023    sinon.clock = {
     3024        now: 0,
     3025
     3026        create: function create(now) {
     3027            var clock = createObject(this);
     3028
     3029            if (typeof now == "number") {
     3030                clock.now = now;
     3031            }
     3032
     3033            if (!!now && typeof now == "object") {
     3034                throw new TypeError("now should be milliseconds since UNIX epoch");
     3035            }
     3036
     3037            return clock;
     3038        },
     3039
     3040        setTimeout: function setTimeout(callback, timeout) {
     3041            return addTimer.call(this, arguments, false);
     3042        },
     3043
     3044        clearTimeout: function clearTimeout(timerId) {
     3045            if (!this.timeouts) {
     3046                this.timeouts = [];
     3047            }
     3048
     3049            if (timerId in this.timeouts) {
     3050                delete this.timeouts[timerId];
     3051            }
     3052        },
     3053
     3054        setInterval: function setInterval(callback, timeout) {
     3055            return addTimer.call(this, arguments, true);
     3056        },
     3057
     3058        clearInterval: function clearInterval(timerId) {
     3059            this.clearTimeout(timerId);
     3060        },
     3061
     3062        setImmediate: function setImmediate(callback) {
     3063            var passThruArgs = Array.prototype.slice.call(arguments, 1);
     3064
     3065            return addTimer.call(this, [callback, 0].concat(passThruArgs), false);
     3066        },
     3067
     3068        clearImmediate: function clearImmediate(timerId) {
     3069            this.clearTimeout(timerId);
     3070        },
     3071
     3072        tick: function tick(ms) {
     3073            ms = typeof ms == "number" ? ms : parseTime(ms);
     3074            var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
     3075            var timer = this.firstTimerInRange(tickFrom, tickTo);
     3076
     3077            var firstException;
     3078            while (timer && tickFrom <= tickTo) {
     3079                if (this.timeouts[timer.id]) {
     3080                    tickFrom = this.now = timer.callAt;
     3081                    try {
     3082                      this.callTimer(timer);
     3083                    } catch (e) {
     3084                      firstException = firstException || e;
     3085                    }
     3086                }
     3087
     3088                timer = this.firstTimerInRange(previous, tickTo);
     3089                previous = tickFrom;
     3090            }
     3091
     3092            this.now = tickTo;
     3093
     3094            if (firstException) {
     3095              throw firstException;
     3096            }
     3097
     3098            return this.now;
     3099        },
     3100
     3101        firstTimerInRange: function (from, to) {
     3102            var timer, smallest = null, originalTimer;
     3103
     3104            for (var id in this.timeouts) {
     3105                if (this.timeouts.hasOwnProperty(id)) {
     3106                    if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
     3107                        continue;
     3108                    }
     3109
     3110                    if (smallest === null || this.timeouts[id].callAt < smallest) {
     3111                        originalTimer = this.timeouts[id];
     3112                        smallest = this.timeouts[id].callAt;
     3113
     3114                        timer = {
     3115                            func: this.timeouts[id].func,
     3116                            callAt: this.timeouts[id].callAt,
     3117                            interval: this.timeouts[id].interval,
     3118                            id: this.timeouts[id].id,
     3119                            invokeArgs: this.timeouts[id].invokeArgs
     3120                        };
     3121                    }
     3122                }
     3123            }
     3124
     3125            return timer || null;
     3126        },
     3127
     3128        callTimer: function (timer) {
     3129            if (typeof timer.interval == "number") {
     3130                this.timeouts[timer.id].callAt += timer.interval;
     3131            } else {
     3132                delete this.timeouts[timer.id];
     3133            }
     3134
     3135            try {
     3136                if (typeof timer.func == "function") {
     3137                    timer.func.apply(null, timer.invokeArgs);
     3138                } else {
     3139                    eval(timer.func);
     3140                }
     3141            } catch (e) {
     3142              var exception = e;
     3143            }
     3144
     3145            if (!this.timeouts[timer.id]) {
     3146                if (exception) {
     3147                  throw exception;
     3148                }
     3149                return;
     3150            }
     3151
     3152            if (exception) {
     3153              throw exception;
     3154            }
     3155        },
     3156
     3157        reset: function reset() {
     3158            this.timeouts = {};
     3159        },
     3160
     3161        Date: (function () {
     3162            var NativeDate = Date;
     3163
     3164            function ClockDate(year, month, date, hour, minute, second, ms) {
     3165                // Defensive and verbose to avoid potential harm in passing
     3166                // explicit undefined when user does not pass argument
     3167                switch (arguments.length) {
     3168                case 0:
     3169                    return new NativeDate(ClockDate.clock.now);
     3170                case 1:
     3171                    return new NativeDate(year);
     3172                case 2:
     3173                    return new NativeDate(year, month);
     3174                case 3:
     3175                    return new NativeDate(year, month, date);
     3176                case 4:
     3177                    return new NativeDate(year, month, date, hour);
     3178                case 5:
     3179                    return new NativeDate(year, month, date, hour, minute);
     3180                case 6:
     3181                    return new NativeDate(year, month, date, hour, minute, second);
     3182                default:
     3183                    return new NativeDate(year, month, date, hour, minute, second, ms);
     3184                }
     3185            }
     3186
     3187            return mirrorDateProperties(ClockDate, NativeDate);
     3188        }())
     3189    };
     3190
     3191    function mirrorDateProperties(target, source) {
     3192        if (source.now) {
     3193            target.now = function now() {
     3194                return target.clock.now;
     3195            };
     3196        } else {
     3197            delete target.now;
     3198        }
     3199
     3200        if (source.toSource) {
     3201            target.toSource = function toSource() {
     3202                return source.toSource();
     3203            };
     3204        } else {
     3205            delete target.toSource;
     3206        }
     3207
     3208        target.toString = function toString() {
     3209            return source.toString();
     3210        };
     3211
     3212        target.prototype = source.prototype;
     3213        target.parse = source.parse;
     3214        target.UTC = source.UTC;
     3215        target.prototype.toUTCString = source.prototype.toUTCString;
     3216
     3217        for (var prop in source) {
     3218            if (source.hasOwnProperty(prop)) {
     3219                target[prop] = source[prop];
     3220            }
     3221        }
     3222
     3223        return target;
     3224    }
     3225
     3226    var methods = ["Date", "setTimeout", "setInterval",
     3227                   "clearTimeout", "clearInterval"];
     3228
     3229    if (typeof global.setImmediate !== "undefined") {
     3230        methods.push("setImmediate");
     3231    }
     3232
     3233    if (typeof global.clearImmediate !== "undefined") {
     3234        methods.push("clearImmediate");
     3235    }
     3236
     3237    function restore() {
     3238        var method;
     3239
     3240        for (var i = 0, l = this.methods.length; i < l; i++) {
     3241            method = this.methods[i];
     3242
     3243            if (global[method].hadOwnProperty) {
     3244                global[method] = this["_" + method];
     3245            } else {
     3246                try {
     3247                    delete global[method];
     3248                } catch (e) {}
     3249            }
     3250        }
     3251
     3252        // Prevent multiple executions which will completely remove these props
     3253        this.methods = [];
     3254    }
     3255
     3256    function stubGlobal(method, clock) {
     3257        clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
     3258        clock["_" + method] = global[method];
     3259
     3260        if (method == "Date") {
     3261            var date = mirrorDateProperties(clock[method], global[method]);
     3262            global[method] = date;
     3263        } else {
     3264            global[method] = function () {
     3265                return clock[method].apply(clock, arguments);
     3266            };
     3267
     3268            for (var prop in clock[method]) {
     3269                if (clock[method].hasOwnProperty(prop)) {
     3270                    global[method][prop] = clock[method][prop];
     3271                }
     3272            }
     3273        }
     3274
     3275        global[method].clock = clock;
     3276    }
     3277
     3278    sinon.useFakeTimers = function useFakeTimers(now) {
     3279        var clock = sinon.clock.create(now);
     3280        clock.restore = restore;
     3281        clock.methods = Array.prototype.slice.call(arguments,
     3282                                                   typeof now == "number" ? 1 : 0);
     3283
     3284        if (clock.methods.length === 0) {
     3285            clock.methods = methods;
     3286        }
     3287
     3288        for (var i = 0, l = clock.methods.length; i < l; i++) {
     3289            stubGlobal(clock.methods[i], clock);
     3290        }
     3291
     3292        return clock;
     3293    };
     3294}(typeof global != "undefined" && typeof global !== "function" ? global : this));
     3295
     3296sinon.timers = {
     3297    setTimeout: setTimeout,
     3298    clearTimeout: clearTimeout,
     3299    setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined),
     3300    clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined),
     3301    setInterval: setInterval,
     3302    clearInterval: clearInterval,
     3303    Date: Date
     3304};
     3305
     3306if (typeof module !== 'undefined' && module.exports) {
     3307    module.exports = sinon;
     3308}
     3309
     3310/*jslint eqeqeq: false, onevar: false*/
     3311/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
     3312/**
     3313 * Minimal Event interface implementation
     3314 *
     3315 * Original implementation by Sven Fuchs: https://gist.github.com/995028
     3316 * Modifications and tests by Christian Johansen.
     3317 *
     3318 * @author Sven Fuchs (svenfuchs@artweb-design.de)
     3319 * @author Christian Johansen (christian@cjohansen.no)
     3320 * @license BSD
     3321 *
     3322 * Copyright (c) 2011 Sven Fuchs, Christian Johansen
     3323 */
     3324
     3325if (typeof sinon == "undefined") {
     3326    this.sinon = {};
     3327}
     3328
     3329(function () {
     3330    var push = [].push;
     3331
     3332    sinon.Event = function Event(type, bubbles, cancelable, target) {
     3333        this.initEvent(type, bubbles, cancelable, target);
     3334    };
     3335
     3336    sinon.Event.prototype = {
     3337        initEvent: function(type, bubbles, cancelable, target) {
     3338            this.type = type;
     3339            this.bubbles = bubbles;
     3340            this.cancelable = cancelable;
     3341            this.target = target;
     3342        },
     3343
     3344        stopPropagation: function () {},
     3345
     3346        preventDefault: function () {
     3347            this.defaultPrevented = true;
     3348        }
     3349    };
     3350
     3351    sinon.EventTarget = {
     3352        addEventListener: function addEventListener(event, listener) {
     3353            this.eventListeners = this.eventListeners || {};
     3354            this.eventListeners[event] = this.eventListeners[event] || [];
     3355            push.call(this.eventListeners[event], listener);
     3356        },
     3357
     3358        removeEventListener: function removeEventListener(event, listener) {
     3359            var listeners = this.eventListeners && this.eventListeners[event] || [];
     3360
     3361            for (var i = 0, l = listeners.length; i < l; ++i) {
     3362                if (listeners[i] == listener) {
     3363                    return listeners.splice(i, 1);
     3364                }
     3365            }
     3366        },
     3367
     3368        dispatchEvent: function dispatchEvent(event) {
     3369            var type = event.type;
     3370            var listeners = this.eventListeners && this.eventListeners[type] || [];
     3371
     3372            for (var i = 0; i < listeners.length; i++) {
     3373                if (typeof listeners[i] == "function") {
     3374                    listeners[i].call(this, event);
     3375                } else {
     3376                    listeners[i].handleEvent(event);
     3377                }
     3378            }
     3379
     3380            return !!event.defaultPrevented;
     3381        }
     3382    };
     3383}());
     3384
     3385/**
     3386 * @depend ../../sinon.js
     3387 * @depend event.js
     3388 */
     3389/*jslint eqeqeq: false, onevar: false*/
     3390/*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
     3391/**
     3392 * Fake XMLHttpRequest object
     3393 *
     3394 * @author Christian Johansen (christian@cjohansen.no)
     3395 * @license BSD
     3396 *
     3397 * Copyright (c) 2010-2013 Christian Johansen
     3398 */
     3399
     3400// wrapper for global
     3401(function(global) {
     3402    if (typeof sinon === "undefined") {
     3403        global.sinon = {};
     3404    }
     3405
     3406    var supportsProgress = typeof ProgressEvent !== "undefined";
     3407    var supportsCustomEvent = typeof CustomEvent !== "undefined";
     3408    sinon.xhr = { XMLHttpRequest: global.XMLHttpRequest };
     3409    var xhr = sinon.xhr;
     3410    xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
     3411    xhr.GlobalActiveXObject = global.ActiveXObject;
     3412    xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
     3413    xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
     3414    xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
     3415                                     ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
     3416    xhr.supportsCORS = 'withCredentials' in (new sinon.xhr.GlobalXMLHttpRequest());
     3417
     3418    /*jsl:ignore*/
     3419    var unsafeHeaders = {
     3420        "Accept-Charset": true,
     3421        "Accept-Encoding": true,
     3422        "Connection": true,
     3423        "Content-Length": true,
     3424        "Cookie": true,
     3425        "Cookie2": true,
     3426        "Content-Transfer-Encoding": true,
     3427        "Date": true,
     3428        "Expect": true,
     3429        "Host": true,
     3430        "Keep-Alive": true,
     3431        "Referer": true,
     3432        "TE": true,
     3433        "Trailer": true,
     3434        "Transfer-Encoding": true,
     3435        "Upgrade": true,
     3436        "User-Agent": true,
     3437        "Via": true
     3438    };
     3439    /*jsl:end*/
     3440
     3441    function FakeXMLHttpRequest() {
     3442        this.readyState = FakeXMLHttpRequest.UNSENT;
     3443        this.requestHeaders = {};
     3444        this.requestBody = null;
     3445        this.status = 0;
     3446        this.statusText = "";
     3447        this.upload = new UploadProgress();
     3448        if (sinon.xhr.supportsCORS) {
     3449            this.withCredentials = false;
     3450        }
     3451
     3452
     3453        var xhr = this;
     3454        var events = ["loadstart", "load", "abort", "loadend"];
     3455
     3456        function addEventListener(eventName) {
     3457            xhr.addEventListener(eventName, function (event) {
     3458                var listener = xhr["on" + eventName];
     3459
     3460                if (listener && typeof listener == "function") {
     3461                    listener(event);
     3462                }
     3463            });
     3464        }
     3465
     3466        for (var i = events.length - 1; i >= 0; i--) {
     3467            addEventListener(events[i]);
     3468        }
     3469
     3470        if (typeof FakeXMLHttpRequest.onCreate == "function") {
     3471            FakeXMLHttpRequest.onCreate(this);
     3472        }
     3473    }
     3474
     3475    // An upload object is created for each
     3476    // FakeXMLHttpRequest and allows upload
     3477    // events to be simulated using uploadProgress
     3478    // and uploadError.
     3479    function UploadProgress() {
     3480        this.eventListeners = {
     3481            "progress": [],
     3482            "load": [],
     3483            "abort": [],
     3484            "error": []
     3485        }
     3486    }
     3487
     3488    UploadProgress.prototype.addEventListener = function(event, listener) {
     3489        this.eventListeners[event].push(listener);
     3490    };
     3491
     3492    UploadProgress.prototype.removeEventListener = function(event, listener) {
     3493        var listeners = this.eventListeners[event] || [];
     3494
     3495        for (var i = 0, l = listeners.length; i < l; ++i) {
     3496            if (listeners[i] == listener) {
     3497                return listeners.splice(i, 1);
     3498            }
     3499        }
     3500    };
     3501
     3502    UploadProgress.prototype.dispatchEvent = function(event) {
     3503        var listeners = this.eventListeners[event.type] || [];
     3504
     3505        for (var i = 0, listener; (listener = listeners[i]) != null; i++) {
     3506            listener(event);
     3507        }
     3508    };
     3509
     3510    function verifyState(xhr) {
     3511        if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
     3512            throw new Error("INVALID_STATE_ERR");
     3513        }
     3514
     3515        if (xhr.sendFlag) {
     3516            throw new Error("INVALID_STATE_ERR");
     3517        }
     3518    }
     3519
     3520    // filtering to enable a white-list version of Sinon FakeXhr,
     3521    // where whitelisted requests are passed through to real XHR
     3522    function each(collection, callback) {
     3523        if (!collection) return;
     3524        for (var i = 0, l = collection.length; i < l; i += 1) {
     3525            callback(collection[i]);
     3526        }
     3527    }
     3528    function some(collection, callback) {
     3529        for (var index = 0; index < collection.length; index++) {
     3530            if(callback(collection[index]) === true) return true;
     3531        }
     3532        return false;
     3533    }
     3534    // largest arity in XHR is 5 - XHR#open
     3535    var apply = function(obj,method,args) {
     3536        switch(args.length) {
     3537        case 0: return obj[method]();
     3538        case 1: return obj[method](args[0]);
     3539        case 2: return obj[method](args[0],args[1]);
     3540        case 3: return obj[method](args[0],args[1],args[2]);
     3541        case 4: return obj[method](args[0],args[1],args[2],args[3]);
     3542        case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
     3543        }
     3544    };
     3545
     3546    FakeXMLHttpRequest.filters = [];
     3547    FakeXMLHttpRequest.addFilter = function(fn) {
     3548        this.filters.push(fn)
     3549    };
     3550    var IE6Re = /MSIE 6/;
     3551    FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
     3552        var xhr = new sinon.xhr.workingXHR();
     3553        each(["open","setRequestHeader","send","abort","getResponseHeader",
     3554              "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
     3555             function(method) {
     3556                 fakeXhr[method] = function() {
     3557                   return apply(xhr,method,arguments);
     3558                 };
     3559             });
     3560
     3561        var copyAttrs = function(args) {
     3562            each(args, function(attr) {
     3563              try {
     3564                fakeXhr[attr] = xhr[attr]
     3565              } catch(e) {
     3566                if(!IE6Re.test(navigator.userAgent)) throw e;
     3567              }
     3568            });
     3569        };
     3570
     3571        var stateChange = function() {
     3572            fakeXhr.readyState = xhr.readyState;
     3573            if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
     3574                copyAttrs(["status","statusText"]);
     3575            }
     3576            if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
     3577                copyAttrs(["responseText"]);
     3578            }
     3579            if(xhr.readyState === FakeXMLHttpRequest.DONE) {
     3580                copyAttrs(["responseXML"]);
     3581            }
     3582            if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr });
     3583        };
     3584        if(xhr.addEventListener) {
     3585          for(var event in fakeXhr.eventListeners) {
     3586              if(fakeXhr.eventListeners.hasOwnProperty(event)) {
     3587                  each(fakeXhr.eventListeners[event],function(handler) {
     3588                      xhr.addEventListener(event, handler);
     3589                  });
     3590              }
     3591          }
     3592          xhr.addEventListener("readystatechange",stateChange);
     3593        } else {
     3594          xhr.onreadystatechange = stateChange;
     3595        }
     3596        apply(xhr,"open",xhrArgs);
     3597    };
     3598    FakeXMLHttpRequest.useFilters = false;
     3599
     3600    function verifyRequestSent(xhr) {
     3601        if (xhr.readyState == FakeXMLHttpRequest.DONE) {
     3602            throw new Error("Request done");
     3603        }
     3604    }
     3605
     3606    function verifyHeadersReceived(xhr) {
     3607        if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
     3608            throw new Error("No headers received");
     3609        }
     3610    }
     3611
     3612    function verifyResponseBodyType(body) {
     3613        if (typeof body != "string") {
     3614            var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
     3615                                 body + ", which is not a string.");
     3616            error.name = "InvalidBodyException";
     3617            throw error;
     3618        }
     3619    }
     3620
     3621    sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
     3622        async: true,
     3623
     3624        open: function open(method, url, async, username, password) {
     3625            this.method = method;
     3626            this.url = url;
     3627            this.async = typeof async == "boolean" ? async : true;
     3628            this.username = username;
     3629            this.password = password;
     3630            this.responseText = null;
     3631            this.responseXML = null;
     3632            this.requestHeaders = {};
     3633            this.sendFlag = false;
     3634            if(sinon.FakeXMLHttpRequest.useFilters === true) {
     3635                var xhrArgs = arguments;
     3636                var defake = some(FakeXMLHttpRequest.filters,function(filter) {
     3637                    return filter.apply(this,xhrArgs)
     3638                });
     3639                if (defake) {
     3640                  return sinon.FakeXMLHttpRequest.defake(this,arguments);
     3641                }
     3642            }
     3643            this.readyStateChange(FakeXMLHttpRequest.OPENED);
     3644        },
     3645
     3646        readyStateChange: function readyStateChange(state) {
     3647            this.readyState = state;
     3648
     3649            if (typeof this.onreadystatechange == "function") {
     3650                try {
     3651                    this.onreadystatechange();
     3652                } catch (e) {
     3653                    sinon.logError("Fake XHR onreadystatechange handler", e);
     3654                }
     3655            }
     3656
     3657            this.dispatchEvent(new sinon.Event("readystatechange"));
     3658
     3659            switch (this.readyState) {
     3660                case FakeXMLHttpRequest.DONE:
     3661                    this.dispatchEvent(new sinon.Event("load", false, false, this));
     3662                    this.dispatchEvent(new sinon.Event("loadend", false, false, this));
     3663                    this.upload.dispatchEvent(new sinon.Event("load", false, false, this));
     3664                    if (supportsProgress) {
     3665                        this.upload.dispatchEvent(new ProgressEvent("progress", {loaded: 100, total: 100}));
     3666                    }
     3667                    break;
     3668            }
     3669        },
     3670
     3671        setRequestHeader: function setRequestHeader(header, value) {
     3672            verifyState(this);
     3673
     3674            if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
     3675                throw new Error("Refused to set unsafe header \"" + header + "\"");
     3676            }
     3677
     3678            if (this.requestHeaders[header]) {
     3679                this.requestHeaders[header] += "," + value;
     3680            } else {
     3681                this.requestHeaders[header] = value;
     3682            }
     3683        },
     3684
     3685        // Helps testing
     3686        setResponseHeaders: function setResponseHeaders(headers) {
     3687            this.responseHeaders = {};
     3688
     3689            for (var header in headers) {
     3690                if (headers.hasOwnProperty(header)) {
     3691                    this.responseHeaders[header] = headers[header];
     3692                }
     3693            }
     3694
     3695            if (this.async) {
     3696                this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
     3697            } else {
     3698                this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
     3699            }
     3700        },
     3701
     3702        // Currently treats ALL data as a DOMString (i.e. no Document)
     3703        send: function send(data) {
     3704            verifyState(this);
     3705
     3706            if (!/^(get|head)$/i.test(this.method)) {
     3707                if (this.requestHeaders["Content-Type"]) {
     3708                    var value = this.requestHeaders["Content-Type"].split(";");
     3709                    this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
     3710                } else {
     3711                    this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
     3712                }
     3713
     3714                this.requestBody = data;
     3715            }
     3716
     3717            this.errorFlag = false;
     3718            this.sendFlag = this.async;
     3719            this.readyStateChange(FakeXMLHttpRequest.OPENED);
     3720
     3721            if (typeof this.onSend == "function") {
     3722                this.onSend(this);
     3723            }
     3724
     3725            this.dispatchEvent(new sinon.Event("loadstart", false, false, this));
     3726        },
     3727
     3728        abort: function abort() {
     3729            this.aborted = true;
     3730            this.responseText = null;
     3731            this.errorFlag = true;
     3732            this.requestHeaders = {};
     3733
     3734            if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
     3735                this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
     3736                this.sendFlag = false;
     3737            }
     3738
     3739            this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
     3740
     3741            this.dispatchEvent(new sinon.Event("abort", false, false, this));
     3742
     3743            this.upload.dispatchEvent(new sinon.Event("abort", false, false, this));
     3744
     3745            if (typeof this.onerror === "function") {
     3746                this.onerror();
     3747            }
     3748        },
     3749
     3750        getResponseHeader: function getResponseHeader(header) {
     3751            if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
     3752                return null;
     3753            }
     3754
     3755            if (/^Set-Cookie2?$/i.test(header)) {
     3756                return null;
     3757            }
     3758
     3759            header = header.toLowerCase();
     3760
     3761            for (var h in this.responseHeaders) {
     3762                if (h.toLowerCase() == header) {
     3763                    return this.responseHeaders[h];
     3764                }
     3765            }
     3766
     3767            return null;
     3768        },
     3769
     3770        getAllResponseHeaders: function getAllResponseHeaders() {
     3771            if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
     3772                return "";
     3773            }
     3774
     3775            var headers = "";
     3776
     3777            for (var header in this.responseHeaders) {
     3778                if (this.responseHeaders.hasOwnProperty(header) &&
     3779                    !/^Set-Cookie2?$/i.test(header)) {
     3780                    headers += header + ": " + this.responseHeaders[header] + "\r\n";
     3781                }
     3782            }
     3783
     3784            return headers;
     3785        },
     3786
     3787        setResponseBody: function setResponseBody(body) {
     3788            verifyRequestSent(this);
     3789            verifyHeadersReceived(this);
     3790            verifyResponseBodyType(body);
     3791
     3792            var chunkSize = this.chunkSize || 10;
     3793            var index = 0;
     3794            this.responseText = "";
     3795
     3796            do {
     3797                if (this.async) {
     3798                    this.readyStateChange(FakeXMLHttpRequest.LOADING);
     3799                }
     3800
     3801                this.responseText += body.substring(index, index + chunkSize);
     3802                index += chunkSize;
     3803            } while (index < body.length);
     3804
     3805            var type = this.getResponseHeader("Content-Type");
     3806
     3807            if (this.responseText &&
     3808                (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
     3809                try {
     3810                    this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
     3811                } catch (e) {
     3812                    // Unable to parse XML - no biggie
     3813                }
     3814            }
     3815
     3816            if (this.async) {
     3817                this.readyStateChange(FakeXMLHttpRequest.DONE);
     3818            } else {
     3819                this.readyState = FakeXMLHttpRequest.DONE;
     3820            }
     3821        },
     3822
     3823        respond: function respond(status, headers, body) {
     3824            this.status = typeof status == "number" ? status : 200;
     3825            this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
     3826            this.setResponseHeaders(headers || {});
     3827            this.setResponseBody(body || "");
     3828        },
     3829
     3830        uploadProgress: function uploadProgress(progressEventRaw) {
     3831            if (supportsProgress) {
     3832                this.upload.dispatchEvent(new ProgressEvent("progress", progressEventRaw));
     3833            }
     3834        },
     3835
     3836        uploadError: function uploadError(error) {
     3837            if (supportsCustomEvent) {
     3838                this.upload.dispatchEvent(new CustomEvent("error", {"detail": error}));
     3839            }
     3840        }
     3841    });
     3842
     3843    sinon.extend(FakeXMLHttpRequest, {
     3844        UNSENT: 0,
     3845        OPENED: 1,
     3846        HEADERS_RECEIVED: 2,
     3847        LOADING: 3,
     3848        DONE: 4
     3849    });
     3850
     3851    // Borrowed from JSpec
     3852    FakeXMLHttpRequest.parseXML = function parseXML(text) {
     3853        var xmlDoc;
     3854
     3855        if (typeof DOMParser != "undefined") {
     3856            var parser = new DOMParser();
     3857            xmlDoc = parser.parseFromString(text, "text/xml");
     3858        } else {
     3859            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
     3860            xmlDoc.async = "false";
     3861            xmlDoc.loadXML(text);
     3862        }
     3863
     3864        return xmlDoc;
     3865    };
     3866
     3867    FakeXMLHttpRequest.statusCodes = {
     3868        100: "Continue",
     3869        101: "Switching Protocols",
     3870        200: "OK",
     3871        201: "Created",
     3872        202: "Accepted",
     3873        203: "Non-Authoritative Information",
     3874        204: "No Content",
     3875        205: "Reset Content",
     3876        206: "Partial Content",
     3877        300: "Multiple Choice",
     3878        301: "Moved Permanently",
     3879        302: "Found",
     3880        303: "See Other",
     3881        304: "Not Modified",
     3882        305: "Use Proxy",
     3883        307: "Temporary Redirect",
     3884        400: "Bad Request",
     3885        401: "Unauthorized",
     3886        402: "Payment Required",
     3887        403: "Forbidden",
     3888        404: "Not Found",
     3889        405: "Method Not Allowed",
     3890        406: "Not Acceptable",
     3891        407: "Proxy Authentication Required",
     3892        408: "Request Timeout",
     3893        409: "Conflict",
     3894        410: "Gone",
     3895        411: "Length Required",
     3896        412: "Precondition Failed",
     3897        413: "Request Entity Too Large",
     3898        414: "Request-URI Too Long",
     3899        415: "Unsupported Media Type",
     3900        416: "Requested Range Not Satisfiable",
     3901        417: "Expectation Failed",
     3902        422: "Unprocessable Entity",
     3903        500: "Internal Server Error",
     3904        501: "Not Implemented",
     3905        502: "Bad Gateway",
     3906        503: "Service Unavailable",
     3907        504: "Gateway Timeout",
     3908        505: "HTTP Version Not Supported"
     3909    };
     3910
     3911    sinon.useFakeXMLHttpRequest = function () {
     3912        sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
     3913            if (xhr.supportsXHR) {
     3914                global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
     3915            }
     3916
     3917            if (xhr.supportsActiveX) {
     3918                global.ActiveXObject = xhr.GlobalActiveXObject;
     3919            }
     3920
     3921            delete sinon.FakeXMLHttpRequest.restore;
     3922
     3923            if (keepOnCreate !== true) {
     3924                delete sinon.FakeXMLHttpRequest.onCreate;
     3925            }
     3926        };
     3927        if (xhr.supportsXHR) {
     3928            global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
     3929        }
     3930
     3931        if (xhr.supportsActiveX) {
     3932            global.ActiveXObject = function ActiveXObject(objId) {
     3933                if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
     3934
     3935                    return new sinon.FakeXMLHttpRequest();
     3936                }
     3937
     3938                return new xhr.GlobalActiveXObject(objId);
     3939            };
     3940        }
     3941
     3942        return sinon.FakeXMLHttpRequest;
     3943    };
     3944
     3945    sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
     3946
     3947})(typeof global === "object" ? global : this);
     3948
     3949if (typeof module !== 'undefined' && module.exports) {
     3950    module.exports = sinon;
     3951}
     3952
     3953/**
     3954 * @depend fake_xml_http_request.js
     3955 */
     3956/*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
     3957/*global module, require, window*/
     3958/**
     3959 * The Sinon "server" mimics a web server that receives requests from
     3960 * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
     3961 * both synchronously and asynchronously. To respond synchronuously, canned
     3962 * answers have to be provided upfront.
     3963 *
     3964 * @author Christian Johansen (christian@cjohansen.no)
     3965 * @license BSD
     3966 *
     3967 * Copyright (c) 2010-2013 Christian Johansen
     3968 */
     3969
     3970if (typeof sinon == "undefined") {
     3971    var sinon = {};
     3972}
     3973
     3974sinon.fakeServer = (function () {
     3975    var push = [].push;
     3976    function F() {}
     3977
     3978    function create(proto) {
     3979        F.prototype = proto;
     3980        return new F();
     3981    }
     3982
     3983    function responseArray(handler) {
     3984        var response = handler;
     3985
     3986        if (Object.prototype.toString.call(handler) != "[object Array]") {
     3987            response = [200, {}, handler];
     3988        }
     3989
     3990        if (typeof response[2] != "string") {
     3991            throw new TypeError("Fake server response body should be string, but was " +
     3992                                typeof response[2]);
     3993        }
     3994
     3995        return response;
     3996    }
     3997
     3998    var wloc = typeof window !== "undefined" ? window.location : {};
     3999    var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
     4000
     4001    function matchOne(response, reqMethod, reqUrl) {
     4002        var rmeth = response.method;
     4003        var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
     4004        var url = response.url;
     4005        var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
     4006
     4007        return matchMethod && matchUrl;
     4008    }
     4009
     4010    function match(response, request) {
     4011        var requestUrl = request.url;
     4012
     4013        if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
     4014            requestUrl = requestUrl.replace(rCurrLoc, "");
     4015        }
     4016
     4017        if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
     4018            if (typeof response.response == "function") {
     4019                var ru = response.url;
     4020                var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []);
     4021                return response.response.apply(response, args);
     4022            }
     4023
     4024            return true;
     4025        }
     4026
     4027        return false;
     4028    }
     4029
     4030    function log(response, request) {
     4031        var str;
     4032
     4033        str =  "Request:\n"  + sinon.format(request)  + "\n\n";
     4034        str += "Response:\n" + sinon.format(response) + "\n\n";
     4035
     4036        sinon.log(str);
     4037    }
     4038
     4039    return {
     4040        create: function () {
     4041            var server = create(this);
     4042            this.xhr = sinon.useFakeXMLHttpRequest();
     4043            server.requests = [];
     4044
     4045            this.xhr.onCreate = function (xhrObj) {
     4046                server.addRequest(xhrObj);
     4047            };
     4048
     4049            return server;
     4050        },
     4051
     4052        addRequest: function addRequest(xhrObj) {
     4053            var server = this;
     4054            push.call(this.requests, xhrObj);
     4055
     4056            xhrObj.onSend = function () {
     4057                server.handleRequest(this);
     4058
     4059                if (server.autoRespond && !server.responding) {
     4060                    setTimeout(function () {
     4061                        server.responding = false;
     4062                        server.respond();
     4063                    }, server.autoRespondAfter || 10);
     4064
     4065                    server.responding = true;
     4066                }
     4067            };
     4068        },
     4069
     4070        getHTTPMethod: function getHTTPMethod(request) {
     4071            if (this.fakeHTTPMethods && /post/i.test(request.method)) {
     4072                var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
     4073                return !!matches ? matches[1] : request.method;
     4074            }
     4075
     4076            return request.method;
     4077        },
     4078
     4079        handleRequest: function handleRequest(xhr) {
     4080            if (xhr.async) {
     4081                if (!this.queue) {
     4082                    this.queue = [];
     4083                }
     4084
     4085                push.call(this.queue, xhr);
     4086            } else {
     4087                this.processRequest(xhr);
     4088            }
     4089        },
     4090
     4091        respondWith: function respondWith(method, url, body) {
     4092            if (arguments.length == 1 && typeof method != "function") {
     4093                this.response = responseArray(method);
     4094                return;
     4095            }
     4096
     4097            if (!this.responses) { this.responses = []; }
     4098
     4099            if (arguments.length == 1) {
     4100                body = method;
     4101                url = method = null;
     4102            }
     4103
     4104            if (arguments.length == 2) {
     4105                body = url;
     4106                url = method;
     4107                method = null;
     4108            }
     4109
     4110            push.call(this.responses, {
     4111                method: method,
     4112                url: url,
     4113                response: typeof body == "function" ? body : responseArray(body)
     4114            });
     4115        },
     4116
     4117        respond: function respond() {
     4118            if (arguments.length > 0) this.respondWith.apply(this, arguments);
     4119            var queue = this.queue || [];
     4120            var requests = queue.splice(0);
     4121            var request;
     4122
     4123            while(request = requests.shift()) {
     4124                this.processRequest(request);
     4125            }
     4126        },
     4127
     4128        processRequest: function processRequest(request) {
     4129            try {
     4130                if (request.aborted) {
     4131                    return;
     4132                }
     4133
     4134                var response = this.response || [404, {}, ""];
     4135
     4136                if (this.responses) {
     4137                    for (var l = this.responses.length, i = l - 1; i >= 0; i--) {
     4138                        if (match.call(this, this.responses[i], request)) {
     4139                            response = this.responses[i].response;
     4140                            break;
     4141                        }
     4142                    }
     4143                }
     4144
     4145                if (request.readyState != 4) {
     4146                    log(response, request);
     4147
     4148                    request.respond(response[0], response[1], response[2]);
     4149                }
     4150            } catch (e) {
     4151                sinon.logError("Fake server request processing", e);
     4152            }
     4153        },
     4154
     4155        restore: function restore() {
     4156            return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
     4157        }
     4158    };
     4159}());
     4160
     4161if (typeof module !== 'undefined' && module.exports) {
     4162    module.exports = sinon;
     4163}
     4164
     4165/**
     4166 * @depend fake_server.js
     4167 * @depend fake_timers.js
     4168 */
     4169/*jslint browser: true, eqeqeq: false, onevar: false*/
     4170/*global sinon*/
     4171/**
     4172 * Add-on for sinon.fakeServer that automatically handles a fake timer along with
     4173 * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
     4174 * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
     4175 * it polls the object for completion with setInterval. Dispite the direct
     4176 * motivation, there is nothing jQuery-specific in this file, so it can be used
     4177 * in any environment where the ajax implementation depends on setInterval or
     4178 * setTimeout.
     4179 *
     4180 * @author Christian Johansen (christian@cjohansen.no)
     4181 * @license BSD
     4182 *
     4183 * Copyright (c) 2010-2013 Christian Johansen
     4184 */
     4185
     4186(function () {
     4187    function Server() {}
     4188    Server.prototype = sinon.fakeServer;
     4189
     4190    sinon.fakeServerWithClock = new Server();
     4191
     4192    sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
     4193        if (xhr.async) {
     4194            if (typeof setTimeout.clock == "object") {
     4195                this.clock = setTimeout.clock;
     4196            } else {
     4197                this.clock = sinon.useFakeTimers();
     4198                this.resetClock = true;
     4199            }
     4200
     4201            if (!this.longestTimeout) {
     4202                var clockSetTimeout = this.clock.setTimeout;
     4203                var clockSetInterval = this.clock.setInterval;
     4204                var server = this;
     4205
     4206                this.clock.setTimeout = function (fn, timeout) {
     4207                    server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
     4208
     4209                    return clockSetTimeout.apply(this, arguments);
     4210                };
     4211
     4212                this.clock.setInterval = function (fn, timeout) {
     4213                    server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
     4214
     4215                    return clockSetInterval.apply(this, arguments);
     4216                };
     4217            }
     4218        }
     4219
     4220        return sinon.fakeServer.addRequest.call(this, xhr);
     4221    };
     4222
     4223    sinon.fakeServerWithClock.respond = function respond() {
     4224        var returnVal = sinon.fakeServer.respond.apply(this, arguments);
     4225
     4226        if (this.clock) {
     4227            this.clock.tick(this.longestTimeout || 0);
     4228            this.longestTimeout = 0;
     4229
     4230            if (this.resetClock) {
     4231                this.clock.restore();
     4232                this.resetClock = false;
     4233            }
     4234        }
     4235
     4236        return returnVal;
     4237    };
     4238
     4239    sinon.fakeServerWithClock.restore = function restore() {
     4240        if (this.clock) {
     4241            this.clock.restore();
     4242        }
     4243
     4244        return sinon.fakeServer.restore.apply(this, arguments);
     4245    };
     4246}());
     4247
     4248/**
     4249 * @depend ../sinon.js
     4250 * @depend collection.js
     4251 * @depend util/fake_timers.js
     4252 * @depend util/fake_server_with_clock.js
     4253 */
     4254/*jslint eqeqeq: false, onevar: false, plusplus: false*/
     4255/*global require, module*/
     4256/**
     4257 * Manages fake collections as well as fake utilities such as Sinon's
     4258 * timers and fake XHR implementation in one convenient object.
     4259 *
     4260 * @author Christian Johansen (christian@cjohansen.no)
     4261 * @license BSD
     4262 *
     4263 * Copyright (c) 2010-2013 Christian Johansen
     4264 */
     4265
     4266if (typeof module !== 'undefined' && module.exports) {
     4267    var sinon = require("../sinon");
     4268    sinon.extend(sinon, require("./util/fake_timers"));
     4269}
     4270
     4271(function () {
     4272    var push = [].push;
     4273
     4274    function exposeValue(sandbox, config, key, value) {
     4275        if (!value) {
     4276            return;
     4277        }
     4278
     4279        if (config.injectInto && !(key in config.injectInto) ) {
     4280            config.injectInto[key] = value;
     4281        } else {
     4282            push.call(sandbox.args, value);
     4283        }
     4284    }
     4285
     4286    function prepareSandboxFromConfig(config) {
     4287        var sandbox = sinon.create(sinon.sandbox);
     4288
     4289        if (config.useFakeServer) {
     4290            if (typeof config.useFakeServer == "object") {
     4291                sandbox.serverPrototype = config.useFakeServer;
     4292            }
     4293
     4294            sandbox.useFakeServer();
     4295        }
     4296
     4297        if (config.useFakeTimers) {
     4298            if (typeof config.useFakeTimers == "object") {
     4299                sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
     4300            } else {
     4301                sandbox.useFakeTimers();
     4302            }
     4303        }
     4304
     4305        return sandbox;
     4306    }
     4307
     4308    sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
     4309        useFakeTimers: function useFakeTimers() {
     4310            this.clock = sinon.useFakeTimers.apply(sinon, arguments);
     4311
     4312            return this.add(this.clock);
     4313        },
     4314
     4315        serverPrototype: sinon.fakeServer,
     4316
     4317        useFakeServer: function useFakeServer() {
     4318            var proto = this.serverPrototype || sinon.fakeServer;
     4319
     4320            if (!proto || !proto.create) {
     4321                return null;
     4322            }
     4323
     4324            this.server = proto.create();
     4325            return this.add(this.server);
     4326        },
     4327
     4328        inject: function (obj) {
     4329            sinon.collection.inject.call(this, obj);
     4330
     4331            if (this.clock) {
     4332                obj.clock = this.clock;
     4333            }
     4334
     4335            if (this.server) {
     4336                obj.server = this.server;
     4337                obj.requests = this.server.requests;
     4338            }
     4339
     4340            return obj;
     4341        },
     4342
     4343        create: function (config) {
     4344            if (!config) {
     4345                return sinon.create(sinon.sandbox);
     4346            }
     4347
     4348            var sandbox = prepareSandboxFromConfig(config);
     4349            sandbox.args = sandbox.args || [];
     4350            var prop, value, exposed = sandbox.inject({});
     4351
     4352            if (config.properties) {
     4353                for (var i = 0, l = config.properties.length; i < l; i++) {
     4354                    prop = config.properties[i];
     4355                    value = exposed[prop] || prop == "sandbox" && sandbox;
     4356                    exposeValue(sandbox, config, prop, value);
     4357                }
     4358            } else {
     4359                exposeValue(sandbox, config, "sandbox", value);
     4360            }
     4361
     4362            return sandbox;
     4363        }
     4364    });
     4365
     4366    sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
     4367
     4368    if (typeof module !== 'undefined' && module.exports) {
     4369        module.exports = sinon.sandbox;
     4370    }
     4371}());
     4372
     4373/**
     4374 * @depend ../sinon.js
     4375 * @depend stub.js
     4376 * @depend mock.js
     4377 * @depend sandbox.js
     4378 */
     4379/*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
     4380/*global module, require, sinon*/
     4381/**
     4382 * Test function, sandboxes fakes
     4383 *
     4384 * @author Christian Johansen (christian@cjohansen.no)
     4385 * @license BSD
     4386 *
     4387 * Copyright (c) 2010-2013 Christian Johansen
     4388 */
     4389
     4390(function (sinon) {
     4391    var commonJSModule = typeof module !== 'undefined' && module.exports;
     4392
     4393    if (!sinon && commonJSModule) {
     4394        sinon = require("../sinon");
     4395    }
     4396
     4397    if (!sinon) {
     4398        return;
     4399    }
     4400
     4401    function test(callback) {
     4402        var type = typeof callback;
     4403
     4404        if (type != "function") {
     4405            throw new TypeError("sinon.test needs to wrap a test function, got " + type);
     4406        }
     4407
     4408        return function () {
     4409            var config = sinon.getConfig(sinon.config);
     4410            config.injectInto = config.injectIntoThis && this || config.injectInto;
     4411            var sandbox = sinon.sandbox.create(config);
     4412            var exception, result;
     4413            var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
     4414
     4415            try {
     4416                result = callback.apply(this, args);
     4417            } catch (e) {
     4418                exception = e;
     4419            }
     4420
     4421            if (typeof exception !== "undefined") {
     4422                sandbox.restore();
     4423                throw exception;
     4424            }
     4425            else {
     4426                sandbox.verifyAndRestore();
     4427            }
     4428
     4429            return result;
     4430        };
     4431    }
     4432
     4433    test.config = {
     4434        injectIntoThis: true,
     4435        injectInto: null,
     4436        properties: ["spy", "stub", "mock", "clock", "server", "requests"],
     4437        useFakeTimers: true,
     4438        useFakeServer: true
     4439    };
     4440
     4441    if (commonJSModule) {
     4442        module.exports = test;
     4443    } else {
     4444        sinon.test = test;
     4445    }
     4446}(typeof sinon == "object" && sinon || null));
     4447
     4448/**
     4449 * @depend ../sinon.js
     4450 * @depend test.js
     4451 */
     4452/*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
     4453/*global module, require, sinon*/
     4454/**
     4455 * Test case, sandboxes all test functions
     4456 *
     4457 * @author Christian Johansen (christian@cjohansen.no)
     4458 * @license BSD
     4459 *
     4460 * Copyright (c) 2010-2013 Christian Johansen
     4461 */
     4462
     4463(function (sinon) {
     4464    var commonJSModule = typeof module !== 'undefined' && module.exports;
     4465
     4466    if (!sinon && commonJSModule) {
     4467        sinon = require("../sinon");
     4468    }
     4469
     4470    if (!sinon || !Object.prototype.hasOwnProperty) {
     4471        return;
     4472    }
     4473
     4474    function createTest(property, setUp, tearDown) {
     4475        return function () {
     4476            if (setUp) {
     4477                setUp.apply(this, arguments);
     4478            }
     4479
     4480            var exception, result;
     4481
     4482            try {
     4483                result = property.apply(this, arguments);
     4484            } catch (e) {
     4485                exception = e;
     4486            }
     4487
     4488            if (tearDown) {
     4489                tearDown.apply(this, arguments);
     4490            }
     4491
     4492            if (exception) {
     4493                throw exception;
     4494            }
     4495
     4496            return result;
     4497        };
     4498    }
     4499
     4500    function testCase(tests, prefix) {
     4501        /*jsl:ignore*/
     4502        if (!tests || typeof tests != "object") {
     4503            throw new TypeError("sinon.testCase needs an object with test functions");
     4504        }
     4505        /*jsl:end*/
     4506
     4507        prefix = prefix || "test";
     4508        var rPrefix = new RegExp("^" + prefix);
     4509        var methods = {}, testName, property, method;
     4510        var setUp = tests.setUp;
     4511        var tearDown = tests.tearDown;
     4512
     4513        for (testName in tests) {
     4514            if (tests.hasOwnProperty(testName)) {
     4515                property = tests[testName];
     4516
     4517                if (/^(setUp|tearDown)$/.test(testName)) {
     4518                    continue;
     4519                }
     4520
     4521                if (typeof property == "function" && rPrefix.test(testName)) {
     4522                    method = property;
     4523
     4524                    if (setUp || tearDown) {
     4525                        method = createTest(property, setUp, tearDown);
     4526                    }
     4527
     4528                    methods[testName] = sinon.test(method);
     4529                } else {
     4530                    methods[testName] = tests[testName];
     4531                }
     4532            }
     4533        }
     4534
     4535        return methods;
     4536    }
     4537
     4538    if (commonJSModule) {
     4539        module.exports = testCase;
     4540    } else {
     4541        sinon.testCase = testCase;
     4542    }
     4543}(typeof sinon == "object" && sinon || null));
     4544
     4545/**
     4546 * @depend ../sinon.js
     4547 * @depend stub.js
     4548 */
     4549/*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
     4550/*global module, require, sinon*/
     4551/**
     4552 * Assertions matching the test spy retrieval interface.
     4553 *
     4554 * @author Christian Johansen (christian@cjohansen.no)
     4555 * @license BSD
     4556 *
     4557 * Copyright (c) 2010-2013 Christian Johansen
     4558 */
     4559
     4560(function (sinon, global) {
     4561    var commonJSModule = typeof module !== "undefined" && module.exports;
     4562    var slice = Array.prototype.slice;
     4563    var assert;
     4564
     4565    if (!sinon && commonJSModule) {
     4566        sinon = require("../sinon");
     4567    }
     4568
     4569    if (!sinon) {
     4570        return;
     4571    }
     4572
     4573    function verifyIsStub() {
     4574        var method;
     4575
     4576        for (var i = 0, l = arguments.length; i < l; ++i) {
     4577            method = arguments[i];
     4578
     4579            if (!method) {
     4580                assert.fail("fake is not a spy");
     4581            }
     4582
     4583            if (typeof method != "function") {
     4584                assert.fail(method + " is not a function");
     4585            }
     4586
     4587            if (typeof method.getCall != "function") {
     4588                assert.fail(method + " is not stubbed");
     4589            }
     4590        }
     4591    }
     4592
     4593    function failAssertion(object, msg) {
     4594        object = object || global;
     4595        var failMethod = object.fail || assert.fail;
     4596        failMethod.call(object, msg);
     4597    }
     4598
     4599    function mirrorPropAsAssertion(name, method, message) {
     4600        if (arguments.length == 2) {
     4601            message = method;
     4602            method = name;
     4603        }
     4604
     4605        assert[name] = function (fake) {
     4606            verifyIsStub(fake);
     4607
     4608            var args = slice.call(arguments, 1);
     4609            var failed = false;
     4610
     4611            if (typeof method == "function") {
     4612                failed = !method(fake);
     4613            } else {
     4614                failed = typeof fake[method] == "function" ?
     4615                    !fake[method].apply(fake, args) : !fake[method];
     4616            }
     4617
     4618            if (failed) {
     4619                failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
     4620            } else {
     4621                assert.pass(name);
     4622            }
     4623        };
     4624    }
     4625
     4626    function exposedName(prefix, prop) {
     4627        return !prefix || /^fail/.test(prop) ? prop :
     4628            prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
     4629    }
     4630
     4631    assert = {
     4632        failException: "AssertError",
     4633
     4634        fail: function fail(message) {
     4635            var error = new Error(message);
     4636            error.name = this.failException || assert.failException;
     4637
     4638            throw error;
     4639        },
     4640
     4641        pass: function pass(assertion) {},
     4642
     4643        callOrder: function assertCallOrder() {
     4644            verifyIsStub.apply(null, arguments);
     4645            var expected = "", actual = "";
     4646
     4647            if (!sinon.calledInOrder(arguments)) {
     4648                try {
     4649                    expected = [].join.call(arguments, ", ");
     4650                    var calls = slice.call(arguments);
     4651                    var i = calls.length;
     4652                    while (i) {
     4653                        if (!calls[--i].called) {
     4654                            calls.splice(i, 1);
     4655                        }
     4656                    }
     4657                    actual = sinon.orderByFirstCall(calls).join(", ");
     4658                } catch (e) {
     4659                    // If this fails, we'll just fall back to the blank string
     4660                }
     4661
     4662                failAssertion(this, "expected " + expected + " to be " +
     4663                              "called in order but were called as " + actual);
     4664            } else {
     4665                assert.pass("callOrder");
     4666            }
     4667        },
     4668
     4669        callCount: function assertCallCount(method, count) {
     4670            verifyIsStub(method);
     4671
     4672            if (method.callCount != count) {
     4673                var msg = "expected %n to be called " + sinon.timesInWords(count) +
     4674                    " but was called %c%C";
     4675                failAssertion(this, method.printf(msg));
     4676            } else {
     4677                assert.pass("callCount");
     4678            }
     4679        },
     4680
     4681        expose: function expose(target, options) {
     4682            if (!target) {
     4683                throw new TypeError("target is null or undefined");
     4684            }
     4685
     4686            var o = options || {};
     4687            var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
     4688            var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
     4689
     4690            for (var method in this) {
     4691                if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
     4692                    target[exposedName(prefix, method)] = this[method];
     4693                }
     4694            }
     4695
     4696            return target;
     4697        }
     4698    };
     4699
     4700    mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
     4701    mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
     4702                          "expected %n to not have been called but was called %c%C");
     4703    mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
     4704    mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
     4705    mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
     4706    mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
     4707    mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
     4708    mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
     4709    mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
     4710    mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
     4711    mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
     4712    mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
     4713    mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
     4714    mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
     4715    mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
     4716    mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
     4717    mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
     4718    mirrorPropAsAssertion("threw", "%n did not throw exception%C");
     4719    mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
     4720
     4721    if (commonJSModule) {
     4722        module.exports = assert;
     4723    } else {
     4724        sinon.assert = assert;
     4725    }
     4726}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global));
     4727
     4728return sinon;}.call(typeof window != 'undefined' && window || {}));
  • new file tests/qunit/vendor/sinon-qunit-1.0.0.js

    diff --git tests/qunit/vendor/sinon-qunit-1.0.0.js tests/qunit/vendor/sinon-qunit-1.0.0.js
    new file mode 100644
    index 0000000..c26232f
    - +  
     1/**
     2 * sinon-qunit 1.0.0, 2010/12/09
     3 *
     4 * @author Christian Johansen (christian@cjohansen.no)
     5 *
     6 * (The BSD License)
     7 *
     8 * Copyright (c) 2010-2011, Christian Johansen, christian@cjohansen.no
     9 * All rights reserved.
     10 *
     11 * Redistribution and use in source and binary forms, with or without modification,
     12 * are permitted provided that the following conditions are met:
     13 *
     14 *     * Redistributions of source code must retain the above copyright notice,
     15 *       this list of conditions and the following disclaimer.
     16 *     * Redistributions in binary form must reproduce the above copyright notice,
     17 *       this list of conditions and the following disclaimer in the documentation
     18 *       and/or other materials provided with the distribution.
     19 *     * Neither the name of Christian Johansen nor the names of his contributors
     20 *       may be used to endorse or promote products derived from this software
     21 *       without specific prior written permission.
     22 *
     23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
     24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     26 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
     27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     29 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     30 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33 */
     34/*global sinon, QUnit, test*/
     35sinon.assert.fail = function (msg) {
     36    QUnit.ok(false, msg);
     37};
     38
     39sinon.assert.pass = function (assertion) {
     40    QUnit.ok(true, assertion);
     41};
     42
     43sinon.config = {
     44    injectIntoThis: true,
     45    injectInto: null,
     46    properties: ["spy", "stub", "mock", "clock", "sandbox"],
     47    useFakeTimers: true,
     48    useFakeServer: false
     49};
     50
     51(function (global) {
     52    var qTest = QUnit.test;
     53   
     54    QUnit.test = global.test = function (testName, expected, callback, async) {
     55        if (arguments.length === 2) {
     56            callback = expected;
     57            expected = null;
     58        }
     59
     60        return qTest(testName, expected, sinon.test(callback), async);
     61    };
     62}(this));
  • new file tests/qunit/wp-admin/js/customize-header.js

    diff --git tests/qunit/wp-admin/js/customize-header.js tests/qunit/wp-admin/js/customize-header.js
    new file mode 100644
    index 0000000..b94efdb
    - +  
     1/* global wp, jQuery */
     2
     3jQuery( function() {
     4        module('Custom Header: ChoiceList', {
     5                setup: function() {
     6                        wp.customize.HeaderTool.currentHeader = new wp.customize.HeaderTool.ImageModel();
     7                        this.apiStub = sinon.stub(wp.customize, 'get').returns('foo');
     8                        this.choiceList = new wp.customize.HeaderTool.ChoiceList();
     9                },
     10                teardown: function() {
     11                        this.apiStub.restore();
     12                }
     13        });
     14
     15        test('should parse _wpCustomizeHeader.uploads into itself', function() {
     16                equal(this.choiceList.length, 4);
     17        });
     18
     19        test('should sort by newest first', function() {
     20                equal(this.choiceList.at(2).get('header').attachment_id, 1);
     21                equal(this.choiceList.first().get('header').attachment_id, 3);
     22        });
     23
     24        module('Custom Header: DefaultsList', {
     25                setup: function() {
     26                        wp.customize.HeaderTool.currentHeader = new wp.customize.HeaderTool.ImageModel();
     27                        this.apiStub = sinon.stub(wp.customize, 'get').returns('foo');
     28                        this.choiceList = new wp.customize.HeaderTool.DefaultsList();
     29                },
     30                teardown: function() {
     31                        this.apiStub.restore();
     32                }
     33        });
     34
     35        test('it should parse _wpCustomizeHeader.defaults into itself', function() {
     36                equal(this.choiceList.length, 4);
     37        });
     38
     39        test('it parses the default image names', function() {
     40                equal(this.choiceList.first().get('header').defaultName, 'circle');
     41                equal(this.choiceList.at(2).get('header').defaultName, 'star');
     42        });
     43
     44        module('Custom Header: HeaderImage shouldBeCropped()', {
     45                setup: function() {
     46                        wp.customize.HeaderTool.currentHeader = new wp.customize.HeaderTool.ImageModel();
     47                        this.model = new wp.customize.HeaderTool.ImageModel();
     48                        this.model.set({
     49                                themeWidth: 1000,
     50                                themeHeight: 200
     51                        });
     52                }
     53        });
     54
     55        test('should not be cropped when the theme does not support flex width or height and the image has the same dimensions of the theme image', function() {
     56                this.model.set({
     57                        themeFlexWidth: false,
     58                        themeFlexHeight: false,
     59                        imageWidth: 1000,
     60                        imageHeight: 200
     61                });
     62
     63                equal(this.model.shouldBeCropped(), false);
     64        });
     65
     66        test('should be cropped when the image has the same dimensions of the theme image', function() {
     67                this.model.set({
     68                        themeFlexWidth: false,
     69                        themeFlexHeight: false,
     70                        imageWidth: 2000,
     71                        imageHeight: 400
     72                });
     73
     74                equal(this.model.shouldBeCropped(), true);
     75        });
     76
     77        test('should not be cropped when the theme only supports flex width and the image has the same height as the theme image', function() {
     78                this.model.set({
     79                        themeFlexWidth: true,
     80                        themeFlexHeight: false,
     81                        imageWidth: 4000,
     82                        imageHeight: 200
     83                });
     84
     85                equal(this.model.shouldBeCropped(), false);
     86        });
     87
     88        test('should not be cropped when the theme only supports flex height and the image has the same width as the theme image', function() {
     89                this.model.set({
     90                        themeFlexWidth: false,
     91                        themeFlexHeight: true,
     92                        imageWidth: 1000,
     93                        imageHeight: 600
     94                });
     95
     96                equal(this.model.shouldBeCropped(), false);
     97        });
     98
     99        test('should not be cropped when the theme supports flex height AND width', function() {
     100                this.model.set({
     101                        themeFlexWidth: true,
     102                        themeFlexHeight: true,
     103                        imageWidth: 10000,
     104                        imageHeight: 8600
     105                });
     106                equal(this.model.shouldBeCropped(), false);
     107        });
     108});