<commit_before>
import AbstractComponent from "ima/page/AbstractComponent"

/**
 * Private field symbols.
 *
 * @type {Object<string, symbol>}
 */
const PRIVATE = Object.freeze({
  // fields
  eventBusListeners: Symbol("eventBusListeners"),
  domListeners: Symbol("domListeners"),
  dispatcherListeners: Symbol("dispatcherListeners"),
  pendingTimeouts: Symbol("pendingTimeouts"),
  activeIntervals: Symbol("activeIntervals"),

  // methods
  registerListener: Symbol("registerListener"),
  deregisterListener: Symbol("deregisterListener")
})

/**
 * Abstract UI component that automatically manages the registered DOM, event
 * bus and dispatcher event listeners, timeouts and intervals. The component
 * automatically deregisters all of these right before the component unmounts
 * from the DOM.
 *
 * @abstract
 */
export default class AbstractManagedComponent extends AbstractComponent {
  /**
   * Initializes the component.
   *
   * @param {Object<string, *>} props Component properties.
   * @param {Object<string, *>} context Component's context.
   */
  constructor(props, context) {
    if (!context || !context.$Utils || !context.$Utils.$Dispatcher) {
      throw new Error("The React context needs to be provided, it must " +
          "contain the view utils in the $Utils property, and the view " +
          "utils must contain the IMA event dispatcher in the $Dispatcher " +
          "property")
    }

    super(props, context)

    if ($Debug) {
      if (
        this.componentWillUnmount !==
        AbstractManagedComponent.prototype.componentWillUnmount
      ) {
        throw new TypeError("The componentWillUnmount method is final and " +
            "cannot be overridden, use the onBeforeUnmount method instead")
      }
    }

    /**
     * Storage of the registered DOM event listeners.
     *
     * @type {Map<EventTarget, Map<string, Map<
     *         function(Event),
     *         function(Event)
     *       >>>}
     */
    this[PRIVATE.domListeners] = new Map()

    /**
     * Storage of the registered event bus listeners.
     *
     * @type {Map<EventTarget, Map<string, Map<
     *         function(Event),
     *         function(Event)
     *       >>>}
     */
    this[PRIVATE.eventBusListeners] = new Map()

    /**
     * Map of dispatcher event names to the registered callbacks.
     *
     * @type {Map<string, Set<function(*)>>}
     */
    this[PRIVATE.dispatcherListeners] = new Map()

    /**
     * Map of registered callbacks executed with a delay that have not been
     * executed yet to the native timeout IDs.
     *
     * @type {Map<function(), number>}
     */
    this[PRIVATE.pendingTimeouts] = new Map()

    /**
     * Map of registered callbacks executed periodically to the native interval
     * IDs.
     *
     * @type {Map<function(), number>}
     */
    this[PRIVATE.activeIntervals] = new Map()
  }

  /**
   * Replacement of the {@linkcode componentWillUnmount()} method that can be
   * overridden by the component extending this class.
   */
  onBeforeUnmount() {}

  /**
   * Registers the provided event listener for execution when the specified
   * event occurs at the specified event target.
   *
   * The listener will be automatically deregistered right before the component
   * will be unmounted from the DOM (by the {@linkcode componentWillUnmount()}
   * method).
   *
   * The listener will automatically have its {@code this} context bound to
   * this instance.
   *
   * @param {(ReactComponent|EventTarget)} eventTarget The event target at
   *        which the event is to be listened for.
   * @param {string} eventName The name of the event to listen for.
   * @param {function(Event)} listener The listener to register.
   */
  addDomListener(eventTarget, eventName, listener) {
    if (!eventTarget.addEventListener) {
      eventTarget = this.findDOMNode(eventTarget)
    }

    let realListener = this[PRIVATE.registerListener](
      this[PRIVATE.domListeners],
      eventTarget,
      eventName,
      listener
    )

    if (realListener) {
      eventTarget.addEventListener(eventName, realListener)
    }
  }

  /**
   * Deregisters the specified event listener from execution of the specified
   * DOM event on the provided event target.
   *
   * The method has no effect if the listener is not registered.
   *
   * @param {(ReactComponent|EventTarget)} eventTarget The event target at
   *        which the event was listened for.
   * @param {string} eventName The name of the event listened for.
   * @param {function(Event)} listener The listener to deregister.
   */
  removeDomListener(eventTarget, eventName, listener) {
    if (!eventTarget.addEventListener) {
      eventTarget = this.findDOMNode(eventTarget)
    }

    let realListener = this[PRIVATE.deregisterListener](
      this[PRIVATE.domListeners],
      eventTarget,
      eventName,
      listener
    )

    if (realListener) {
      eventTarget.removeEventListener(eventName, realListener)
    }
  }

  /**
   * Registers the provided event listener for execution whenever an IMA.js
   * DOM custom event of the specified name occurs at the specified event
   * target.
   *
   * The listener will be automatically deregistered right before the component
   * will be unmounted from the DOM (by the {@linkcode componentWillUnmount()}
   * method).
   *
   * The listener will automatically have its {@code this} context bound to
   * this instance.
   *
   * @method listen
   * @param {(ReactElement|EventTarget)} eventTarget The react component or
   *        event target at which the listener should listen for the event.
   * @param {string} eventName The name of the event for which to listen.
   * @param {function(Event)} listener The listener for event to register.
   */
  listen(eventTarget, eventName, listener) {
    let realListener = this[PRIVATE.registerListener](
      this[PRIVATE.eventBusListeners],
      eventTarget,
      eventName,
      listener
    )

    if (realListener) {
      super.listen(eventTarget, eventName, realListener)
    }
  }

  /**
   * Deregisters the provided event listener for an IMA.js DOM custom event
   * of the specified name at the specified event target.
   *
   * @method unlisten
   * @param {(ReactElement|EventTarget)} eventTarget The react component or
   *        event target at which the listener should listen for the event.
   * @param {string} eventName The name of the event for which to listen.
   * @param {function(Event)} listener The listener for event to register.
   */
  unlisten(eventTarget, eventName, listener) {
    let realListener = this[PRIVATE.deregisterListener](
      this[PRIVATE.eventBusListeners],
      eventTarget,
      eventName,
      listener
    )

    if (realListener) {
      super.unlisten(eventTarget, eventName, realListener)
    }
  }

  /**
   * Registers the provided event listener to be executed when the specified
   * event occurs on the IMA event dispatcher.
   *
   * The listener will be automatically deregistered right before the component
   * will be unmounted from the DOM (by the {@linkcode componentWillUnmount()}
   * method).
   *
   * The listener will automatically have its {@code this} context bound to
   * this instance.
   *
   * @param {string} eventName The name of the event.
   * @param {function(*)} listener The event listener to register.
   */
  addDispatcherListener(eventName, listener) {
    if (!this[PRIVATE.dispatcherListeners].has(eventName)) {
      this[PRIVATE.dispatcherListeners].set(eventName, new Set())
    }
    let listeners = this[PRIVATE.dispatcherListeners].get(eventName)

    this.utils.$Dispatcher.listen(eventName, listener, this)

    listeners.add(listener)
  }

  /**
   * Deregisters the provided event listener from execution of the occurrence
   * of the specified event on the IMA event dispatcher.
   *
   * The method has no effect if the listener is not registered.
   *
   * @param {string} eventName The name of the event.
   * @param {function(*)} listener The event listener to deregister.
   */
  removeDispatcherListener(eventName, listener) {
    if (!this[PRIVATE.dispatcherListeners].has(eventName)) {
      return
    }
    let listeners = this[PRIVATE.dispatcherListeners].get(eventName)
    if (!listeners.has(listener)) {
      return
    }

    this.utils.$Dispatcher.unlisten(eventName, listener, this)

    listeners.delete(listener)
    if (!listeners.size()) {
      this[PRIVATE.dispatcherListeners].delete(eventName)
    }
  }

  /**
   * Registers the provided callback to be executed after the specified delay.
   *
   * The callback will be automatically deregistered right before the component
   * will be unmounted from the DOM (by the {@linkcode componentWillUnmount()}
   * method).
   *
   * The callback will automatically have its {@code this} context bound to
   * this instance.
   *
   * @param {function()} callback The callback to schedule for execution.
   * @param {number} delay The delay in milliseconds after which the callback
   *        should be executed.
   */
  setTimeout(callback, delay) {
    if (this[PRIVATE.pendingTimeouts].has(callback)) {
      throw new Error("The provided callback is already pending to be " +
          "executed. If you need to reschedule the callback execution, " +
          "clear the callback's scheduled timeout execution using the " +
          "clearTimeout() method first")
    }

    let timeoutId = setTimeout(() => {
      callback.call(this)
      this[PRIVATE.pendingTimeouts].delete(callback)
    }, delay)
    this[PRIVATE.pendingTimeouts].set(callback, timeoutId)
  }

  /**
   * Cancels the scheduled delayed execution of the provided callback. The
   * method has no effect if the callback is not registered for delayed
   * execution.
   *
   * @param {function()} callback The callback that is scheduled for execution.
   */
  clearTimeout(callback) {
    if (!this[PRIVATE.pendingTimeouts].has(callback)) {
      return // nothing to do
    }

    clearTimeout(this[PRIVATE.pendingTimeouts].get(callback))
    this[PRIVATE.pendingTimeouts].delete(callback)
  }

