Player.html 14.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  <style type="text/css">
    .highlight { display: block; background-color: #ddd; }
  </style>
  <script type="text/javascript">
    function highlight() {
      document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
    }
  </script>
</head>
<body onload="prettyPrint(); highlight();">
  <pre class="prettyprint lang-js"><span id='Ext-ux-event-Player'>/**
</span> * This class manages the playback of an array of &quot;event descriptors&quot;. For details on the
 * contents of an &quot;event descriptor&quot;, see {@link Ext.ux.event.Recorder}. The events recorded by the
 * {@link Ext.ux.event.Recorder} class are designed to serve as input for this class.
 * 
 * The simplest use of this class is to instantiate it with an {@link #eventQueue} and call
 * {@link #method-start}. Like so:
 *
 *      var player = Ext.create('Ext.ux.event.Player', {
 *          eventQueue: [ ... ],
 *          speed: 2,  // play at 2x speed
 *          listeners: {
 *              stop: function () {
 *                  player = null; // all done
 *              }
 *          }
 *      });
 *
 *      player.start();
 *
 * A more complex use would be to incorporate keyframe generation after playing certain
 * events.
 *
 *      var player = Ext.create('Ext.ux.event.Player', {
 *          eventQueue: [ ... ],
 *          keyFrameEvents: {
 *              click: true
 *          },
 *          listeners: {
 *              stop: function () {
 *                  // play has completed... probably time for another keyframe...
 *                  player = null;
 *              },
 *              keyframe: onKeyFrame
 *          }
 *      });
 *
 *      player.start();
 *
 * If a keyframe can be handled immediately (synchronously), the listener would be:
 *
 *      function onKeyFrame () {
 *          handleKeyFrame();
 *      }
 *
 *  If the keyframe event is always handled asynchronously, then the event listener is only
 *  a bit more:
 *
 *      function onKeyFrame (p, eventDescriptor) {
 *          eventDescriptor.defer(); // pause event playback...
 *
 *          handleKeyFrame(function () {
 *              eventDescriptor.finish(); // ...resume event playback
 *          });
 *      }
 *
 * Finally, if the keyframe could be either handled synchronously or asynchronously (perhaps
 * differently by browser), a slightly more complex listener is required.
 *
 *      function onKeyFrame (p, eventDescriptor) {
 *          var async;
 *
 *          handleKeyFrame(function () {
 *              // either this callback is being called immediately by handleKeyFrame (in
 *              // which case async is undefined) or it is being called later (in which case
 *              // async will be true).
 *
 *              if (async) {
 *                  eventDescriptor.finish();
 *              } else {
 *                  async = false;
 *              }
 *          });
 *
 *          // either the callback was called (and async is now false) or it was not
 *          // called (and async remains undefined).
 *
 *          if (async !== false) {
 *              eventDescriptor.defer();
 *              async = true; // let the callback know that we have gone async
 *          }
 *      }
 */
Ext.define('Ext.ux.event.Player', {
    extend: 'Ext.ux.event.Driver',

<span id='Ext-ux-event-Player-cfg-eventQueue'>    /**
</span>     * @cfg {Array} eventQueue The event queue to playback. This must be provided before
     * the {@link #method-start} method is called.
     */

<span id='Ext-ux-event-Player-cfg-keyFrameEvents'>    /**
</span>     * @cfg {Object} keyFrameEvents An object that describes the events that should generate
     * keyframe events. For example, `{ click: true }` would generate keyframe events after
     * each `click` event.
     */
    keyFrameEvents: {
        click: true
    },

<span id='Ext-ux-event-Player-cfg-pauseForAnimations'>    /**
</span>     * @cfg {Boolean} pauseForAnimations True to pause event playback during animations, false
     * to ignore animations. Default is true.
     */
    pauseForAnimations: true,

<span id='Ext-ux-event-Player-cfg-speed'>    /**
</span>     * @cfg {Number} speed The playback speed multiplier. Default is 1.0 (to playback at the
     * recorded speed). A value of 2 would playback at 2x speed.
     */
    speed: 1.0,

    stallTime: 0,

    tagPathRegEx: /(\w+)(?:\[(\d+)\])?/,
    
    constructor: function (config) {
        var me = this;
        
        me.callParent(arguments);

        me.addEvents(
<span id='Ext-ux-event-Player-event-beforeplay'>            /**
</span>             * @event beforeplay
             * Fires before an event is played.
             * @param {Ext.ux.event.Player} this
             * @param {Object} eventDescriptor The event descriptor about to be played.
             */
            'beforeplay',

<span id='Ext-ux-event-Player-event-keyframe'>            /**
</span>             * @event keyframe
             * Fires when this player reaches a keyframe. Typically, this is after events
             * like `click` are injected and any resulting animations have been completed.
             * @param {Ext.ux.event.Player} this
             * @param {Object} eventDescriptor The keyframe event descriptor.
             */
            'keyframe'
        );

        me.eventObject = new Ext.EventObjectImpl();

        me.timerFn = function () {
            me.onTick();
        };
        me.attachTo = me.attachTo || window;
    },

<span id='Ext-ux-event-Player-method-getElementFromXPath'>    /**
</span>     * Returns the element given is XPath-like description.
     * @param {String} xpath The XPath-like description of the element.
     * @return {HTMLElement}
     */
    getElementFromXPath: function (xpath) {
        var me = this,
            parts = xpath.split('/'),
            regex = me.tagPathRegEx,
            i, n, m, count, tag, child,
            el = me.attachTo.document;

        el = (parts[0] == '~') ? el.body
                    : el.getElementById(parts[0].substring(1)); // remove '#'

        for (i = 1, n = parts.length; el &amp;&amp; i &lt; n; ++i) {
            m = regex.exec(parts[i]);
            count = m[2] ? parseInt(m[2], 10) : 1;
            tag = m[1].toUpperCase();

            for (child = el.firstChild; child; child = child.nextSibling) {
                if (child.tagName == tag) {
                    if (count == 1) {
                        break;
                    }
                    --count;
                }
            }

            el = child;
        }

        return el;
    },

    getTimeIndex: function () {
        var t = this.getTimestamp() - this.stallTime;
        return t * this.speed;
    },

    makeToken: function (eventDescriptor, signal) {
        var me = this,
            t0;

        eventDescriptor[signal] = true;

        eventDescriptor.defer = function () {
            eventDescriptor[signal] = false;
            t0 = me.getTime();
        };

        eventDescriptor.finish = function () {
            eventDescriptor[signal] = true;
            me.stallTime += me.getTime() - t0;

            me.schedule();
        };
    },

<span id='Ext-ux-event-Player-method-nextEvent'>    /**
</span>     * This method is called after an event has been played to prepare for the next event.
     * @param {Object} eventDescriptor The descriptor of the event just played.
     */
    nextEvent: function (eventDescriptor) {
        var me = this,
            index = ++me.queueIndex;

        // keyframe events are inserted after a keyFrameEvent is played.
        if (me.keyFrameEvents[eventDescriptor.type]) {
            Ext.Array.insert(me.eventQueue, index, [
                { keyframe: true, ts: eventDescriptor.ts }
            ]);
        }
    },

<span id='Ext-ux-event-Player-method-peekEvent'>    /**
</span>     * This method returns the event descriptor at the front of the queue. This does not
     * dequeue the event. Repeated calls return the same object (until {@link #nextEvent}
     * is called).
     */
    peekEvent: function () {
        var me = this,
            queue = me.eventQueue,
            index = me.queueIndex,
            eventDescriptor = queue[index],
            type = eventDescriptor &amp;&amp; eventDescriptor.type,
            tmp;

        if (type == 'mduclick') {
            tmp = [
                Ext.applyIf({ type: 'mousedown' }, eventDescriptor),
                Ext.applyIf({ type: 'mouseup' }, eventDescriptor),
                Ext.applyIf({ type: 'click' }, eventDescriptor)
            ];

            me.replaceEvent(index, tmp);
        }

        return queue[index] || null;
    },

    replaceEvent: function (index, events) {
        for (var t, i = 0, n = events.length; i &lt; n; ++i) {
            if (i) {
                t = events[i-1];
                delete t.afterplay;
                delete t.screenshot;

                delete events[i].beforeplay;
            }
        }

        Ext.Array.replace(this.eventQueue, index, 1, events);
    },

<span id='Ext-ux-event-Player-method-processEvents'>    /**
</span>     * This method dequeues and injects events until it has arrived at the time index. If
     * no events are ready (based on the time index), this method does nothing.
     * @return {Boolean} True if there is more to do; false if not (at least for now).
     */
    processEvents: function () {
        var me = this,
            animations = me.pauseForAnimations &amp;&amp; me.attachTo.Ext.fx.Manager.items,
            eventDescriptor;

        while ((eventDescriptor = me.peekEvent()) !== null) {
            if (animations &amp;&amp; animations.getCount()) {
                return true;
            }
            
            if (eventDescriptor.keyframe) {
                if (!me.processKeyFrame(eventDescriptor)) {
                    return false;
                }
                me.nextEvent(eventDescriptor);
            } else if (eventDescriptor.ts &lt;= me.getTimeIndex() &amp;&amp;
                       me.fireEvent('beforeplay', me, eventDescriptor) !== false &amp;&amp;
                       me.playEvent(eventDescriptor)) {
                if(window.__x &amp;&amp; eventDescriptor.screenshot) {
                     __x.poll.sendSyncRequest({cmd: 'screenshot'});
                }       
                me.nextEvent(eventDescriptor);
            } else {
                return true;
            }
        }

        me.stop();
        return false;
    },

<span id='Ext-ux-event-Player-method-processKeyFrame'>    /**
</span>     * This method is called when a keyframe is reached. This will fire the keyframe event.
     * If the keyframe has been handled, true is returned. Otherwise, false is returned.
     * @param {Object} The event descriptor of the keyframe.
     * @return {Boolean} True if the keyframe was handled, false if not.
     */
    processKeyFrame: function (eventDescriptor) {
        var me = this;

        // only fire keyframe event (and setup the eventDescriptor) once...
        if (!eventDescriptor.defer) {
            me.makeToken(eventDescriptor, 'done');
            me.fireEvent('keyframe', me, eventDescriptor);
        }

        return eventDescriptor.done;
    },

<span id='Ext-ux-event-Player-method-injectEvent'>    /**
</span>     * Called to inject the given event on the specified target.
     * @param {HTMLElement} target The target of the event.
     * @param {Ext.EventObject} The event to inject.
     */
    injectEvent: function (target, event) {
        event.injectEvent(target);
    },

    playEvent: function (eventDescriptor) {
        var me = this,
            target = me.getElementFromXPath(eventDescriptor.target),
            event;

        if (!target) {
            // not present (yet)... wait for element present...
            // TODO - need a timeout here
            return false;
        }

        if (!me.playEventHook(eventDescriptor, 'beforeplay')) {
            return false;
        }

        if (!eventDescriptor.injected) {
            eventDescriptor.injected = true;
            event = me.translateEvent(eventDescriptor, target);
            me.injectEvent(target, event);
        }

        return me.playEventHook(eventDescriptor, 'afterplay');
    },

    playEventHook: function (eventDescriptor, hookName) {
        var me = this,
            doneName = hookName + '.done',
            firedName = hookName + '.fired',
            hook = eventDescriptor[hookName];

        if (hook &amp;&amp; !eventDescriptor[doneName]) {
            if (!eventDescriptor[firedName]) {
                eventDescriptor[firedName] = true;
                me.makeToken(eventDescriptor, doneName);

                me.eventScope[hook](eventDescriptor);
            }
            return false;
        }

        return true;
    },

    schedule: function () {
        var me = this;
        if (!me.timer) {
            me.timer = setTimeout(me.timerFn, 10);
        }
    },

    translateEvent: function (eventDescriptor, target) {
        var me = this,
            event = me.eventObject,
            modKeys = eventDescriptor.modKeys || '',
            xy;

        if ('x' in eventDescriptor) {
            event.xy = xy = Ext.fly(target).getXY();
            xy[0] += eventDescriptor.x;
            xy[1] += eventDescriptor.y;
        }

        if ('wheel' in eventDescriptor) {
            // see getWheelDelta
        }

        event.type = eventDescriptor.type;
        event.button = eventDescriptor.button;
        event.altKey = modKeys.indexOf('A') &gt; 0;
        event.ctrlKey = modKeys.indexOf('C') &gt; 0;
        event.metaKey = modKeys.indexOf('M') &gt; 0;
        event.shiftKey = modKeys.indexOf('S') &gt; 0;
    
        return event;
    },

    //---------------------------------
    // Driver overrides

    onStart: function () {
        var me = this;

        me.queueIndex = 0;
        me.schedule();
    },

    onStop: function () {
        var me = this;

        if (me.timer) {
            clearTimeout(me.timer);
            me.timer = null;
        }
        if (window.__x) {
            __x.poll.sendSyncRequest({cmd: 'finish'});
        }
    },

    //---------------------------------

    onTick: function () {
        var me = this;

        me.timer = null;

        if (me.processEvents()) {
            me.schedule();
        }
    }
});
</pre>
</body>
</html>