  /**
   * Registers the provided callback to be executed periodically.
   *
   * The callback will be automatically deregistered right before the component
   * will be unmounted from the DOM (by the {@linkcode componentWillUnmount()}
   * method).
   *
   * The callback will automatically have its {@code this} context bound to
   * this instance.
   *
   * @param {function()} callback The callback to execute periodically.
   * @param {number} period The time period at which the provided callback
   *        should be executed, in milliseconds.
   */
  setInterval(callback, period) {
    if (this[PRIVATE.activeIntervals].has(callback)) {
      throw new Error("The provided callback is already registered to be " +
          "executed periodically. If you need to reschedule the callback " +
          "execution, clear the callback's scheduled interval execution " +
          "using the clearInterval() method first")
    }

    let intervalId = setInterval(() => {
      callback.call(this)
      this[PRIVATE.activeIntervals].delete(callback)
    }, period)
    this[PRIVATE.activeIntervals].set(callback, intervalId)
  }

  /**
   * Cancels the periodic execution of the provided callback. The method has
   * no effect if the callback is not registered of execution.
   *
   * @param {function()} callback The callback that should no longer be
   *        executed periodically.
   */
  clearInterval(callback) {
    if (!this[PRIVATE.activeIntervals].has(callback)) {
      return // nothing to do
    }

    clearInterval(this[PRIVATE.activeIntervals].get(callback))
    this[PRIVATE.activeIntervals].delete(callback)
  }

  /**
   * Executes the {@linkcode onBeforeUnmount}, then deregisters all registered
   * event bus, dispatcher and DOM event listeners, all pending timeouts and
   * active intervals registered by this component.
   *
   * @override
   */
  componentWillUnmount() {
    this.onBeforeUnmount()

    for (let eventTarget of this[PRIVATE.eventBusListeners].keys()) {
      let eventListeners = this[PRIVATE.eventBusListeners].get(eventTarget)
      for (let eventName of eventListeners.keys()) {
        for (let realListener of eventListeners.get(eventName).values()) {
          super.unlisten(eventTarget, eventName, realListener)
        }
      }
    }
    for (let eventTarget of this[PRIVATE.domListeners].keys()) {
      let eventListeners = this[PRIVATE.domListeners].get(eventTarget)
      for (let eventName of eventListeners.keys()) {
        for (let realListener of eventListeners.get(eventName).values()) {
          eventTarget.removeEventListener(eventName, realListener)
        }
      }
    }
    for (let eventName of this[PRIVATE.dispatcherListeners].keys()) {
      for (let listener of this[PRIVATE.dispatcherListeners].get(eventName)) {
        this.utils.$Dispatcher.unlisten(eventName, listener, this)
      }
    }
    for (let timeoutId of this[PRIVATE.pendingTimeouts].values()) {
      clearTimeout(timeoutId)
    }
    for (let intervalId of this[PRIVATE.activeIntervals].values()) {
      clearInterval(intervalId)
    }

    // clear the managed listeners
    this[PRIVATE.eventBusListeners].clear()
    this[PRIVATE.domListeners].clear()
    this[PRIVATE.dispatcherListeners].clear()
    this[PRIVATE.pendingTimeouts].clear()
    this[PRIVATE.activeIntervals].clear()
  }

  /**
   * Registers the specified event listeners within the provided storage. The
   * structure of the storage will be automatically updated as necessary.
   *
   * The method returns a new listener that will execute the provided listener
   * with the {@code this} context bound to this component instance.
   *
   * @param {Map<EventTarget, Map<string, Map<
   *          function(Event),
   *          function(Event)
   *        >>>} listenerStorage The storage of the managed events.
   * @param {(ReactComponent|EventTarget)} eventTarget The event target at
   *        which the event will be listened for.
   * @param {string} eventName The name of the event on which the listener is
   *        to be executed.
   * @param {function(*)} listener The event listener to execute on the
   *        specified event's occurrence.
   * @return {?function(*)} The listener to pass to the underlying event API.
   */
  [PRIVATE.registerListener](listenerStorage, eventTarget, eventName,
      listener) {
    if (!eventTarget.addEventListener) {
      eventTarget = this.findDOMNode(eventTarget)
    }

    if (!listenerStorage.has(eventTarget)) {
      listenerStorage.set(eventTarget, new Map())
    }
    let eventListeners = listenerStorage.get(eventTarget)
    if (!eventListeners.has(eventName)) {
      eventListeners.set(eventName, new Map())
    }
    let listeners = eventListeners.get(eventName)
    if (listeners.has(listener)) {
      return null // already listening for the event
    }

    let realListener = listener.bind(this)
    listeners.set(listener, realListener)

    return realListener
  }

  /**
   * Deregisters the specified event listener from the provided storage. The
   * method automatically clears off the empty parts of the storage's tree
   * structure that would be left after the removal of the event listener.
   *
   * @param {Map<EventTarget, Map<string, Map<
   *          function(Event),
   *          function(Event)
   *        >>>} listenerStorage The storage of the managed events.
   * @param {(ReactComponent|EventTarget)} eventTarget The event target at
   *        which the event was listened for.
   * @param {string} eventName The name of the event on which the listener was
   *        to be executed.
   * @param {function(*)} listener The listener that was to be executed on the
   *        specified event's occurrence.
   * @return {?function(*)} The listener that was passed to the underlying
   *         event API, or {@code null} if the provided listener was not
   *         registered.
   */
  [PRIVATE.deregisterListener](listenerStorage, eventTarget, eventName,
      listener) {
    if (!eventTarget.addEventListener) {
      eventTarget = this.findDOMNode(eventTarget)
    }

    if (!listenerStorage.has(eventTarget)) {
      return null
    }
    let eventListeners = listenerStorage.get(eventTarget)
    if (!eventListeners.has(eventName)) {
      return null
    }
    let listeners = eventListeners.get(eventName)
    if (!listeners.has(listener)) {
      return null
    }
    let realListener = listeners.get(listener)

    listeners.delete(listener)
    if (!listeners.size()) {
      eventListeners.delete(eventName)
    }
    if (!eventListeners.size()) {
      listenerStorage.delete(eventTarget)
    }

    return realListener
  }
}
<commit_msg>switched to IMA.js code style<commit_after>
import AbstractComponent from 'ima/page/AbstractComponent';

/**
 * Private field symbols.
 *
 * @type {Object<string, symbol>}
 */
const PRIVATE = Object.freeze({
	// fields
	eventBusListeners: Symbol('eventBusListeners'),
	domListeners: Symbol('domListeners'),
	dispatcherListeners: Symbol('dispatcherListeners'),
	pendingTimeouts: Symbol('pendingTimeouts'),
	activeIntervals: Symbol('activeIntervals'),

	// methods
	registerListener: Symbol('registerListener'),
	deregisterListener: Symbol('deregisterListener')
});

/**
 * Abstract UI component that automatically manages the registered DOM, event
 * bus and dispatcher event listeners, timeouts and intervals. The component
 * automatically deregisters all of these right before the component unmounts
 * from the DOM.
 *
 * @abstract
 */
export default class AbstractManagedComponent extends AbstractComponent {
	/**
	 * Initializes the component.
	 *
	 * @param {Object<string, *>} props Component properties.
	 * @param {Object<string, *>} context Component's context.
	 */
	constructor(props, context) {
		if (!context || !context.$Utils || !context.$Utils.$Dispatcher) {
			throw new Error('The React context needs to be provided, it ' +
					'must contain the view utils in the $Utils property, ' +
					'and the view utils must contain the IMA event ' +
					'dispatcher in the $Dispatcher property');
		}

		super(props, context);

		if ($Debug) {
			if (
				this.componentWillUnmount !==
				AbstractManagedComponent.prototype.componentWillUnmount
			) {
				throw new TypeError('The componentWillUnmount method is ' +
						'final and cannot be overridden, use the ' +
						'onBeforeUnmount method instead');
			}
		}

		/**
		 * Storage of the registered DOM event listeners.
		 *
		 * @type {Map<EventTarget, Map<string, Map<
		 *         function(Event),
		 *         function(Event)
		 *       >>>}
		 */
		this[PRIVATE.domListeners] = new Map();

		/**
		 * Storage of the registered event bus listeners.
		 *
		 * @type {Map<EventTarget, Map<string, Map<
		 *         function(Event),
		 *         function(Event)
		 *       >>>}
		 */
		this[PRIVATE.eventBusListeners] = new Map();

		/**
		 * Map of dispatcher event names to the registered callbacks.
		 *
		 * @type {Map<string, Set<function(*)>>}
		 */
		this[PRIVATE.dispatcherListeners] = new Map();

		/**
		 * Map of registered callbacks executed with a delay that have not been
		 * executed yet to the native timeout IDs.
		 *
		 * @type {Map<function(), number>}
		 */
		this[PRIVATE.pendingTimeouts] = new Map();

		/**
		 * Map of registered callbacks executed periodically to the native
		 * interval IDs.
		 *
		 * @type {Map<function(), number>}
		 */
		this[PRIVATE.activeIntervals] = new Map();
	}

	/**
	 * Replacement of the {@linkcode componentWillUnmount()} method that can be
	 * overridden by the component extending this class.
	 */
	onBeforeUnmount() {}

	/**
	 * Registers the provided event listener for execution when the specified
	 * event occurs at the specified event target.
	 *
	 * The listener will be automatically deregistered right before the
	 * component will be unmounted from the DOM (by the
	 * {@linkcode componentWillUnmount()} method).
	 *
	 * The listener will automatically have its {@code this} context bound to
	 * this instance.
	 *
	 * @param {(ReactComponent|EventTarget)} eventTarget The event target at
	 *        which the event is to be listened for.
	 * @param {string} eventName The name of the event to listen for.
	 * @param {function(Event)} listener The listener to register.
	 */
	addDomListener(eventTarget, eventName, listener) {
		if (!eventTarget.addEventListener) {
			eventTarget = this.findDOMNode(eventTarget);
		}

		let realListener = this[PRIVATE.registerListener](
			this[PRIVATE.domListeners],
			eventTarget,
			eventName,
			listener
		);

		if (realListener) {
			eventTarget.addEventListener(eventName, realListener);
		}
	}

	/**
	 * Deregisters the specified event listener from execution of the specified
	 * DOM event on the provided event target.
	 *
	 * The method has no effect if the listener is not registered.
	 *
	 * @param {(ReactComponent|EventTarget)} eventTarget The event target at
	 *        which the event was listened for.
	 * @param {string} eventName The name of the event listened for.
	 * @param {function(Event)} listener The listener to deregister.
	 */
	removeDomListener(eventTarget, eventName, listener) {
		if (!eventTarget.addEventListener) {
			eventTarget = this.findDOMNode(eventTarget);
		}

		let realListener = this[PRIVATE.deregisterListener](
			this[PRIVATE.domListeners],
			eventTarget,
			eventName,
			listener
		);

		if (realListener) {
			eventTarget.removeEventListener(eventName, realListener);
		}
	}

	/**
	 * Registers the provided event listener for execution whenever an IMA.js
	 * DOM custom event of the specified name occurs at the specified event
	 * target.
	 *
	 * The listener will be automatically deregistered right before the
	 * component will be unmounted from the DOM (by the
	 * {@linkcode componentWillUnmount()} method).
	 *
	 * The listener will automatically have its {@code this} context bound to
	 * this instance.
	 *
	 * @method listen
	 * @param {(ReactElement|EventTarget)} eventTarget The react component or
	 *        event target at which the listener should listen for the event.
	 * @param {string} eventName The name of the event for which to listen.
	 * @param {function(Event)} listener The listener for event to register.
	 */
	listen(eventTarget, eventName, listener) {
		let realListener = this[PRIVATE.registerListener](
			this[PRIVATE.eventBusListeners],
			eventTarget,
			eventName,
			listener
		);

		if (realListener) {
			super.listen(eventTarget, eventName, realListener);
		}
	}

	/**
	 * Deregisters the provided event listener for an IMA.js DOM custom event
	 * of the specified name at the specified event target.
	 *
	 * @method unlisten
	 * @param {(ReactElement|EventTarget)} eventTarget The react component or
	 *        event target at which the listener should listen for the event.
	 * @param {string} eventName The name of the event for which to listen.
	 * @param {function(Event)} listener The listener for event to register.
	 */
	unlisten(eventTarget, eventName, listener) {
		let realListener = this[PRIVATE.deregisterListener](
			this[PRIVATE.eventBusListeners],
			eventTarget,
			eventName,
			listener
		);

		if (realListener) {
			super.unlisten(eventTarget, eventName, realListener);
		}
	}

	/**
	 * Registers the provided event listener to be executed when the specified
	 * event occurs on the IMA event dispatcher.
	 *
	 * The listener will be automatically deregistered right before the
	 * component will be unmounted from the DOM (by the
	 * {@linkcode componentWillUnmount()} method).
	 *
	 * The listener will automatically have its {@code this} context bound to
	 * this instance.
	 *
	 * @param {string} eventName The name of the event.
	 * @param {function(*)} listener The event listener to register.
	 */
	addDispatcherListener(eventName, listener) {
		if (!this[PRIVATE.dispatcherListeners].has(eventName)) {
			this[PRIVATE.dispatcherListeners].set(eventName, new Set());
		}
		let listeners = this[PRIVATE.dispatcherListeners].get(eventName);

		this.utils.$Dispatcher.listen(eventName, listener, this);

		listeners.add(listener);
	}

	/**
	 * Deregisters the provided event listener from execution of the occurrence
	 * of the specified event on the IMA event dispatcher.
	 *
	 * The method has no effect if the listener is not registered.
	 *
	 * @param {string} eventName The name of the event.
	 * @param {function(*)} listener The event listener to deregister.
	 */
	removeDispatcherListener(eventName, listener) {
		if (!this[PRIVATE.dispatcherListeners].has(eventName)) {
			return;
		}
		let listeners = this[PRIVATE.dispatcherListeners].get(eventName);
		if (!listeners.has(listener)) {
			return;
		}

		this.utils.$Dispatcher.unlisten(eventName, listener, this);

		listeners.delete(listener);
		if (!listeners.size()) {
			this[PRIVATE.dispatcherListeners].delete(eventName);
		}
	}

	/**
	 * Registers the provided callback to be executed after the specified
	 * delay.
	 *
	 * The callback will be automatically deregistered right before the
	 * component will be unmounted from the DOM (by the
	 * {@linkcode componentWillUnmount()} method).
	 *
	 * The callback will automatically have its {@code this} context bound to
	 * this instance.
	 *
	 * @param {function()} callback The callback to schedule for execution.
	 * @param {number} delay The delay in milliseconds after which the callback
	 *        should be executed.
	 */
	setTimeout(callback, delay) {
		if (this[PRIVATE.pendingTimeouts].has(callback)) {
			throw new Error('The provided callback is already pending to be ' +
					'executed. If you need to reschedule the callback ' +
					'execution, clear the callback\'s scheduled timeout ' +
					'execution using the clearTimeout() method first');
		}

		let timeoutId = setTimeout(() => {
			callback.call(this);
			this[PRIVATE.pendingTimeouts].delete(callback);
		}, delay);
		this[PRIVATE.pendingTimeouts].set(callback, timeoutId);
	}

	/**
	 * Cancels the scheduled delayed execution of the provided callback. The
	 * method has no effect if the callback is not registered for delayed
	 * execution.
	 *
	 * @param {function()} callback The callback that is scheduled for
	 *        execution.
	 */
	clearTimeout(callback) {
		if (!this[PRIVATE.pendingTimeouts].has(callback)) {
			return; // nothing to do
		}

		clearTimeout(this[PRIVATE.pendingTimeouts].get(callback));
		this[PRIVATE.pendingTimeouts].delete(callback);
	}

	/**
	 * Registers the provided callback to be executed periodically.
	 *
	 * The callback will be automatically deregistered right before the
	 * component will be unmounted from the DOM (by the
	 * {@linkcode componentWillUnmount()} method).
	 *
	 * The callback will automatically have its {@code this} context bound to
	 * this instance.
	 *
	 * @param {function()} callback The callback to execute periodically.
	 * @param {number} period The time period at which the provided callback
	 *        should be executed, in milliseconds.
	 */
	setInterval(callback, period) {
		if (this[PRIVATE.activeIntervals].has(callback)) {
			throw new Error('The provided callback is already registered to ' +
					'be executed periodically. If you need to reschedule ' +
					'the callback execution, clear the callback\'s ' +
					'scheduled interval execution using the clearInterval() ' +
					'method first');
		}

		let intervalId = setInterval(() => {
			callback.call(this);
			this[PRIVATE.activeIntervals].delete(callback);
		}, period)
		this[PRIVATE.activeIntervals].set(callback, intervalId);
	}

	/**
	 * Cancels the periodic execution of the provided callback. The method has
	 * no effect if the callback is not registered of execution.
	 *
	 * @param {function()} callback The callback that should no longer be
	 *        executed periodically.
	 */
	clearInterval(callback) {
		if (!this[PRIVATE.activeIntervals].has(callback)) {
			return; // nothing to do
		}

		clearInterval(this[PRIVATE.activeIntervals].get(callback));
		this[PRIVATE.activeIntervals].delete(callback);
	}

	/**
	 * Executes the {@linkcode onBeforeUnmount}, then deregisters all
	 * registered event bus, dispatcher and DOM event listeners, all pending
	 * timeouts and active intervals registered by this component.
	 *
	 * @override
	 */
	componentWillUnmount() {
		this.onBeforeUnmount();

		let eventBusListeners = this[PRIVATE.eventBusListeners];
		for (let eventTarget of eventBusListeners.keys()) {
			let eventListeners = eventBusListeners.get(eventTarget);
			for (let eventName of eventListeners.keys()) {
				let realListeners = eventListeners.get(eventName).values();
				for (let realListener of realListeners) {
					super.unlisten(eventTarget, eventName, realListener);
				}
			}
		}
		for (let eventTarget of this[PRIVATE.domListeners].keys()) {
			let eventListeners = this[PRIVATE.domListeners].get(eventTarget);
			for (let eventName of eventListeners.keys()) {
				let realListeners = eventListeners.get(eventName).values();
				for (let realListener of realListeners) {
					eventTarget.removeEventListener(eventName, realListener);
				}
			}
		}
		let dispatcherListeners = this[PRIVATE.dispatcherListeners];
		for (let eventName of dispatcherListeners.keys()) {
			for (let listener of dispatcherListeners.get(eventName)) {
				this.utils.$Dispatcher.unlisten(eventName, listener, this);
			}
		}
		for (let timeoutId of this[PRIVATE.pendingTimeouts].values()) {
			clearTimeout(timeoutId);
		}
		for (let intervalId of this[PRIVATE.activeIntervals].values()) {
			clearInterval(intervalId);
		}

		// clear the managed listeners
		this[PRIVATE.eventBusListeners].clear();
		this[PRIVATE.domListeners].clear();
		this[PRIVATE.dispatcherListeners].clear();
		this[PRIVATE.pendingTimeouts].clear();
		this[PRIVATE.activeIntervals].clear();
	}

	/**
	 * Registers the specified event listeners within the provided storage. The
	 * structure of the storage will be automatically updated as necessary.
	 *
	 * The method returns a new listener that will execute the provided listener
	 * with the {@code this} context bound to this component instance.
	 *
	 * @param {Map<EventTarget, Map<string, Map<
	 *          function(Event),
	 *          function(Event)
	 *        >>>} listenerStorage The storage of the managed events.
	 * @param {(ReactComponent|EventTarget)} eventTarget The event target at
	 *        which the event will be listened for.
	 * @param {string} eventName The name of the event on which the listener is
	 *        to be executed.
	 * @param {function(*)} listener The event listener to execute on the
	 *        specified event's occurrence.
	 * @return {?function(*)} The listener to pass to the underlying event API.
	 */
	[PRIVATE.registerListener](listenerStorage, eventTarget, eventName,
			listener) {
		if (!eventTarget.addEventListener) {
			eventTarget = this.findDOMNode(eventTarget);
		}

		if (!listenerStorage.has(eventTarget)) {
			listenerStorage.set(eventTarget, new Map());
		}
		let eventListeners = listenerStorage.get(eventTarget);
		if (!eventListeners.has(eventName)) {
			eventListeners.set(eventName, new Map());
		}
		let listeners = eventListeners.get(eventName);
		if (listeners.has(listener)) {
			return null; // already listening for the event
		}

		let realListener = listener.bind(this);
		listeners.set(listener, realListener);

		return realListener;
	}

	/**
	 * Deregisters the specified event listener from the provided storage. The
	 * method automatically clears off the empty parts of the storage's tree
	 * structure that would be left after the removal of the event listener.
	 *
	 * @param {Map<EventTarget, Map<string, Map<
	 *          function(Event),
	 *          function(Event)
	 *        >>>} listenerStorage The storage of the managed events.
	 * @param {(ReactComponent|EventTarget)} eventTarget The event target at
	 *        which the event was listened for.
	 * @param {string} eventName The name of the event on which the listener was
	 *        to be executed.
	 * @param {function(*)} listener The listener that was to be executed on the
	 *        specified event's occurrence.
	 * @return {?function(*)} The listener that was passed to the underlying
	 *         event API, or {@code null} if the provided listener was not
	 *         registered.
	 */
	[PRIVATE.deregisterListener](listenerStorage, eventTarget, eventName,
			listener) {
		if (!eventTarget.addEventListener) {
			eventTarget = this.findDOMNode(eventTarget);
		}

		if (!listenerStorage.has(eventTarget)) {
			return null;
		}
		let eventListeners = listenerStorage.get(eventTarget);
		if (!eventListeners.has(eventName)) {
			return null;
		}
		let listeners = eventListeners.get(eventName);
		if (!listeners.has(listener)) {
			return null;
		}
		let realListener = listeners.get(listener);

		listeners.delete(listener);
		if (!listeners.size()) {
			eventListeners.delete(eventName);
		}
		if (!eventListeners.size()) {
			listenerStorage.delete(eventTarget);
		}

		return realListener;
	}
}
<|endoftext|>


<commit_before>var AWS = require('aws-sdk')
  , ac = require('./config/aws.json')
  , https = require('https')
  , fs = require('fs')
  , temp = '/tmp/'
  , exec = require('child_process').exec
  , Promise = require('bluebird')
  , MessageQueue = require('./util/message_queue.js')
  , FileRepo = require('./util/file_repo.js');

var sqs = new AWS.SQS();
var CuraEngine = /darwin/.test(process.platform) ? 'CuraEngine_darwin' : 'CuraEngine';

function runLoop() {
  MessageQueue.poolMessage(ac.sqs_run)
  .then(sliceStl)
  .then(runLoop)
  .catch(function(err) {
    console.info("ERROR: ", err);
    return runLoop();
  })
}

function runSlicer(configFile, stl, gcodeFilePath) {
  return new Promise(function(resolve, reject) {
    console.info('-- SLICE');
    var cmd = "CURA_ENGINE_SEARCH_PATH=./ ./"+CuraEngine+" slice -v -j "+configFile+" -l "+stl;
    cmd += " -s mesh_position_z=\"0\" -s center_object=\"true\"";
    cmd += " -o "+gcodeFilePath;
    console.info(cmd);
    exec(cmd, function callback(err, stdout, stderr) {
      if (err) {
        console.info("SLICING FAILED, ", err)
        reject(err);
      } else {
        console.info(stderr);
        console.info(stdout);
        // cura writes output to stderr for some reason...
        resolve(stderr);
      }
    });
  });
}

function buildSimpleConfig(inFilePath, outFilePath,  params) {
  return new Promise(function(resolve, reject) {
    var jsonConfig = require(inFilePath);

    // resolution
    switch(params.resolution) {
      case 'low':
        jsonConfig.overrides.layer_height = { "default_value": 0.2 };
        break;

      case 'standard':
        jsonConfig.overrides.layer_height = { "default_value": 0.1 };
        break;

      case 'high':
        jsonConfig.overrides.layer_height = { "default_value": 0.05 };
        break;
    }

    // infill
    switch(params.infill) {
      case 'hollow':
        jsonConfig.overrides.infill_line_distance = { "default_value": 0 };
        break;

      case 'light':
        jsonConfig.overrides.infill_line_distance = { "default_value": 5 };
        break;

      case 'standard':
        jsonConfig.overrides.infill_line_distance = { "default_value": 2 };
        break;

      case 'medium':
        jsonConfig.overrides.infill_line_distance = { "default_value": 1 };
        break;

      case 'heavy':
        jsonConfig.overrides.infill_line_distance = { "default_value": .5 };
        break;

      case 'solid':
        jsonConfig.overrides.infill_line_distance = { "default_value": 100 };
        break;
    }

    // support
    if (params.support)
      jsonConfig.overrides.support_enable = { "default_value": true };

    // brim
    if (params.brim)
      jsonConfig.overrides.adhesion_type = { "default_value": "Brim" };

    // write config to file
    fs.writeFile(outFilePath, JSON.stringify(jsonConfig), 'utf8', function(err, res) {
      if (err)
        reject(err);
      else {
        resolve();
      }
    });
  });
}

function uploadFile(filePath, bucket, key) {
  console.info("-- UPLOADING FILE: ", key);
  return new Promise(function(resolve, reject) {
    fs.readFile(filePath, function(err, data) {
      if (err) {
        reject(err);
      } else {
        var params = {
          Bucket: bucket,
          Key: key,
          Body: data,
          ACL: 'public-read'
        };
        var s3bucket = new AWS.S3({"params": { Bucket: bucket }});
        s3bucket.upload(params, function(err, sres) {
          if (err) {
            reject(err);
          } else {
            resolve(sres);
          }
        });
      }
    });
  });
}

function getLinesCount(filePath) {
  return new Promise(function(resolve, reject) {
    exec("sed -n '$=' "+filePath, function callback(err, stdout, stderr) {
      console.info("-- TOTAL LINES: ", stdout);
      resolve(stdout.trim());
    });
  })
}

function writeGcodeHeader(inFilePath, slicerOut, event) {
  console.info("-- WRITING GCODE HEADER ");
  return new Promise(function(resolve, reject) {
    // first read line count
    getLinesCount(inFilePath)
    .then(function(lineCount) {
      var s = slicerOut.split("Print time: ")[1].split("\n")
        , t = s[1].split(" ")
        , v = s[2].split(" ")[1];

      var head = {
        "time": s[0],
        "readable": t[3]+" "+t[4],
        "volume": v,
        "filament": Math.round(v/(Math.pow((Math.PI*(1.75/2)), 2)))
      };

      function capitalize(s) {
        return s[0].toUpperCase() + s.slice(1);
      }

      head.lines = (lineCount);
      head.resolution = capitalize(event.resolution);
      head.support = event.support;
      head.infill = capitalize(event.infill);
      head.brim = event.brim;

      var hs = ";" + JSON.stringify(head);

      // write to file
      exec('echo "'+(hs.replace(/"/g, '\\"').replace("\n", ""))+'\n$(cat '+inFilePath+')" > '+inFilePath, function callback(err, stdout, stderr) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    })
    .catch(function(err) {
      reject(err);
    })
  });
}

function sliceStl(res) {

  return new Promise(function(resolve, reject) {

    console.info("IN SLICE STL ", res)
    if (!res.Messages)
      return reject('empty message');

    var message = res.Messages[0]
      , event = JSON.parse(message.Body)

    if (!event.id || !event.file_path || !event.user)
      return reject("Required parameters missing");

    var s3 = new AWS.S3()
      , keyPath = 'u/'+(event.user)+'/i/'+(event.id)+'/'
      , stlFilePath = "/tmp/obj_"+(event.id)+".stl"
      , bucket = 'files.printrapp.com'
      , configDefault = './simple.json'
      , configOut = '/tmp/config_'+(event.id)+'.json'
      , gcodeFilePath = '/tmp/out_'+(event.id)+'.gco'

    // download stl
    FileRepo.downloadFromS3(event.file_path, stlFilePath)
      .then(function() {
        // build config file
        return buildSimpleConfig(configDefault, configOut, event);
      })
      .then(function() {
        // run slicer
        return runSlicer(configOut, stlFilePath, gcodeFilePath);
      })
      .then(function(slicerOut) {
        // inject info header into gcode
        return writeGcodeHeader(gcodeFilePath, slicerOut, event);
      })
      .then(function() {
        // upload gcode
        return uploadFile(gcodeFilePath, bucket, keyPath + (event.id) + '.gco')
      })
      .then(function(s3res) {
        // finish, send complete message
        console.info("DONE UPLOADING, SENDING FINISH MSG")
        MessageQueue.sendCompleteMessage(event)
          .then(MessageQueue.deleteRequestMessage(message.ReceiptHandle))
          .then(function(r) {
            return r
          })
      })
      .then(function(r) {
        // cleanup
        fs.unlinkSync(stlFilePath);
        fs.unlinkSync(configOut);
        fs.unlinkSync(gcodeFilePath);
        resolve()
      })
      .catch(function(err) {
        // log error
        console.error(err);
        reject(err);
      });
  })
}

runLoop();
<commit_msg>changed infill_line_distance to infill_sparse_density<commit_after>var AWS = require('aws-sdk')
  , ac = require('./config/aws.json')
  , https = require('https')
  , fs = require('fs')
  , temp = '/tmp/'
  , exec = require('child_process').exec
  , Promise = require('bluebird')
  , MessageQueue = require('./util/message_queue.js')
  , FileRepo = require('./util/file_repo.js');

var sqs = new AWS.SQS();
var CuraEngine = /darwin/.test(process.platform) ? 'CuraEngine_darwin' : 'CuraEngine';

function runLoop() {
  MessageQueue.poolMessage(ac.sqs_run)
  .then(sliceStl)
  .then(runLoop)
  .catch(function(err) {
    console.info("ERROR: ", err);
    return runLoop();
  })
}

function runSlicer(configFile, stl, gcodeFilePath) {
  return new Promise(function(resolve, reject) {
    console.info('-- SLICE');
    var cmd = "CURA_ENGINE_SEARCH_PATH=./ ./"+CuraEngine+" slice -v -j "+configFile+" -l "+stl;
    cmd += " -s mesh_position_z=\"0\" -s center_object=\"true\"";
    cmd += " -o "+gcodeFilePath;
    console.info(cmd);
    exec(cmd, function callback(err, stdout, stderr) {
      if (err) {
        console.info("SLICING FAILED, ", err)
        reject(err);
      } else {
        console.info(stderr);
        console.info(stdout);
        // cura writes output to stderr for some reason...
        resolve(stderr);
      }
    });
  });
}

function buildSimpleConfig(inFilePath, outFilePath,  params) {
  return new Promise(function(resolve, reject) {
    var jsonConfig = require(inFilePath);

    // resolution
    switch(params.resolution) {
      case 'low':
        jsonConfig.overrides.layer_height = { "default_value": 0.2 };
        break;

      case 'standard':
        jsonConfig.overrides.layer_height = { "default_value": 0.1 };
        break;

      case 'high':
        jsonConfig.overrides.layer_height = { "default_value": 0.05 };
        break;
    }

    // infill
    switch(params.infill) {
      case 'hollow':
        jsonConfig.overrides.infill_sparse_density = { "default_value": 0 };
        break;

      case 'light':
        jsonConfig.overrides.infill_sparse_density = { "default_value": 5 };
        break;

      case 'standard':
        jsonConfig.overrides.infill_sparse_density = { "default_value": 20 };
        break;

      case 'medium':
        jsonConfig.overrides.infill_sparse_density = { "default_value": 30 };
        break;

      case 'heavy':
        jsonConfig.overrides.infill_sparse_density = { "default_value": 50 };
        break;

      case 'solid':
        jsonConfig.overrides.infill_sparse_density = { "default_value": 100 };
        break;
    }

    // support
    if (params.support)
      jsonConfig.overrides.support_enable = { "default_value": true };

    // brim
    if (params.brim)
      jsonConfig.overrides.adhesion_type = { "default_value": "Brim" };

    // write config to file
    fs.writeFile(outFilePath, JSON.stringify(jsonConfig), 'utf8', function(err, res) {
      if (err)
        reject(err);
      else {
        resolve();
      }
    });
  });
}

function uploadFile(filePath, bucket, key) {
  console.info("-- UPLOADING FILE: ", key);
  return new Promise(function(resolve, reject) {
    fs.readFile(filePath, function(err, data) {
      if (err) {
        reject(err);
      } else {
        var params = {
          Bucket: bucket,
          Key: key,
          Body: data,
          ACL: 'public-read'
        };
        var s3bucket = new AWS.S3({"params": { Bucket: bucket }});
        s3bucket.upload(params, function(err, sres) {
          if (err) {
            reject(err);
          } else {
            resolve(sres);
          }
        });
      }
    });
  });
}

function getLinesCount(filePath) {
  return new Promise(function(resolve, reject) {
    exec("sed -n '$=' "+filePath, function callback(err, stdout, stderr) {
      console.info("-- TOTAL LINES: ", stdout);
      resolve(stdout.trim());
    });
  })
}

function writeGcodeHeader(inFilePath, slicerOut, event) {
  console.info("-- WRITING GCODE HEADER ");
  return new Promise(function(resolve, reject) {
    // first read line count
    getLinesCount(inFilePath)
    .then(function(lineCount) {
      var s = slicerOut.split("Print time: ")[1].split("\n")
        , t = s[1].split(" ")
        , v = s[2].split(" ")[1];

      var head = {
        "time": s[0],
        "readable": t[3]+" "+t[4],
        "volume": v,
        "filament": Math.round(v/(Math.pow((Math.PI*(1.75/2)), 2)))
      };

      function capitalize(s) {
        return s[0].toUpperCase() + s.slice(1);
      }

      head.lines = (lineCount);
      head.resolution = capitalize(event.resolution);
      head.support = event.support;
      head.infill = capitalize(event.infill);
      head.brim = event.brim;

      var hs = ";" + JSON.stringify(head);

      // write to file
      exec('echo "'+(hs.replace(/"/g, '\\"').replace("\n", ""))+'\n$(cat '+inFilePath+')" > '+inFilePath, function callback(err, stdout, stderr) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    })
    .catch(function(err) {
      reject(err);
    })
  });
}

function sliceStl(res) {

  return new Promise(function(resolve, reject) {

    console.info("IN SLICE STL ", res)
    if (!res.Messages)
      return reject('empty message');

    var message = res.Messages[0]
      , event = JSON.parse(message.Body)

    if (!event.id || !event.file_path || !event.user)
      return reject("Required parameters missing");

    var s3 = new AWS.S3()
      , keyPath = 'u/'+(event.user)+'/i/'+(event.id)+'/'
      , stlFilePath = "/tmp/obj_"+(event.id)+".stl"
      , bucket = 'files.printrapp.com'
      , configDefault = './simple.json'
      , configOut = '/tmp/config_'+(event.id)+'.json'
      , gcodeFilePath = '/tmp/out_'+(event.id)+'.gco'

    // download stl
    FileRepo.downloadFromS3(event.file_path, stlFilePath)
      .then(function() {
        // build config file
        return buildSimpleConfig(configDefault, configOut, event);
      })
      .then(function() {
        // run slicer
        return runSlicer(configOut, stlFilePath, gcodeFilePath);
      })
      .then(function(slicerOut) {
        // inject info header into gcode
        return writeGcodeHeader(gcodeFilePath, slicerOut, event);
      })
      .then(function() {
        // upload gcode
        return uploadFile(gcodeFilePath, bucket, keyPath + (event.id) + '.gco')
      })
      .then(function(s3res) {
        // finish, send complete message
        console.info("DONE UPLOADING, SENDING FINISH MSG")
        MessageQueue.sendCompleteMessage(event)
          .then(MessageQueue.deleteRequestMessage(message.ReceiptHandle))
          .then(function(r) {
            return r
          })
      })
      .then(function(r) {
        // cleanup
        fs.unlinkSync(stlFilePath);
        fs.unlinkSync(configOut);
        fs.unlinkSync(gcodeFilePath);
        resolve()
      })
      .catch(function(err) {
        // log error
        console.error(err);
        reject(err);
      });
  })
}

runLoop();
<|endoftext|>


<commit_before>import WebGPUUniformsGroup from './WebGPUUniformsGroup.js';
import { FloatUniform, Matrix4Uniform } from './WebGPUUniform.js';
import WebGPUSampler from './WebGPUSampler.js';
import WebGPUSampledTexture from './WebGPUSampledTexture.js';

class WebGPUBindings {

	constructor( device, info, properties, textures, pipelines ) {

		this.device = device;
		this.info = info;
		this.properties = properties;
		this.textures = textures;
		this.pipelines = pipelines;

		this.uniformsData = new WeakMap();

		this.sharedUniformsGroups = new Map();

		this.updateMap = new WeakMap();

		this._setupSharedUniformsGroups();

	}

	get( object ) {

		let data = this.uniformsData.get( object );

		if ( data === undefined ) {

			const pipeline = this.pipelines.get( object );
			const material = object.material;
			let bindings;

			// each material defines an array of bindings (ubos, textures, samplers etc.)

			if ( material.isMeshBasicMaterial ) {

				bindings = this._getMeshBasicBindings();

			} else if ( material.isPointsMaterial ) {

				bindings = this._getPointsBasicBindings();

			} else if ( material.isLineBasicMaterial ) {

				bindings = this._getLinesBasicBindings();

			} else {

				console.error( 'THREE.WebGPURenderer: Unknwon shader type.' );

			}

			// setup (static) binding layout and (dynamic) binding group

			const bindLayout = pipeline.getBindGroupLayout( 0 );
			const bindGroup = this._createBindGroup( bindings, bindLayout );

			data = {
				layout: bindLayout,
				group: bindGroup,
				bindings: bindings
			};

			this.uniformsData.set( object, data );

		}

		return data;

	}

	update( object, camera ) {

		const textures = this.textures;

		const data = this.get( object );
		const bindings = data.bindings;

		const updateMap = this.updateMap;
		const frame = this.info.render.frame;
		const sharedUniformsGroups = this.sharedUniformsGroups;

		let needsBindGroupRefresh = false;

		// iterate over all bindings and check if buffer updates or a new binding group is required

		for ( const binding of bindings ) {

			if ( binding.isUniformsGroup ) {

				const isShared = sharedUniformsGroups.has( binding.name );
				const isUpdated = updateMap.get( binding ) === frame;

				if ( isShared && isUpdated ) continue;

				const array = binding.array;
				const bufferGPU = binding.bufferGPU;

				binding.onBeforeUpdate( object, camera );

				const needsBufferWrite = binding.update();

				if ( needsBufferWrite === true ) {

					this.device.defaultQueue.writeBuffer(
						bufferGPU,
						0,
						array,
						0
					);

				}

				updateMap.set( binding, frame );

			} else if ( binding.isSampler ) {

				const material = object.material;
				const texture = material[ binding.name ];

				textures.updateSampler( texture );

				const samplerGPU = textures.getSampler( texture );

				if ( binding.samplerGPU !== samplerGPU ) {

					binding.samplerGPU = samplerGPU;
					needsBindGroupRefresh = true;

				}

			} else if ( binding.isSampledTexture ) {

				const material = object.material;
				const texture = material[ binding.name ];

				const forceUpdate = textures.updateTexture( texture );
				const textureGPU = textures.getTextureGPU( texture );

				if ( binding.textureGPU !== textureGPU || forceUpdate === true ) {

					binding.textureGPU = textureGPU;
					needsBindGroupRefresh = true;

				}

			}

		}

		if ( needsBindGroupRefresh === true ) {

			data.group = this._createBindGroup( bindings, data.layout );

		}

	}

	dispose() {

		this.uniformsData = new WeakMap();
		this.updateMap = new WeakMap();

	}

	_createBindGroup( bindings, layout ) {

		let bindingPoint = 0;
		const entries = [];

		for ( const binding of bindings ) {

			if ( binding.isUniformsGroup ) {

				if ( binding.bufferGPU === null ) {

					const byteLength = binding.getByteLength();

					binding.array = new Float32Array( new ArrayBuffer( byteLength ) );

					binding.bufferGPU = this.device.createBuffer( {
						size: byteLength,
						usage: binding.usage,
					} );

				}

				entries.push( { binding: bindingPoint, resource: { buffer: binding.bufferGPU } } );

			} else if ( binding.isSampler ) {

				if ( binding.samplerGPU === null ) {

					binding.samplerGPU = this.textures.getDefaultSampler();

				}

				entries.push( { binding: bindingPoint, resource: binding.samplerGPU } );

			} else if ( binding.isSampledTexture ) {

				if ( binding.textureGPU === null ) {

					binding.textureGPU = this.textures.getDefaultTexture();

				}

				entries.push( { binding: bindingPoint, resource: binding.textureGPU.createView() } );

			}

			bindingPoint ++;

		}

		return this.device.createBindGroup( {
			layout: layout,
			entries: entries
		} );

	}

	_getMeshBasicBindings() {

		const bindings = [];

		// UBOs

		// model

		const modelViewUniform = new Matrix4Uniform( 'modelMatrix' );
		const modelViewMatrixUniform = new Matrix4Uniform( 'modelViewMatrix' );

		const modelGroup = new WebGPUUniformsGroup();
		modelGroup.setName( 'modelUniforms' );
		modelGroup.addUniform( modelViewUniform );
		modelGroup.addUniform( modelViewMatrixUniform );
		modelGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			modelViewUniform.setValue( object.matrixWorld );
			modelViewMatrixUniform.setValue( object.modelViewMatrix );

		} );

		// camera

		const cameraGroup = this.sharedUniformsGroups.get( 'cameraUniforms' );

		// material (opacity for testing)

		const opacityUniform = new FloatUniform( 'opacity', 1 );

		const opacityGroup = new WebGPUUniformsGroup();
		opacityGroup.setName( 'opacityUniforms' );
		opacityGroup.addUniform( opacityUniform );
		opacityGroup.visibility = GPUShaderStage.FRAGMENT;
		opacityGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			const material = object.material;
			const opacity = ( material.transparent === true ) ? material.opacity : 1.0;

			opacityUniform.setValue( opacity );

		} );

		// sampler

		const diffuseSampler = new WebGPUSampler();
		diffuseSampler.setName( 'map' );

		// texture

		const diffuseTexture = new WebGPUSampledTexture();
		diffuseTexture.setName( 'map' );

		// the order of WebGPUBinding objects must match the binding order in the shader

		bindings.push( modelGroup );
		bindings.push( cameraGroup );
		bindings.push( opacityGroup );
		bindings.push( diffuseSampler );
		bindings.push( diffuseTexture );

		return bindings;

	}

	_getPointsBasicBindings() {

		const bindings = [];

		// UBOs

		const modelViewUniform = new Matrix4Uniform( 'modelMatrix' );
		const modelViewMatrixUniform = new Matrix4Uniform( 'modelViewMatrix' );

		const modelGroup = new WebGPUUniformsGroup();
		modelGroup.setName( 'modelUniforms' );
		modelGroup.addUniform( modelViewUniform );
		modelGroup.addUniform( modelViewMatrixUniform );
		modelGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			modelViewUniform.setValue( object.matrixWorld );
			modelViewMatrixUniform.setValue( object.modelViewMatrix );

		} );

		const cameraGroup = this.sharedUniformsGroups.get( 'cameraUniforms' );

		//

		bindings.push( modelGroup );
		bindings.push( cameraGroup );

		return bindings;

	}

	_getLinesBasicBindings() {

		const bindings = [];

		// UBOs

		const modelViewUniform = new Matrix4Uniform( 'modelMatrix' );
		const modelViewMatrixUniform = new Matrix4Uniform( 'modelViewMatrix' );

		const modelGroup = new WebGPUUniformsGroup();
		modelGroup.setName( 'modelUniforms' );
		modelGroup.addUniform( modelViewUniform );
		modelGroup.addUniform( modelViewMatrixUniform );
		modelGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			modelViewUniform.setValue( object.matrixWorld );
			modelViewMatrixUniform.setValue( object.modelViewMatrix );

		} );

		const cameraGroup = this.sharedUniformsGroups.get( 'cameraUniforms' );

		//

		bindings.push( modelGroup );
		bindings.push( cameraGroup );

		return bindings;

	}

	_setupSharedUniformsGroups() {

		const projectionMatrixUniform = new Matrix4Uniform( 'projectionMatrix' );
		const viewMatrixUniform = new Matrix4Uniform( 'viewMatrix' );

		const cameraGroup = new WebGPUUniformsGroup();
		cameraGroup.setName( 'cameraUniforms' );
		cameraGroup.addUniform( projectionMatrixUniform );
		cameraGroup.addUniform( viewMatrixUniform );
		cameraGroup.setOnBeforeUpdate( function ( object, camera ) {

			projectionMatrixUniform.setValue( camera.projectionMatrix );
			viewMatrixUniform.setValue( camera.matrixWorldInverse );

		} );

		this.sharedUniformsGroups.set( cameraGroup.name, cameraGroup );

	}

}

export default WebGPUBindings;
<commit_msg>WebGPUBindings: Make texture update more robust.<commit_after>import WebGPUUniformsGroup from './WebGPUUniformsGroup.js';
import { FloatUniform, Matrix4Uniform } from './WebGPUUniform.js';
import WebGPUSampler from './WebGPUSampler.js';
import WebGPUSampledTexture from './WebGPUSampledTexture.js';

class WebGPUBindings {

	constructor( device, info, properties, textures, pipelines ) {

		this.device = device;
		this.info = info;
		this.properties = properties;
		this.textures = textures;
		this.pipelines = pipelines;

		this.uniformsData = new WeakMap();

		this.sharedUniformsGroups = new Map();

		this.updateMap = new WeakMap();

		this._setupSharedUniformsGroups();

	}

	get( object ) {

		let data = this.uniformsData.get( object );

		if ( data === undefined ) {

			const pipeline = this.pipelines.get( object );
			const material = object.material;
			let bindings;

			// each material defines an array of bindings (ubos, textures, samplers etc.)

			if ( material.isMeshBasicMaterial ) {

				bindings = this._getMeshBasicBindings();

			} else if ( material.isPointsMaterial ) {

				bindings = this._getPointsBasicBindings();

			} else if ( material.isLineBasicMaterial ) {

				bindings = this._getLinesBasicBindings();

			} else {

				console.error( 'THREE.WebGPURenderer: Unknwon shader type.' );

			}

			// setup (static) binding layout and (dynamic) binding group

			const bindLayout = pipeline.getBindGroupLayout( 0 );
			const bindGroup = this._createBindGroup( bindings, bindLayout );

			data = {
				layout: bindLayout,
				group: bindGroup,
				bindings: bindings
			};

			this.uniformsData.set( object, data );

		}

		return data;

	}

	update( object, camera ) {

		const textures = this.textures;

		const data = this.get( object );
		const bindings = data.bindings;

		const updateMap = this.updateMap;
		const frame = this.info.render.frame;
		const sharedUniformsGroups = this.sharedUniformsGroups;

		let needsBindGroupRefresh = false;

		// iterate over all bindings and check if buffer updates or a new binding group is required

		for ( const binding of bindings ) {

			if ( binding.isUniformsGroup ) {

				const isShared = sharedUniformsGroups.has( binding.name );
				const isUpdated = updateMap.get( binding ) === frame;

				if ( isShared && isUpdated ) continue;

				const array = binding.array;
				const bufferGPU = binding.bufferGPU;

				binding.onBeforeUpdate( object, camera );

				const needsBufferWrite = binding.update();

				if ( needsBufferWrite === true ) {

					this.device.defaultQueue.writeBuffer(
						bufferGPU,
						0,
						array,
						0
					);

				}

				updateMap.set( binding, frame );

			} else if ( binding.isSampler ) {

				const material = object.material;
				const texture = material[ binding.name ];

				if ( texture !== null ) {

					textures.updateSampler( texture );

					const samplerGPU = textures.getSampler( texture );

					if ( binding.samplerGPU !== samplerGPU ) {

						binding.samplerGPU = samplerGPU;
						needsBindGroupRefresh = true;

					}

				}

			} else if ( binding.isSampledTexture ) {

				const material = object.material;
				const texture = material[ binding.name ];

				if ( texture !== null ) {

					const forceUpdate = textures.updateTexture( texture );
					const textureGPU = textures.getTextureGPU( texture );

					if ( binding.textureGPU !== textureGPU || forceUpdate === true ) {

						binding.textureGPU = textureGPU;
						needsBindGroupRefresh = true;

					}

				}

			}

		}

		if ( needsBindGroupRefresh === true ) {

			data.group = this._createBindGroup( bindings, data.layout );

		}

	}

	dispose() {

		this.uniformsData = new WeakMap();
		this.updateMap = new WeakMap();

	}

	_createBindGroup( bindings, layout ) {

		let bindingPoint = 0;
		const entries = [];

		for ( const binding of bindings ) {

			if ( binding.isUniformsGroup ) {

				if ( binding.bufferGPU === null ) {

					const byteLength = binding.getByteLength();

					binding.array = new Float32Array( new ArrayBuffer( byteLength ) );

					binding.bufferGPU = this.device.createBuffer( {
						size: byteLength,
						usage: binding.usage,
					} );

				}

				entries.push( { binding: bindingPoint, resource: { buffer: binding.bufferGPU } } );

			} else if ( binding.isSampler ) {

				if ( binding.samplerGPU === null ) {

					binding.samplerGPU = this.textures.getDefaultSampler();

				}

				entries.push( { binding: bindingPoint, resource: binding.samplerGPU } );

			} else if ( binding.isSampledTexture ) {

				if ( binding.textureGPU === null ) {

					binding.textureGPU = this.textures.getDefaultTexture();

				}

				entries.push( { binding: bindingPoint, resource: binding.textureGPU.createView() } );

			}

			bindingPoint ++;

		}

		return this.device.createBindGroup( {
			layout: layout,
			entries: entries
		} );

	}

	_getMeshBasicBindings() {

		const bindings = [];

		// UBOs

		// model

		const modelViewUniform = new Matrix4Uniform( 'modelMatrix' );
		const modelViewMatrixUniform = new Matrix4Uniform( 'modelViewMatrix' );

		const modelGroup = new WebGPUUniformsGroup();
		modelGroup.setName( 'modelUniforms' );
		modelGroup.addUniform( modelViewUniform );
		modelGroup.addUniform( modelViewMatrixUniform );
		modelGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			modelViewUniform.setValue( object.matrixWorld );
			modelViewMatrixUniform.setValue( object.modelViewMatrix );

		} );

		// camera

		const cameraGroup = this.sharedUniformsGroups.get( 'cameraUniforms' );

		// material (opacity for testing)

		const opacityUniform = new FloatUniform( 'opacity', 1 );

		const opacityGroup = new WebGPUUniformsGroup();
		opacityGroup.setName( 'opacityUniforms' );
		opacityGroup.addUniform( opacityUniform );
		opacityGroup.visibility = GPUShaderStage.FRAGMENT;
		opacityGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			const material = object.material;
			const opacity = ( material.transparent === true ) ? material.opacity : 1.0;

			opacityUniform.setValue( opacity );

		} );

		// sampler

		const diffuseSampler = new WebGPUSampler();
		diffuseSampler.setName( 'map' );

		// texture

		const diffuseTexture = new WebGPUSampledTexture();
		diffuseTexture.setName( 'map' );

		// the order of WebGPUBinding objects must match the binding order in the shader

		bindings.push( modelGroup );
		bindings.push( cameraGroup );
		bindings.push( opacityGroup );
		bindings.push( diffuseSampler );
		bindings.push( diffuseTexture );

		return bindings;

	}

	_getPointsBasicBindings() {

		const bindings = [];

		// UBOs

		const modelViewUniform = new Matrix4Uniform( 'modelMatrix' );
		const modelViewMatrixUniform = new Matrix4Uniform( 'modelViewMatrix' );

		const modelGroup = new WebGPUUniformsGroup();
		modelGroup.setName( 'modelUniforms' );
		modelGroup.addUniform( modelViewUniform );
		modelGroup.addUniform( modelViewMatrixUniform );
		modelGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			modelViewUniform.setValue( object.matrixWorld );
			modelViewMatrixUniform.setValue( object.modelViewMatrix );

		} );

		const cameraGroup = this.sharedUniformsGroups.get( 'cameraUniforms' );

		//

		bindings.push( modelGroup );
		bindings.push( cameraGroup );

		return bindings;

	}

	_getLinesBasicBindings() {

		const bindings = [];

		// UBOs

		const modelViewUniform = new Matrix4Uniform( 'modelMatrix' );
		const modelViewMatrixUniform = new Matrix4Uniform( 'modelViewMatrix' );

		const modelGroup = new WebGPUUniformsGroup();
		modelGroup.setName( 'modelUniforms' );
		modelGroup.addUniform( modelViewUniform );
		modelGroup.addUniform( modelViewMatrixUniform );
		modelGroup.setOnBeforeUpdate( function ( object/*, camera */ ) {

			modelViewUniform.setValue( object.matrixWorld );
			modelViewMatrixUniform.setValue( object.modelViewMatrix );

		} );

		const cameraGroup = this.sharedUniformsGroups.get( 'cameraUniforms' );

		//

		bindings.push( modelGroup );
		bindings.push( cameraGroup );

		return bindings;

	}

	_setupSharedUniformsGroups() {

		const projectionMatrixUniform = new Matrix4Uniform( 'projectionMatrix' );
		const viewMatrixUniform = new Matrix4Uniform( 'viewMatrix' );

		const cameraGroup = new WebGPUUniformsGroup();
		cameraGroup.setName( 'cameraUniforms' );
		cameraGroup.addUniform( projectionMatrixUniform );
		cameraGroup.addUniform( viewMatrixUniform );
		cameraGroup.setOnBeforeUpdate( function ( object, camera ) {

			projectionMatrixUniform.setValue( camera.projectionMatrix );
			viewMatrixUniform.setValue( camera.matrixWorldInverse );

		} );

		this.sharedUniformsGroups.set( cameraGroup.name, cameraGroup );

	}

}

export default WebGPUBindings;
<|endoftext|>


<commit_before>function modify_dom_init(){
    var span2 = $("body>div.container-fluid>div.row-fluid>div.span2");
    span2.addClass("fixed visible-desktop");
    span2.removeClass("span2");

    span2.children("ul").removeClass("well");

    var span10 = $("body>div.container-fluid>div.row-fluid>div.span10");
    span10.addClass("filler");
    span10.removeClass("span10");

    var cnt2 = $("body>div.container-fluid").contents();
    $("body>div.container-fluid").replaceWith(cnt2);

    var cnt = $("body>div.row-fluid").contents();
    $("body>div.row-fluid").replaceWith(cnt);

    $('body').show();
}<commit_msg>bugfix firefox show body<commit_after>function modify_dom_init(){
    var span2 = $("body>div.container-fluid>div.row-fluid>div.span2");
    span2.addClass("fixed visible-desktop");
    span2.removeClass("span2");

    span2.children("ul").removeClass("well");

    var span10 = $("body>div.container-fluid>div.row-fluid>div.span10");
    span10.addClass("filler");
    span10.removeClass("span10");

    var cnt2 = $("body>div.container-fluid").contents();
    $("body>div.container-fluid").replaceWith(cnt2);

    var cnt = $("body>div.row-fluid").contents();
    $("body>div.row-fluid").replaceWith(cnt);

    $('body').show();
    $('body').css('display','block'); /* Hack Firefox previous line dosen't work with firefox */
}<|endoftext|>


<commit_before>'use strict';

import {expect} from 'chai';
import YAWN from '../src/index.js';

describe('preserves comments and styling when', ()=> {

  describe('JSON is an array and', ()=> {
    // debugger
    it('transformed to an object', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      yawn.json = {val1: 1, val2: 2};

      expect(yawn.yaml).to.equal(`
        # leading comment
        val1: 1
        val2: 2
        # trailing comment`);
    });

    it('one item in array is changed', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json[0] = 'value0';
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
        - value2
        - value0
        # trailing comment`);
    });

    it('two items in array are changed', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json[0] = 'value0';
      json[1] = 'value1';
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
        - value0 # inline comment
        - value1
        # trailing comment`);
    });

    it('one item is deleted', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json.shift();
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
         # inline comment
        - value2
        # trailing comment`);
    });

    it('one item is added', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json.push('value3');
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
        - value1 # inline comment
        - value2
        - value3
        # trailing comment`);
    });
  });
});
<commit_msg>Fix some array bugs<commit_after>'use strict';

import {expect} from 'chai';
import YAWN from '../src/index.js';

describe('preserves comments and styling when', ()=> {

  describe('JSON is an array and', ()=> {
    // debugger
    it('transformed to an object', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      yawn.json = {val1: 1, val2: 2};

      expect(yawn.yaml).to.equal(`
        # leading comment
        val1: 1
        val2: 2
        # trailing comment`);
    });

    it('one item in array is changed', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json[0] = 'value0';
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
         # inline comment
        - value2
        - value0
        # trailing comment`);
    });

    it('two items in array are changed', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json[0] = 'value0';
      json[1] = 'value3';
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
         # inline comment
        - value3
        - value0
        # trailing comment`);
    });

    it('one item is deleted', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json.shift();
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
         # inline comment
        - value2
        # trailing comment`);
    });

    it('one item is added', ()=> {
      let str = `
        # leading comment
        - value1 # inline comment
        - value2
        # trailing comment`;

      let yawn = new YAWN(str);
      let json = yawn.json;
      json.push('value3');
      yawn.json = json;

      expect(yawn.yaml).to.equal(`
        # leading comment
        - value1 # inline comment
        - value2
        - value3
        # trailing comment`);
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');

function validateRemainingLength(value) {
    var maxMessageLength = 268435455;
    if (value > maxMessageLength) {
        return Error('max message length exceeded');
    }
    return undefined;
}

function existy(value) {
    return value !== null && value !== undefined;
}

function dispatch() {
    var funcs = arguments;

    return function(target) {
        for (var funcIndex in funcs) {
            var func = funcs[funcIndex];
            var ret = func.apply(null, [target]);
            if (existy(ret)) {
                return ret;
            }
        }
        return undefined;
    }
}

function encodeRemainingLength(value) {

    var dispatcher = dispatch(validateRemainingLength, encode);

    return dispatcher(value);

    function encode(value) {
        var buffer = new Buffer(0);
        do {
            var digit = value % 128;
            value = parseInt(value / 128);
            if (value > 0) {
                digit = digit | 0xFF;
            }
            var next = new Buffer(1);
            next.writeUInt8(digit, 0);
            buffer = Buffer.concat([buffer, next])
        }
        while (value > 0);
        return buffer;
    }
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            return Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

function remainingLengthByteCount(value) {
    var dispatcher = dispatch(validateRemainingLength, count);
    return dispatcher(value);

    function count(value) {
        return Math.ceil(Math.log(value) / Math.log(128));
    }
}

describe('MQTT Special Functions', function() {

    var oneByteUpperLimit = 128 - 1;
    var twoByteUpperLimit = 128 * 128 - 1;
    var threeByteUpperLimit = 128 * 128 * 128 - 1;
    var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding up to one byte upper limit returns a 1 byte Buffer', function() {
            expectEncoding(oneByteUpperLimit, [0x7F]);
        });

        it('encoding up to two byte upper limit returns a 2 byte Buffer', function() {
            expectEncoding(twoByteUpperLimit, [0xFF, 0x7F]);
        });

        it('encoding up to three byte upper limit returns a 3 byte Buffer', function() {
            expectEncoding(threeByteUpperLimit, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding up to four byte upper limit returns a 4 byte Buffer', function() {
            expectEncoding(fourByteUpperLimit, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than four byte upper limit throws an error', function() {
            var error = encodeRemainingLength(fourByteUpperLimit+1);
            assert.equal(error.message, 'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            var error = decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            assert.equal(error.message, 'malformed remaining length');
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<commit_msg>Bug in the encoding I was using 0xFF instead of 128<commit_after>var assert = require('assert');
var services = require('../lib/services');

describe('MQTT Special Functions', function() {

    var oneByteUpperLimit = 128 - 1;
    var twoByteUpperLimit = 128 * 128 - 1;
    var threeByteUpperLimit = 128 * 128 * 128 - 1;
    var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = services.encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding up to one byte upper limit returns a 1 byte Buffer', function() {
            expectEncoding(oneByteUpperLimit, [0x7F]);
        });

        it('encoding up to two byte upper limit returns a 2 byte Buffer', function() {
            expectEncoding(twoByteUpperLimit, [0xFF, 0x7F]);
        });

        it('encoding up to three byte upper limit returns a 3 byte Buffer', function() {
            expectEncoding(threeByteUpperLimit, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding up to four byte upper limit returns a 4 byte Buffer', function() {
            expectEncoding(fourByteUpperLimit, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than four byte upper limit throws an error', function() {
            var error = services.encodeRemainingLength(fourByteUpperLimit + 1);
            assert.equal(error.message, 'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = services.decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            var error = services.decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            assert.equal(error.message, 'malformed remaining length');
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, services.remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, services.remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, services.remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, services.remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(services.remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<|endoftext|>


<commit_before>/*
 * Copyright 2008-2012 Microarray Informatics Team, EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * For further details of the Gene Expression Atlas project, including source code,
 * downloads and documentation, please see:
 *
 * http://gxa.github.com/gxa
 */

/*global $, jQuery, console:false */
var helpTooltipsModule = (function($) {
    "use strict";

    function buildHelpAnchor() {
        return $("<a/>", {
                    'class': 'help-icon',
                    'href': '#',
                    'title': '',
                    'text': '?'
                });
    }

    function getHelpFileName(pageName){
        return 'help-tooltips.' + pageName + '-page.html';
    }

    function getHelpLocation(pageName, inlineAnchor) {
        return 'resources/html/' + getHelpFileName(pageName) + ' ' + inlineAnchor;
    }

    function initTooltips(pageName){

        var anchor = buildHelpAnchor();

        $("[data-help-loc]")
            .append(anchor)
            .click(function(e) {
                e.preventDefault();
            })
            .tooltip(
            {
                tooltipClass: "help-tooltip",
                content: function(callback) {
                    var tooltipHelpHtmlId = $(this).parent().attr('data-help-loc');
                    $("#help-placeholder").load(getHelpLocation(pageName, tooltipHelpHtmlId),
                        function (response, status, xhr) {
                            var tooltipContent;
                            if (status === "error") {
                                tooltipContent = "Sorry but there was an error: " + xhr.status + " " + xhr.statusText;
                            }
                            tooltipContent = $(this).text();
                            if (!tooltipContent){
                                tooltipContent = "Missing help section for id = " + tooltipHelpHtmlId + " in html file " + getHelpFileName(pageName);
                            }
                            callback(tooltipContent);

                        }
                    );

                }
            });

    }

    return {
        init:  function(pageName) {
                    initTooltips(pageName);
                },
        buildHelpAnchor: buildHelpAnchor,
        getHelpFileName: getHelpFileName
    };

}(jQuery));
<commit_msg>corrected error handling<commit_after>/*
 * Copyright 2008-2012 Microarray Informatics Team, EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * For further details of the Gene Expression Atlas project, including source code,
 * downloads and documentation, please see:
 *
 * http://gxa.github.com/gxa
 */

/*global $, jQuery, console:false */
var helpTooltipsModule = (function($) {
    "use strict";

    function buildHelpAnchor() {
        return $("<a/>", {
                    'class': 'help-icon',
                    'href': '#',
                    'title': '',
                    'text': '?'
                });
    }

    function getHelpFileName(pageName){
        return 'help-tooltips.' + pageName + '-page.html';
    }

    function getHelpLocation(pageName, inlineAnchor) {
        return 'resources/html/' + getHelpFileName(pageName) + ' ' + inlineAnchor;
    }

    function initTooltips(pageName){

        var anchor = buildHelpAnchor();

        $("[data-help-loc]")
            .append(anchor)
            .click(function(e) {
                e.preventDefault();
            })
            .tooltip(
            {
                tooltipClass: "help-tooltip",
                content: function(callback) {
                    var tooltipHelpHtmlId = $(this).parent().attr('data-help-loc');
                    $("#help-placeholder").load(getHelpLocation(pageName, tooltipHelpHtmlId),
                        function (response, status, xhr) {
                            var tooltipContent;
                            if (status === "error") {
                                tooltipContent = "Sorry but there was an error: " + xhr.status + " " + xhr.statusText;
                                callback(tooltipContent);
                                return;
                            }
                            tooltipContent = $(this).text();
                            if (!tooltipContent){
                                tooltipContent = "Missing help section for id = " + tooltipHelpHtmlId + " in html file " + getHelpFileName(pageName);
                            }
                            callback(tooltipContent);

                        }
                    );

                }
            });

    }

    return {
        init:  function(pageName) {
                    initTooltips(pageName);
                },
        buildHelpAnchor: buildHelpAnchor,
        getHelpFileName: getHelpFileName
    };

}(jQuery));
<|endoftext|>