<commit_before>import React from 'react';
import {shallow, mount} from 'enzyme';

import {createPullRequestResult} from '../fixtures/factories/pull-request-result';
import Branch, {nullBranch} from '../../lib/models/branch';
import BranchSet from '../../lib/models/branch-set';
import Issueish from '../../lib/models/issueish';
import IssueishListView from '../../lib/views/issueish-list-view';

const allGreen = new Issueish(createPullRequestResult({number: 1, states: ['SUCCESS', 'SUCCESS', 'SUCCESS']}));
const mixed = new Issueish(createPullRequestResult({number: 2, states: ['SUCCESS', 'PENDING', 'FAILURE']}));
const allRed = new Issueish(createPullRequestResult({number: 3, states: ['FAILURE', 'ERROR', 'FAILURE']}));
const noStatus = new Issueish(createPullRequestResult({number: 4, states: null}));

class CustomComponent extends React.Component {
  render() {
    return
;
  }
}

describe('IssueishListView', function() {
  let branch, branchSet;

  beforeEach(function() {
    branch = new Branch('master', nullBranch, nullBranch, true);
    branchSet = new BranchSet();
    branchSet.add(branch);
  });

  function buildApp(overrideProps = {}) {
    return (
      <IssueishListView
        title="aaa"
        isLoading={true}
        total={0}
        issueishes={[]}

        onCreatePr={() => {}}
        onIssueishClick={() => {}}
        onMoreClick={() => {}}

        {...overrideProps}
      />
    );
  }

  it('sets the accordion title to the search name', function() {
    const wrapper = shallow(buildApp({
      title: 'the search name',
    }));
    assert.strictEqual(wrapper.find('Accordion').prop('leftTitle'), 'the search name');
  });

  describe('while loading', function() {
    it('sets its accordion as isLoading', function() {
      const wrapper = shallow(buildApp());
      assert.isTrue(wrapper.find('Accordion').prop('isLoading'));
    });

    it('passes an empty result list', function() {
      const wrapper = shallow(buildApp());
      assert.lengthOf(wrapper.find('Accordion').prop('results'), 0);
    });
  });

  describe('with empty results', function() {
    it('uses a custom EmptyComponent if one is provided', function() {
      const wrapper = mount(buildApp({isLoading: false, emptyComponent: CustomComponent}));

      assert.isTrue(wrapper.find('CustomComponent').exists());
    });

    it('renders an error tile if an error is present', function() {
      const error = new Error('error');
      error.rawStack = error.stack;
      const wrapper = mount(buildApp({isLoading: false, error}));

      assert.isTrue(wrapper.find('QueryErrorTile').exists());
    });
  });

  describe('with nonempty results', function() {
    it('passes its results to the accordion', function() {
      const issueishes = [allGreen, mixed, allRed];
      const wrapper = shallow(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
      }));
      assert.deepEqual(wrapper.find('Accordion').prop('results'), issueishes);
    });

    it('renders a check if all status checks are successful', function() {
      const wrapper = mount(buildApp({isLoading: false, total: 1, issueishes: [allGreen]}));
      assert.isTrue(wrapper.find('span.github-IssueishList-item--status').hasClass('icon-check'));
    });

    it('renders an x if all status checks have failed', function() {
      const wrapper = mount(buildApp({isLoading: false, total: 1, issueishes: [allRed]}));
      assert.isTrue(wrapper.find('span.github-IssueishList-item--status').hasClass('icon-x'));
    });

    it('renders a donut chart if status checks are mixed', function() {
      const wrapper = mount(buildApp({isLoading: false, total: 1, issueishes: [mixed]}));

      const chart = wrapper.find('StatusDonutChart');
      assert.strictEqual(chart.prop('pending'), 1);
      assert.strictEqual(chart.prop('failure'), 1);
      assert.strictEqual(chart.prop('success'), 1);
    });

    it('renders nothing with no status checks are present', function() {
      const wrapper = mount(buildApp({isLoading: false, total: 1, issueishes: [noStatus]}));
      assert.isTrue(wrapper.find('span.github-IssueishList-item--status').hasClass('icon-dash'));
    });

    it('calls its onIssueishClick handler when an item is clicked', function() {
      const issueishes = [allGreen, mixed, allRed];
      const onIssueishClick = sinon.stub();
      const wrapper = mount(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
        onIssueishClick,
      }));

      wrapper.find('.github-Accordion-listItem').at(1).simulate('click');
      assert.isTrue(onIssueishClick.calledWith(mixed));
    });

    it('calls its onMoreClick handler when a "more" component is clicked', function() {
      const issueishes = [allGreen, mixed, allRed];
      const onMoreClick = sinon.stub();
      const wrapper = mount(buildApp({
        isLoading: false,
        total: 4,
        issueishes,
        onMoreClick,
      }));

      wrapper.find('.github-IssueishList-more a').simulate('click');
      assert.isTrue(onMoreClick.called);
    });
  });

  it('renders review button only if needed', function() {
    const openReviews = sinon.spy();
    const wrapper = mount(buildApp({total: 1, openReviews}));
    assert.isFalse(wrapper.find('.github-IssueishList-openReviewsButton').exists());

    wrapper.setProps({needReviewsButton: true});
    assert.isTrue(wrapper.find('.github-IssueishList-openReviewsButton').exists());
    wrapper.find('.github-IssueishList-openReviewsButton').simulate('click');
    assert.isTrue(openReviews.called);
  });
});
<commit_msg>Use shallow renderer and GraphQL builders in IssueishListView tests<commit_after>import React from 'react';
import {shallow} from 'enzyme';

import Branch, {nullBranch} from '../../lib/models/branch';
import BranchSet from '../../lib/models/branch-set';
import Issueish from '../../lib/models/issueish';
import IssueishListView from '../../lib/views/issueish-list-view';
import CheckSuitesAccumulator from '../../lib/containers/accumulators/check-suites-accumulator';
import {pullRequestBuilder} from '../builder/graphql/pr';

import issueishQuery from '../../lib/controllers/__generated__/issueishListController_results.graphql';

function createPullRequestResult({number, states}) {
  return pullRequestBuilder(issueishQuery)
    .number(number)
    .commits(conn => {
      conn.addNode(n => n.commit(c => {
        if (states) {
          c.status(st => {
            for (const state of states) {
              st.addContext(con => con.state(state));
            }
          });
        } else {
          c.nullStatus();
        }
      }));
    })
    .build();
}

const allGreen = new Issueish(createPullRequestResult({number: 1, states: ['SUCCESS', 'SUCCESS', 'SUCCESS']}));
const mixed = new Issueish(createPullRequestResult({number: 2, states: ['SUCCESS', 'PENDING', 'FAILURE']}));
const allRed = new Issueish(createPullRequestResult({number: 3, states: ['FAILURE', 'ERROR', 'FAILURE']}));
const noStatus = new Issueish(createPullRequestResult({number: 4, states: null}));

class CustomComponent extends React.Component {
  render() {
    return
;
  }
}

describe('IssueishListView', function() {
  let branch, branchSet;

  beforeEach(function() {
    branch = new Branch('master', nullBranch, nullBranch, true);
    branchSet = new BranchSet();
    branchSet.add(branch);
  });

  function buildApp(overrideProps = {}) {
    return (
      <IssueishListView
        title="aaa"
        isLoading={true}
        total={0}
        issueishes={[]}

        onCreatePr={() => {}}
        onIssueishClick={() => {}}
        onMoreClick={() => {}}

        {...overrideProps}
      />
    );
  }

  it('sets the accordion title to the search name', function() {
    const wrapper = shallow(buildApp({
      title: 'the search name',
    }));
    assert.strictEqual(wrapper.find('Accordion').prop('leftTitle'), 'the search name');
  });

  describe('while loading', function() {
    it('sets its accordion as isLoading', function() {
      const wrapper = shallow(buildApp());
      assert.isTrue(wrapper.find('Accordion').prop('isLoading'));
    });

    it('passes an empty result list', function() {
      const wrapper = shallow(buildApp());
      assert.lengthOf(wrapper.find('Accordion').prop('results'), 0);
    });
  });

  describe('with empty results', function() {
    it('uses a custom EmptyComponent if one is provided', function() {
      const wrapper = shallow(buildApp({isLoading: false, emptyComponent: CustomComponent}));

      const empty = wrapper.find('Accordion').renderProp('emptyComponent')();
      assert.isTrue(empty.is(CustomComponent));
    });

    it('renders an error tile if an error is present', function() {
      const error = new Error('error');
      error.rawStack = error.stack;
      const wrapper = shallow(buildApp({isLoading: false, error}));

      const empty = wrapper.find('Accordion').renderProp('emptyComponent')();
      assert.isTrue(empty.is('QueryErrorTile'));
    });
  });

  describe('with nonempty results', function() {
    it('passes its results to the accordion', function() {
      const issueishes = [allGreen, mixed, allRed];
      const wrapper = shallow(buildApp({
        isLoading: false,
        total: 3,
        issueishes,
      }));
      assert.deepEqual(wrapper.find('Accordion').prop('results'), issueishes);
    });

    it('renders a check if all status checks are successful', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(allGreen);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});
      assert.strictEqual(accumulated.find('Octicon').prop('icon'), 'check');
    });

    it('renders an x if all status checks have failed', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(allRed);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});
      assert.strictEqual(accumulated.find('Octicon').prop('icon'), 'x');
    });

    it('renders a donut chart if status checks are mixed', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(mixed);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      const chart = accumulated.find('StatusDonutChart');
      assert.strictEqual(chart.prop('pending'), 1);
      assert.strictEqual(chart.prop('failure'), 1);
      assert.strictEqual(chart.prop('success'), 1);
    });

    it('renders nothing with no status checks are present', function() {
      const wrapper = shallow(buildApp({isLoading: false, total: 1}));
      const result = wrapper.find('Accordion').renderProp('children')(noStatus);
      const accumulated = result.find(CheckSuitesAccumulator).renderProp('children')({runsBySuite: new Map()});

      assert.strictEqual(accumulated.find('Octicon').prop('icon'), 'dash');
    });

    it('calls its onIssueishClick handler when an item is clicked', function() {
      const onIssueishClick = sinon.stub();
      const wrapper = shallow(buildApp({isLoading: false, onIssueishClick}));

      wrapper.find('Accordion').prop('onClickItem')(mixed);
      assert.isTrue(onIssueishClick.calledWith(mixed));
    });

    it('calls its onMoreClick handler when a "more" component is clicked', function() {
      const onMoreClick = sinon.stub();
      const wrapper = shallow(buildApp({isLoading: false, onMoreClick}));

      const more = wrapper.find('Accordion').renderProp('moreComponent')();
      more.find('.github-IssueishList-more a').simulate('click');
      assert.isTrue(onMoreClick.called);
    });
  });

  it('renders review button only if needed', function() {
    const openReviews = sinon.spy();
    const wrapper = shallow(buildApp({total: 1, openReviews}));
    assert.isFalse(wrapper.exists('.github-IssueishList-openReviewsButton'));

    wrapper.setProps({needReviewsButton: true});
    const reviews = wrapper.find('Accordion').renderProp('reviewsButton')();
    assert.isTrue(reviews.exists('.github-IssueishList-openReviewsButton'));
    reviews.find('.github-IssueishList-openReviewsButton').simulate('click', {stopPropagation() {}});
    assert.isTrue(openReviews.called);
  });
});
<|endoftext|>


<commit_before>/**
 * @author dmarcos / https://github.com/dmarcos
 * @author mrdoob / http://mrdoob.com
 *
 * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
 *
 * Firefox: http://mozvr.com/downloads/
 * Chromium: https://drive.google.com/folderview?id=0BzudLt22BqGRbW9WTHMtOWMzNjQ&usp=sharing#list
 *
 */

THREE.VREffect = function ( renderer, onError ) {

    var vrHMD;
    var eyeTranslationL, eyeFOVL;
    var eyeTranslationR, eyeFOVR;

    var stereoTransformL = new THREE.Matrix4(),
        stereoTransformR = new THREE.Matrix4();

    var scale = 1;
    Object.defineProperty( this, 'scale', {
        get: function () {

            return scale;

        },
        set: function ( s ) {

            scale = s;
            stereoTransformL.makeTranslation( scale * eyeTranslationL.x, scale * eyeTranslationL.y, scale * eyeTranslationL.z );
            stereoTransformR.makeTranslation( scale * eyeTranslationR.x, scale * eyeTranslationR.y, scale * eyeTranslationR.z );

        }
    } );

    function gotVRDevices( devices ) {

        for ( var i = 0; i < devices.length; i ++ ) {

            if ( devices[ i ] instanceof HMDVRDevice ) {

                vrHMD = devices[ i ];

                if ( vrHMD.getEyeParameters !== undefined ) {

                    var eyeParamsL = vrHMD.getEyeParameters( 'left' );
                    var eyeParamsR = vrHMD.getEyeParameters( 'right' );

                    eyeTranslationL = eyeParamsL.eyeTranslation;
                    eyeTranslationR = eyeParamsR.eyeTranslation;
                    eyeFOVL = eyeParamsL.recommendedFieldOfView;
                    eyeFOVR = eyeParamsR.recommendedFieldOfView;

                } else {

                    // TODO: This is an older code path and not spec compliant.
                    // It should be removed at some point in the near future.
                    eyeTranslationL = vrHMD.getEyeTranslation( 'left' );
                    eyeTranslationR = vrHMD.getEyeTranslation( 'right' );
                    eyeFOVL = vrHMD.getRecommendedEyeFieldOfView( 'left' );
                    eyeFOVR = vrHMD.getRecommendedEyeFieldOfView( 'right' );

                }

                this.scale = 1;

                cameraL.projectionMatrix = fovToProjection( eyeFOVL, true, 0.1, 1000 );
                cameraR.projectionMatrix = fovToProjection( eyeFOVR, true, 0.1, 1000 );

                break; // We keep the first we encounter

            }

        }

        if ( vrHMD === undefined ) {

            if ( onError ) onError( 'HMD not available' );

        }

    }

    if ( navigator.getVRDevices ) {

        navigator.getVRDevices().then( gotVRDevices.bind( this ) );

    }

    //

    this.setSize = function( width, height ) {

        renderer.setSize( width, height );

    };

    // fullscreen

    var isFullscreen = false;

    var canvas = renderer.domElement;
    var fullscreenchange = canvas.mozRequestFullScreen ? 'mozfullscreenchange' : 'webkitfullscreenchange';

    document.addEventListener( fullscreenchange, function ( event ) {

        isFullscreen = document.mozFullScreenElement || document.webkitFullscreenElement;

    }, false );

    this.setFullScreen = function ( boolean ) {

        if ( vrHMD === undefined ) return;
        if ( isFullscreen === boolean ) return;

        if ( canvas.mozRequestFullScreen ) {

            canvas.mozRequestFullScreen( { vrDisplay: vrHMD } );

        } else if ( canvas.webkitRequestFullscreen ) {

            canvas.webkitRequestFullscreen( { vrDisplay: vrHMD } );

        }

    };

    // render

    var cameraL = new THREE.PerspectiveCamera();
    var cameraR = new THREE.PerspectiveCamera();

    cameraL.matrixAutoUpdate = false;
    cameraR.matrixAutoUpdate = false;

    this.render = function ( scene, camera ) {

        if ( vrHMD ) {

            var sceneL, sceneR;
            var autoUpdate;

            if ( Array.isArray( scene ) ) {

                sceneL = scene[ 0 ];
                sceneR = scene[ 1 ];

            } else {

                sceneL = scene;
                sceneR = scene;

                if ( scene.autoUpdate === true ) {

                    scene.updateMatrixWorld();
                    autoUpdate = scene.autoUpdate;
                    scene.autoUpdate = false;

                }

            }

            var size = renderer.getSize();
            size.width /= 2;

            renderer.enableScissorTest( true );
            renderer.clear();

            if ( camera.parent === null ) camera.updateMatrixWorld();

            // render left eye
            renderer.setViewport( 0, 0, size.width, size.height );
            renderer.setScissor( 0, 0, size.width, size.height );
            cameraL.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformL );
            renderer.render( sceneL, cameraL );

            // render right eye
            renderer.setViewport( size.width, 0, size.width, size.height );
            renderer.setScissor( size.width, 0, size.width, size.height );
            cameraR.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformR );
            renderer.render( sceneR, cameraR );

            renderer.enableScissorTest( false );

            if ( autoUpdate === true ) {

                scene.autoUpdate = true;

            }

            return;

        }

        // Regular render mode if not HMD

        if ( Array.isArray( scene ) ) scene = scene[ 0 ];

        renderer.render( scene, camera );

    };

    //

    function fovToNDCScaleOffset( fov ) {

        var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
        var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
        var pyscale = 2.0 / ( fov.upTan + fov.downTan );
        var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
        return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };

    }

    function fovPortToProjection( fov, rightHanded, zNear, zFar ) {

        rightHanded = rightHanded === undefined ? true : rightHanded;
        zNear = zNear === undefined ? 0.01 : zNear;
        zFar = zFar === undefined ? 10000.0 : zFar;

        var handednessScale = rightHanded ? - 1.0 : 1.0;

        // start with an identity matrix
        var mobj = new THREE.Matrix4();
        var m = mobj.elements;

        // and with scale/offset info for normalized device coords
        var scaleAndOffset = fovToNDCScaleOffset( fov );

        // X result, map clip edges to [-w,+w]
        m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
        m[ 0 * 4 + 1 ] = 0.0;
        m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
        m[ 0 * 4 + 3 ] = 0.0;

        // Y result, map clip edges to [-w,+w]
        // Y offset is negated because this proj matrix transforms from world coords with Y=up,
        // but the NDC scaling has Y=down (thanks D3D?)
        m[ 1 * 4 + 0 ] = 0.0;
        m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
        m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
        m[ 1 * 4 + 3 ] = 0.0;

        // Z result (up to the app)
        m[ 2 * 4 + 0 ] = 0.0;
        m[ 2 * 4 + 1 ] = 0.0;
        m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
        m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );

        // W result (= Z in)
        m[ 3 * 4 + 0 ] = 0.0;
        m[ 3 * 4 + 1 ] = 0.0;
        m[ 3 * 4 + 2 ] = handednessScale;
        m[ 3 * 4 + 3 ] = 0.0;

        mobj.transpose();

        return mobj;

    }

    function fovToProjection( fov, rightHanded, zNear, zFar ) {

        var DEG2RAD = Math.PI / 180.0;

        var fovPort = {
            upTan: Math.tan( fov.upDegrees * DEG2RAD ),
            downTan: Math.tan( fov.downDegrees * DEG2RAD ),
            leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
            rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
        };

        return fovPortToProjection( fovPort, rightHanded, zNear, zFar );

    }

};
<commit_msg>update for new three.js<commit_after>/**
 * @author dmarcos / https://github.com/dmarcos
 * @author mrdoob / http://mrdoob.com
 *
 * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
 *
 * Firefox: http://mozvr.com/downloads/
 * Chromium: https://drive.google.com/folderview?id=0BzudLt22BqGRbW9WTHMtOWMzNjQ&usp=sharing#list
 *
 */

THREE.VREffect = function ( renderer, onError ) {

    var vrHMD;
    var eyeTranslationL, eyeFOVL;
    var eyeTranslationR, eyeFOVR;

    var stereoTransformL = new THREE.Matrix4(),
        stereoTransformR = new THREE.Matrix4();

    var scale = 1;
    Object.defineProperty( this, 'scale', {
        get: function () {

            return scale;

        },
        set: function ( s ) {

            scale = s;
            stereoTransformL.makeTranslation( scale * eyeTranslationL.x, scale * eyeTranslationL.y, scale * eyeTranslationL.z );
            stereoTransformR.makeTranslation( scale * eyeTranslationR.x, scale * eyeTranslationR.y, scale * eyeTranslationR.z );

        }
    } );

    function gotVRDevices( devices ) {

        for ( var i = 0; i < devices.length; i ++ ) {

            if ( devices[ i ] instanceof HMDVRDevice ) {

                vrHMD = devices[ i ];

                if ( vrHMD.getEyeParameters !== undefined ) {

                    var eyeParamsL = vrHMD.getEyeParameters( 'left' );
                    var eyeParamsR = vrHMD.getEyeParameters( 'right' );

                    eyeTranslationL = eyeParamsL.eyeTranslation;
                    eyeTranslationR = eyeParamsR.eyeTranslation;
                    eyeFOVL = eyeParamsL.recommendedFieldOfView;
                    eyeFOVR = eyeParamsR.recommendedFieldOfView;

                } else {

                    // TODO: This is an older code path and not spec compliant.
                    // It should be removed at some point in the near future.
                    eyeTranslationL = vrHMD.getEyeTranslation( 'left' );
                    eyeTranslationR = vrHMD.getEyeTranslation( 'right' );
                    eyeFOVL = vrHMD.getRecommendedEyeFieldOfView( 'left' );
                    eyeFOVR = vrHMD.getRecommendedEyeFieldOfView( 'right' );

                }

                this.scale = 1;

                cameraL.projectionMatrix = fovToProjection( eyeFOVL, true, 0.1, 1000 );
                cameraR.projectionMatrix = fovToProjection( eyeFOVR, true, 0.1, 1000 );

                break; // We keep the first we encounter

            }

        }

        if ( vrHMD === undefined ) {

            if ( onError ) onError( 'HMD not available' );

        }

    }

    if ( navigator.getVRDevices ) {

        navigator.getVRDevices().then( gotVRDevices.bind( this ) );

    }

    //

    this.setSize = function( width, height ) {

        renderer.setSize( width, height );

    };

    // fullscreen

    var isFullscreen = false;

    var canvas = renderer.domElement;
    var fullscreenchange = canvas.mozRequestFullScreen ? 'mozfullscreenchange' : 'webkitfullscreenchange';

    document.addEventListener( fullscreenchange, function ( event ) {

        isFullscreen = document.mozFullScreenElement || document.webkitFullscreenElement;

    }, false );

    this.setFullScreen = function ( boolean ) {

        if ( vrHMD === undefined ) return;
        if ( isFullscreen === boolean ) return;

        if ( canvas.mozRequestFullScreen ) {

            canvas.mozRequestFullScreen( { vrDisplay: vrHMD } );

        } else if ( canvas.webkitRequestFullscreen ) {

            canvas.webkitRequestFullscreen( { vrDisplay: vrHMD } );

        }

    };

    // render

    var cameraL = new THREE.PerspectiveCamera();
    var cameraR = new THREE.PerspectiveCamera();

    cameraL.matrixAutoUpdate = false;
    cameraR.matrixAutoUpdate = false;

    this.render = function ( scene, camera ) {

        if ( vrHMD ) {

            var sceneL, sceneR;
            var autoUpdate;

            if ( Array.isArray( scene ) ) {

                sceneL = scene[ 0 ];
                sceneR = scene[ 1 ];

            } else {

                sceneL = scene;
                sceneR = scene;

                if ( scene.autoUpdate === true ) {

                    scene.updateMatrixWorld();
                    autoUpdate = scene.autoUpdate;
                    scene.autoUpdate = false;

                }

            }

            var size = renderer.getSize();
            size.width /= 2;

            renderer.clear();

            if ( camera.parent === null ) camera.updateMatrixWorld();

            renderer.setScissorTest( true );

            // render left eye
            renderer.setViewport( 0, 0, size.width, size.height );
            renderer.setScissor( 0, 0, size.width, size.height );
            cameraL.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformL );
            renderer.render( sceneL, cameraL );

            // render right eye
            renderer.setViewport( size.width, 0, size.width, size.height );
            renderer.setScissor( size.width, 0, size.width, size.height );
            cameraR.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformR );
            renderer.render( sceneR, cameraR );

            renderer.setScissorTest( false );

            if ( autoUpdate === true ) {

                scene.autoUpdate = true;

            }

            return;

        }

        // Regular render mode if not HMD

        if ( Array.isArray( scene ) ) scene = scene[ 0 ];

        renderer.render( scene, camera );

    };

    //

    function fovToNDCScaleOffset( fov ) {

        var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
        var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
        var pyscale = 2.0 / ( fov.upTan + fov.downTan );
        var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
        return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };

    }

    function fovPortToProjection( fov, rightHanded, zNear, zFar ) {

        rightHanded = rightHanded === undefined ? true : rightHanded;
        zNear = zNear === undefined ? 0.01 : zNear;
        zFar = zFar === undefined ? 10000.0 : zFar;

        var handednessScale = rightHanded ? - 1.0 : 1.0;

        // start with an identity matrix
        var mobj = new THREE.Matrix4();
        var m = mobj.elements;

        // and with scale/offset info for normalized device coords
        var scaleAndOffset = fovToNDCScaleOffset( fov );

        // X result, map clip edges to [-w,+w]
        m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
        m[ 0 * 4 + 1 ] = 0.0;
        m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
        m[ 0 * 4 + 3 ] = 0.0;

        // Y result, map clip edges to [-w,+w]
        // Y offset is negated because this proj matrix transforms from world coords with Y=up,
        // but the NDC scaling has Y=down (thanks D3D?)
        m[ 1 * 4 + 0 ] = 0.0;
        m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
        m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
        m[ 1 * 4 + 3 ] = 0.0;

        // Z result (up to the app)
        m[ 2 * 4 + 0 ] = 0.0;
        m[ 2 * 4 + 1 ] = 0.0;
        m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
        m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );

        // W result (= Z in)
        m[ 3 * 4 + 0 ] = 0.0;
        m[ 3 * 4 + 1 ] = 0.0;
        m[ 3 * 4 + 2 ] = handednessScale;
        m[ 3 * 4 + 3 ] = 0.0;

        mobj.transpose();

        return mobj;

    }

    function fovToProjection( fov, rightHanded, zNear, zFar ) {

        var DEG2RAD = Math.PI / 180.0;

        var fovPort = {
            upTan: Math.tan( fov.upDegrees * DEG2RAD ),
            downTan: Math.tan( fov.downDegrees * DEG2RAD ),
            leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
            rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
        };

        return fovPortToProjection( fovPort, rightHanded, zNear, zFar );

    }

};
<|endoftext|>


<commit_before>'use strict';

import * as Modules from './src/modules';
import * as Props from './src/properties';
import { CONST, TYPES } from './src/core/Constants';
import Synth from './src/Synth';

const methods = Object.keys(Modules);

export default (props) => {
    let factory = {
            VARS: CONST,
            TYPES: TYPES
        },
        properties = props || {},
        synth = new Synth(properties),
        fx;

    function callModule (type) {
        return (label, props) => {
            synth.module(type, label, props);
            return factory;
        };
    }

    function init () {
        methods.forEach((type) => {
            const fx = type.toLowerCase();
            factory[fx] = callModule(type);
        });
    }

    function module (type, label, props) {
        synth.module(type, label, props);
        return factory;
    }

    function destroyModule (id) {
        //TODO check on deletion of voices...you can remove sounds runtime
        delete synth.modulesConfig[id];
        return factory;
    }

    function linkModules (source, target) {
        if (source === CONST.MASTER) {
            throw new Error('ERROR :: master can\'t be linked to any modules');
        }

        if (synth.modulesConfig[source] && synth.modulesConfig[target]) {
            synth.modulesConfig[source].props.link = target;
        }
        return factory;
    }

    function listAllModules () {
        return methods;
    }

    function listModules () {
        return synth.modulesConfig;
    }

    function getModulePropertiesSet (type) {
        const p = Props[type + 'Props'] || {};
        return Object.assign({}, p, Props.DefaultProps);
    }

    function play (note) {
        synth.play(note);
    }

    function stop (note) {
        synth.stop(note);
    }

    init();

    factory.module = module;
    factory.destroyModule = destroyModule;
    factory.linkModules = linkModules;

    factory.listAllModules = listAllModules;
    factory.listModules = listModules;
    factory.getModulePropertiesSet = getModulePropertiesSet;

    factory.play = play;
    factory.stop = stop;

    return factory;
};
<commit_msg>library todo<commit_after>'use strict';

import * as Modules from './src/modules';
import * as Props from './src/properties';
import { CONST, TYPES } from './src/core/Constants';
import Synth from './src/Synth';

const methods = Object.keys(Modules);

export default (props) => {
    let factory = {
            VARS: CONST,
            TYPES: TYPES
        },
        properties = props || {},
        synth = new Synth(properties),
        fx;

    function callModule (type) {
        return (label, props) => {
            synth.module(type, label, props);
            return factory;
        };
    }

    function init () {
        methods.forEach((type) => {
            const fx = type.toLowerCase();
            factory[fx] = callModule(type);
        });
    }

    //TODO create an adsr method to manage the adsr params...

    //TODO creae a master level volume method..

    function module (type, label, props) {
        synth.module(type, label, props);
        return factory;
    }

    function destroyModule (id) {
        //TODO check on deletion of voices...you can remove sounds runtime
        delete synth.modulesConfig[id];
        return factory;
    }

    function linkModules (source, target) {
        if (source === CONST.MASTER) {
            throw new Error('ERROR :: master can\'t be linked to any modules');
        }

        if (synth.modulesConfig[source] && synth.modulesConfig[target]) {
            synth.modulesConfig[source].props.link = target;
        }
        return factory;
    }

    function listAllModules () {
        return methods;
    }

    function listModules () {
        return synth.modulesConfig;
    }

    function getModulePropertiesSet (type) {
        const p = Props[type + 'Props'] || {};
        return Object.assign({}, p, Props.DefaultProps);
    }

    function play (note) {
        synth.play(note);
    }

    function stop (note) {
        synth.stop(note);
    }

    init();

    factory.module = module;
    factory.destroyModule = destroyModule;
    factory.linkModules = linkModules;

    factory.listAllModules = listAllModules;
    factory.listModules = listModules;
    factory.getModulePropertiesSet = getModulePropertiesSet;

    factory.play = play;
    factory.stop = stop;

    return factory;
};
<|endoftext|>


<commit_before>var extend = require('extend');
var q = require('q');
/**
 * Defines a mapper
 */
module.exports = function(manager, namespace, options) {
  var mapper = {
    options: extend(true,
      // default options
      {
        type:           namespace,
        autoincrement:  true,
        fields:         {},
        views:          {},
        record:         {
          beforeSave: function() { return true; }
          ,afterSave: function() { return true; }
          ,beforeRemove: function() { return true; }
          ,afterRemove: function() { return true; }
        }
      }
      , options
    ),
    /**
     * Finds data from the specified resultset
     */
    find: function(view, criteria) {
      var result = q.defer();
      if (criteria instanceof Array) {
        if (criteria.length > 1) {
          criteria = {
            keys: criteria
          };
        } else {
          criteria = {
            key: criteria[0]
          };
        }
      } else if (!(criteria instanceof Object)) {
        criteria = {
          key: criteria
        };
      }
      criteria = extend(true, {
        limit: 10,
        include_docs: true,
        skip: 0
      }, criteria);
      manager.cb.view(namespace, view, criteria).query(function(err, data, misc) {
        if (err) {
          result.reject(err);
        } else {
          result.resolve(
            resultset.deserialize(view, criteria, data, misc)
          );
        }
      });
      return result.promise
    },
    /**
     * Creates a new record
     */
    create: function(doc) {
      return record.deserialize(doc);
    },
    /**
     * Automatically creates
     */
    setup: function() {
      var result = q.defer();
      var docs = { views: {} };
      var found = false;
      for(var viewName in mapper.options.views) {
        var view = mapper.options.views[viewName];
        docs.views[viewName] = {};
        if (view.hasOwnProperty('map')) {
          found = true;
          docs.views[viewName].map = view.map;
        }
        if (view.hasOwnProperty('reduce')) {
          found = true;
          docs.views[viewName].reduce = view.reduce;
        }
      }
      if (found) {
        manager.cb.setDesignDoc(mapper.options.type, docs, function(err) {
          if (err) {
            result.reject(err);
          } else {
            result.resolve(docs);
          }
        });
      } else result.resolve(false);
      return result.promise;
    }
  };
  // initialize fields properties
  for(var fieldName in mapper.options.fields) {
    mapper.options.fields[fieldName] = require('./field')(
      fieldName,
      mapper.options.fields[fieldName]
    );
    if (mapper.options.fields[fieldName].meta.unique) {
      mapper.options.views[fieldName] = {
        type: 'unique', fields: [fieldName]
      };
    } else if (mapper.options.fields[fieldName].meta.index) {
      mapper.options.views[fieldName] = {
        type: 'index', fields: [fieldName]
      };
    }
  }
  // initialize views
  for(var viewName in mapper.options.views) {
    var view = mapper.options.views[viewName];
    // handle map function
    if (!view.hasOwnProperty('map')) {
      view.map =
        'function(doc, meta) {\n'
        + '\tif(doc._type && doc._type === ' + JSON.stringify(mapper.options.type) + ') {\n\t\t'
      ;
      if (view.fields.length > 1) {
        view.map += 'emit([doc.' + view.fields.join(', doc.') + '], null);';
      } else {
        view.map += 'emit(doc.' + view.fields[0] + ', null);';
      }
      view.map += '\n\t}\n}';
    } else if (view.map instanceof Function) {
      view.map = view.map.toString();
    }
    // handle finder
    if (view.find instanceof Function) {
      mapper[viewName] = view.find;
    } else {
      (function(viewName) {
        mapper[viewName] = function() {
          return this.find(viewName, arguments.length > 1 ? arguments : arguments[0]);
        };
      })(viewName);
    }
  }
  // record manager
  var record = require('./record')(manager, mapper);
  // resultset manager
  var resultset = require('./resultset')(manager, mapper);
  return mapper;
};<commit_msg>rewrite the mapper to handle more options and use event emitter<commit_after>var extend = require('extend');
var q = require('q');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var uuid = require('node-uuid');

/**
 * Initialize a mapper class for the specified manager
 */
module.exports = function(manager) {
  /**
   * Defines a new mapper instance into the specified manager
   */
  var mapper = function(namespace, options) {
    var self = this;
    // parent constructor call
    EventEmitter.call(this);
    // default options
    this.options = extend(true,
      {
        type:           namespace,
        autoincrement:  true,
        fields:         {},
        views:          {},
        // register factories
        factory: {
          field:        manager.options.factory.field(manager, this),
          record:       manager.options.factory.record(manager, this),
          resultset:    manager.options.factory.resultset(manager, this)
        }
      }
      , options
    );
    // initialize fields properties
    for(var name in this.options.fields) {
      this.options.fields[name] = new this.options.factory.field(
        name, this.options.fields[name]
      );
      // behaviour decorator
      for(var i = 0; i < manager.options.behaviours.length; i++) {
        this.options.fields[name] = manager.options.behaviours[i].apply(
          manager, [
            this, this.options.fields[name], name
          ]
        );
      }
    }
    // initialize views
    for(var name in this.options.views) {
      var view = this.options.views[name];
      // handle map function
      if (!view.hasOwnProperty('map')) {
        view.map =
          'function(doc, meta) {\n'
          + '\tif(doc._type && doc._type === ' + JSON.stringify(mapper.options.type) + ') {\n\t\t'
        ;
        if (view.fields.length > 1) {
          view.map += 'emit([doc.' + view.fields.join(', doc.') + '], null);';
        } else {
          view.map += 'emit(doc.' + view.fields[0] + ', null);';
        }
        view.map += '\n\t}\n}';
      } else if (view.map instanceof Function) {
        view.map = view.map.toString();
      }
      // handle finder
      if (view.find instanceof Function) {
        this[name] = view.find;
      } else {
        (function(viewName) {
          self[viewName] = function() {
            return self.find(viewName, arguments.length > 1 ? arguments : arguments[0]);
          };
        })(name);
      }
    }
    // chain error to manager
    this.on('error', function(err) {
      manager.emit('error', err);
    });
    // registers itself into the manager
    manager.mappers[namespace] = this;
    manager.emit('declare', this);
  };
  util.inherits(mapper, EventEmitter);

  /**
   * Finds data from the specified resultset
   */
  mapper.prototype.find = function(view, criteria) {
    var result = q.defer();
    // handling criteria parameters
    if (criteria instanceof Array) {
      if (criteria.length > 1) {
        criteria = {
          keys: criteria
        };
      } else {
        criteria = {
          key: criteria[0]
        };
      }
    } else if (!(criteria instanceof Object)) {
      criteria = {
        key: criteria
      };
    }
    // set criteria default options :
    criteria = extend(true, {
      limit: 10,            // by default limit to 10 first entries
      include_docs: true,   // also retrieve document contents to populate records
      skip: 0               // pagination
    }, criteria);
    // request :
    manager.cb.view(this.options.type, view, criteria).query(function(err, data, misc) {
      if (err) {
        result.reject(err);
        self.emit('error', err);
      } else {
        var resultset = new this.options.factory.resultset(
          data, {
            view: view,
            misc: misc,
            criteria: criteria
          }
        );
        result.resolve(resultset);
        self.emit('find', resultset);
      }
    });
    return result.promise;
  };
  /**
   * Creates a new record
   */
  mapper.prototype.create = function(doc) {
    return new this.options.factory.record(doc);
  };
  /**
   * Retrieves the next sequence id
   */
  mapper.prototype.nextId = function() {
    var result = q.defer();
    var self = this;
    if (this.options.autoincrement == true) {
      manager.cb.incr(
        'seq.' + mapper.options.type,
        {initial: 1, offset: 1},
        function(err, data) {
          if (err) {
            result.reject(err);
            self.emit('error', err);
          } else {
            result.resolve(data.value);
            self.emit('next', data.value);
          }
        }
      );
    } else {
      var id = uuid.v4();
      result.resolve(id);
      self.emit('next', id);
    }
    return result.promise;
  };
  /**
   * Automatically creates views into couchbase
   */
  mapper.prototype.setup: function() {
    var result = q.defer();
    var docs = { views: {} };
    var found = false;
    var self = this;
    for(var name in this.options.views) {
      var view = this.options.views[name];
      docs.views[name] = {};
      if (view.hasOwnProperty('map')) {
        found = true;
        docs.views[name].map = view.map;
      }
      if (view.hasOwnProperty('reduce')) {
        found = true;
        docs.views[name].reduce = view.reduce;
      }
    }
    if (found) {
      manager.cb.setDesignDoc(this.options.type, docs, function(err) {
        if (err) {
          result.reject(err);
          self.emit('error', err);
        } else {
          result.resolve(docs);
          self.emit('setup', docs);
        }
      });
    } else result.resolve(false);
    return result.promise;
  };
  // returns the mapper class
  return mapper;
};<|endoftext|>


<commit_before>'use strict';

var _find = require('lodash.find');
var raf = require('raf');
var xhr = require('xhr');
var contra = require('contra');
var cache = require('./cache');
var aggregate = require('./aggregate');
var emitUpstream = require('./emitUpstream');
var methods = ['get', 'post', 'put', 'delete', 'patch'];
var stateEvents = ['create', 'cache', 'request', 'abort', 'error', 'data', 'always'];
var core;

function measly (measlyOptions, parent) {
  var layer = find(measlyOptions.context, true);
  if (layer) {
    return layer;
  }

  layer = contra.emitter({
    thinner: thinner,
    parent: parent,
    context: measlyOptions.context,
    children: [],
    requests: [],
    cache: {},
    abort: abort,
    request: request
  }, { throws: false });

  methods.forEach(function addMethod (method) {
    layer[method] = fire.bind(null, method);
  });

  function request (url, opt) {
    var method = opt.method;
    if (opt && opt.xhr && opt.xhr.method) {
      method = opt.xhr.method;
    }
    if (!method) {
      throw new Error('A request method must be specified.');
    }
    return fire(method, url, opt);
  }

  function thinner (opt) {
    var child = measly(opt || measlyOptions, layer);
    layer.children.push(child);
    return child;
  }

  function fire (method, url, opt) {
    var fireOptions = opt || {};
    fireOptions.url = url;
    fireOptions.method = method.toUpperCase();

    var req = contra.emitter({
      done: false,
      requested: false,
      prevented: false,
      prevent: prevent,
      layer: layer,
      context: fireOptions.context || measlyOptions.context,
      cache: fireOptions.cache || measlyOptions.cache,
      url: url,
      method: method
    }, { throws: false });
    req.abort = abortRequest.bind(null, req);

    emitUpstream(req, layer, stateEvents);
    raf(go);

    function go () {
      req.emit('create', req);
      request();
    }

    function prevent (err, body, statusCode) {
      if (req.prevented) {
        return;
      }
      if (req.requested === true) {
        throw new Error('A request has already been made. Prevent synchronously!');
      }
      req.prevented = true;
      raf(prevented);

      function prevented () {
        var xhr = {
          body: body,
          statusCode: statusCode || err ? 500 : 200
        };
        req.emit('cache', err, body);
        done(err, xhr, body);
      }
    }

    function cacheHit () {
      var entry = cache.find(url, layer);
      if (entry) {
        entry.cached = true;
        req.xhr = entry;
        req.prevented = true;
        req.emit('cache', entry.error, entry.body);
        done(entry.error, entry, entry.body);
      }
    }

    function request () {
      if (method === 'GET') {
        cacheHit();
      }
      if (req.prevented) {
        return;
      }
      req.requested = true;
      req.xhr = xhr(fireOptions, done);
      req.emit('request', req.xhr);
    }

    function done (err, res, body) {
      req.error = err;
      req.response = body;
      req.done = true;
      if (req.cache && !res.cached) {
        layer.cache[url] = {
          expires: cache.expires(req.cache),
          error: err,
          body: body,
          statusCode: res.statusCode
        };
      }
      if (err) {
        req.emit('error', err, body);
        req.emit(err.statusCode, err, body);
      } else {
        req.emit('data', body);
      }
      untrack(req);
    }

    track(req);
    return req;
  }

  function abort () {
    aggregate.requests(layer, true).forEach(abortRequest);
  }

  function abortRequest (req) {
    req.prevented = true;
    req.emit('abort', req.xhr);

    if (req.xhr) {
      req.xhr.abort();
    }
    untrack(req);
  }

  function track (req) {
    layer.requests.push(req);
  }

  function untrack (req) {
    var i = layer.requests.indexOf(req);
    var spliced = layer.requests.splice(i, 1);
    if (spliced.length) {
      req.emit('always', req.error, req.response, req);
    }
  }

  return layer;
}

function find (context, shallow) {
  if (core === void 0) {
    return;
  }
  var layers = aggregate.contexts(core);
  while (context && !shallow) {
    var needle = _find(layers, { context: context });
    if (needle) {
      return needle.layer;
    }
    context = context.parentNode;
    shallow = true;
  }
}

module.exports = core = measly({
  context: global.document.body,
  base: ''
});

core.find = find;
<commit_msg>fix api<commit_after>'use strict';

var _find = require('lodash.find');
var raf = require('raf');
var xhr = require('xhr');
var contra = require('contra');
var cache = require('./cache');
var aggregate = require('./aggregate');
var emitUpstream = require('./emitUpstream');
var methods = ['get', 'post', 'put', 'delete', 'patch'];
var stateEvents = ['create', 'cache', 'request', 'abort', 'error', 'data', 'always'];
var core;

function measly (measlyOptions, parent) {
  var layer = find(measlyOptions.context, true);
  if (layer) {
    return layer;
  }

  layer = contra.emitter({
    layer: thinner,
    parent: parent,
    context: measlyOptions.context,
    children: [],
    requests: [],
    cache: {},
    abort: abort,
    request: request
  }, { throws: false });

  methods.forEach(function addMethod (method) {
    layer[method] = fire.bind(null, method);
  });

  function request (url, opt) {
    var method = opt.method;
    if (opt && opt.xhr && opt.xhr.method) {
      method = opt.xhr.method;
    }
    if (!method) {
      throw new Error('A request method must be specified.');
    }
    return fire(method, url, opt);
  }

  function thinner (opt) {
    var child = measly(opt || measlyOptions, layer);
    layer.children.push(child);
    return child;
  }

  function fire (method, url, opt) {
    var fireOptions = opt || {};
    fireOptions.url = url;
    fireOptions.method = method.toUpperCase();

    var req = contra.emitter({
      done: false,
      requested: false,
      prevented: false,
      prevent: prevent,
      layer: layer,
      context: fireOptions.context || measlyOptions.context,
      cache: fireOptions.cache || measlyOptions.cache,
      url: url,
      method: method
    }, { throws: false });
    req.abort = abortRequest.bind(null, req);

    emitUpstream(req, layer, stateEvents);
    raf(go);

    function go () {
      req.emit('create', req);
      request();
    }

    function prevent (err, body, statusCode) {
      if (req.prevented) {
        return;
      }
      if (req.requested === true) {
        throw new Error('A request has already been made. Prevent synchronously!');
      }
      req.prevented = true;
      raf(prevented);

      function prevented () {
        var xhr = {
          body: body,
          statusCode: statusCode || err ? 500 : 200
        };
        req.emit('cache', err, body);
        done(err, xhr, body);
      }
    }

    function cacheHit () {
      var entry = cache.find(url, layer);
      if (entry) {
        entry.cached = true;
        req.xhr = entry;
        req.prevented = true;
        req.emit('cache', entry.error, entry.body);
        done(entry.error, entry, entry.body);
      }
    }

    function request () {
      if (method === 'GET') {
        cacheHit();
      }
      if (req.prevented) {
        return;
      }
      req.requested = true;
      req.xhr = xhr(fireOptions, done);
      req.emit('request', req.xhr);
    }

    function done (err, res, body) {
      req.error = err;
      req.response = body;
      req.done = true;
      if (req.cache && !res.cached) {
        layer.cache[url] = {
          expires: cache.expires(req.cache),
          error: err,
          body: body,
          statusCode: res.statusCode
        };
      }
      if (err) {
        req.emit('error', err, body);
        req.emit(err.statusCode, err, body);
      } else {
        req.emit('data', body);
      }
      untrack(req);
    }

    track(req);
    return req;
  }

  function abort () {
    aggregate.requests(layer, true).forEach(abortRequest);
  }

  function abortRequest (req) {
    req.prevented = true;
    req.emit('abort', req.xhr);

    if (req.xhr) {
      req.xhr.abort();
    }
    untrack(req);
  }

  function track (req) {
    layer.requests.push(req);
  }

  function untrack (req) {
    var i = layer.requests.indexOf(req);
    var spliced = layer.requests.splice(i, 1);
    if (spliced.length) {
      req.emit('always', req.error, req.response, req);
    }
  }

  return layer;
}

function find (context, shallow) {
  if (core === void 0) {
    return;
  }
  var layers = aggregate.contexts(core);
  while (context && !shallow) {
    var needle = _find(layers, { context: context });
    if (needle) {
      return needle.layer;
    }
    context = context.parentNode;
    shallow = true;
  }
}

module.exports = core = measly({
  context: global.document.body,
  base: ''
});

core.find = find;
<|endoftext|>


<commit_before>'use strict';

var _find = require('lodash.find');
var raf = require('raf');
var xhr = require('xhr');
var contra = require('contra');
var cache = require('./cache');
var aggregate = require('./aggregate');
var emitUpstream = require('./emitUpstream');
var methods = ['get', 'post', 'put', 'delete', 'patch'];
var stateEvents = ['create', 'cache', 'request', 'abort', 'error', 'data', 'always'];
var core;

function measly (measlyOptions, parent) {
  var layer = find(measlyOptions.context, true);
  if (layer) {
    return layer;
  }

  layer = contra.emitter({
    thinner: thinner,
    parent: parent,
    context: measlyOptions.context,
    children: [],
    requests: [],
    cache: {},
    abort: abort,
    request: request
  }, { throws: false });

  methods.forEach(function addMethod (method) {
    layer[method] = fire.bind(null, method);
  });

  function request (url, opt) {
    var method = opt.method;
    if (opt && opt.xhr && opt.xhr.method) {
      method = opt.xhr.method;
    }
    if (!method) {
      throw new Error('A request method must be specified.');
    }
    return fire(method, url, opt);
  }

  function thinner (opt) {
    var child = measly(opt || measlyOptions, layer);
    layer.children.push(child);
    return child;
  }

  function fire (method, url, opt) {
    var fireOptions = opt || {};
    fireOptions.url = url;
    fireOptions.method = method.toUpperCase();

    var req = contra.emitter({
      done: false,
      requested: false,
      prevented: false,
      prevent: prevent,
      layer: layer,
      context: fireOptions.context || measlyOptions.context,
      cache: fireOptions.cache || measlyOptions.cache,
      url: url,
      method: method
    }, { throws: false });
    req.abort = abortRequest.bind(null, req);

    emitUpstream(req, layer, stateEvents);
    raf(go);

    function go () {
      req.emit('create', req);
      request();
    }

    function prevent (err, body, statusCode) {
      if (req.prevented) {
        return;
      }
      if (req.requested === true) {
        throw new Error('A request has already been made. Prevent synchronously!');
      }
      req.prevented = true;
      raf(prevented);

      function prevented () {
        var xhr = {
          body: body,
          statusCode: statusCode || err ? 500 : 200
        };
        req.emit('cache', err, body);
        done(err, xhr, body);
      }
    }

    function cacheHit () {
      var entry = cache.find(url, layer);
      if (entry) {
        entry.cached = true;
        req.xhr = entry;
        req.prevented = true;
        req.emit('cache', entry.error, entry.body);
        done(entry.error, entry, entry.body);
      }
    }

    function request () {
      if (method === 'GET') {
        cacheHit();
      }
      if (req.prevented) {
        return;
      }
      req.requested = true;
      req.xhr = xhr(fireOptions, done);
      req.emit('request', req.xhr);
    }

    function done (err, res, body) {
      req.error = err;
      req.response = body;
      req.done = true;
      if (req.cache && !res.cached) {
        layer.cache[url] = {
          expires: cache.expires(req.cache),
          error: err,
          body: body,
          statusCode: res.statusCode
        };
      }
      if (err) {
        req.emit('error', err, body);
        req.emit(err.statusCode, err, body);
      } else {
        req.emit('data', body);
      }
      untrack(req);
    }

    track(req);
    return req;
  }

  function abort () {
    aggregate.requests(layer, true).forEach(abortRequest);
  }

  function abortRequest (req) {
    req.prevented = true;
    req.emit('abort', req.xhr);

    if (req.xhr) {
      req.xhr.abort();
    }
    untrack(req);
  }

  function track (req) {
    layer.requests.push(req);
  }

  function untrack (req) {
    var i = layer.requests.indexOf(req);
    var spliced = layer.requests.splice(i, 1);
    if (spliced.length) {
      req.emit('always', req.error, req.response, req);
    }
  }

  return layer;
}

function find (context, shallow) {
  var layers = aggregate.contexts(core);
  while (context && !shallow) {
    var needle = _find(layers, { context: context });
    if (needle) {
      return needle.layer;
    }
    context = context.parentNode;
    shallow = true;
  }
}

module.exports = core = measly({
  context: global.document.body,
  base: ''
});

core.find = find;
<commit_msg>fix issue<commit_after>'use strict';

var _find = require('lodash.find');
var raf = require('raf');
var xhr = require('xhr');
var contra = require('contra');
var cache = require('./cache');
var aggregate = require('./aggregate');
var emitUpstream = require('./emitUpstream');
var methods = ['get', 'post', 'put', 'delete', 'patch'];
var stateEvents = ['create', 'cache', 'request', 'abort', 'error', 'data', 'always'];
var core;

function measly (measlyOptions, parent) {
  var layer = find(measlyOptions.context, true);
  if (layer) {
    return layer;
  }

  layer = contra.emitter({
    thinner: thinner,
    parent: parent,
    context: measlyOptions.context,
    children: [],
    requests: [],
    cache: {},
    abort: abort,
    request: request
  }, { throws: false });

  methods.forEach(function addMethod (method) {
    layer[method] = fire.bind(null, method);
  });

  function request (url, opt) {
    var method = opt.method;
    if (opt && opt.xhr && opt.xhr.method) {
      method = opt.xhr.method;
    }
    if (!method) {
      throw new Error('A request method must be specified.');
    }
    return fire(method, url, opt);
  }

  function thinner (opt) {
    var child = measly(opt || measlyOptions, layer);
    layer.children.push(child);
    return child;
  }

  function fire (method, url, opt) {
    var fireOptions = opt || {};
    fireOptions.url = url;
    fireOptions.method = method.toUpperCase();

    var req = contra.emitter({
      done: false,
      requested: false,
      prevented: false,
      prevent: prevent,
      layer: layer,
      context: fireOptions.context || measlyOptions.context,
      cache: fireOptions.cache || measlyOptions.cache,
      url: url,
      method: method
    }, { throws: false });
    req.abort = abortRequest.bind(null, req);

    emitUpstream(req, layer, stateEvents);
    raf(go);

    function go () {
      req.emit('create', req);
      request();
    }

    function prevent (err, body, statusCode) {
      if (req.prevented) {
        return;
      }
      if (req.requested === true) {
        throw new Error('A request has already been made. Prevent synchronously!');
      }
      req.prevented = true;
      raf(prevented);

      function prevented () {
        var xhr = {
          body: body,
          statusCode: statusCode || err ? 500 : 200
        };
        req.emit('cache', err, body);
        done(err, xhr, body);
      }
    }

    function cacheHit () {
      var entry = cache.find(url, layer);
      if (entry) {
        entry.cached = true;
        req.xhr = entry;
        req.prevented = true;
        req.emit('cache', entry.error, entry.body);
        done(entry.error, entry, entry.body);
      }
    }

    function request () {
      if (method === 'GET') {
        cacheHit();
      }
      if (req.prevented) {
        return;
      }
      req.requested = true;
      req.xhr = xhr(fireOptions, done);
      req.emit('request', req.xhr);
    }

    function done (err, res, body) {
      req.error = err;
      req.response = body;
      req.done = true;
      if (req.cache && !res.cached) {
        layer.cache[url] = {
          expires: cache.expires(req.cache),
          error: err,
          body: body,
          statusCode: res.statusCode
        };
      }
      if (err) {
        req.emit('error', err, body);
        req.emit(err.statusCode, err, body);
      } else {
        req.emit('data', body);
      }
      untrack(req);
    }

    track(req);
    return req;
  }

  function abort () {
    aggregate.requests(layer, true).forEach(abortRequest);
  }

  function abortRequest (req) {
    req.prevented = true;
    req.emit('abort', req.xhr);

    if (req.xhr) {
      req.xhr.abort();
    }
    untrack(req);
  }

  function track (req) {
    layer.requests.push(req);
  }

  function untrack (req) {
    var i = layer.requests.indexOf(req);
    var spliced = layer.requests.splice(i, 1);
    if (spliced.length) {
      req.emit('always', req.error, req.response, req);
    }
  }

  return layer;
}

function find (context, shallow) {
  if (core === void 0) {
    return;
  }
  var layers = aggregate.contexts(core);
  while (context && !shallow) {
    var needle = _find(layers, { context: context });
    if (needle) {
      return needle.layer;
    }
    context = context.parentNode;
    shallow = true;
  }
}

module.exports = core = measly({
  context: global.document.body,
  base: ''
});

core.find = find;
<|endoftext|>


<commit_before>'use strict';

var async = require('async');

var debug = require('./util/debug')('analysis');

var Factory = require('./workflow/factory');
var toposort = require('../lib/dag/toposort');
var validator = require('../lib/dag/validator');

var DatabaseService = require('./service/database');

function Analysis(rootNode) {
    this.rootNode = rootNode;
}

Analysis.prototype.id = function() {
    return this.rootNode.id();
};

Analysis.prototype.getQuery = function() {
    return this.rootNode.getQuery();
};

Analysis.prototype.getRoot = function() {
    return this.rootNode;
};

Analysis.prototype.getNodes = function() {
    function buildList(node, nodesList) {
        nodesList = nodesList || [node];

        node.getInputNodes().forEach(function(inputNode) {
            nodesList.push(inputNode);

            buildList(inputNode, nodesList);
        });

        return nodesList;
    }

    return buildList(this.rootNode);
};

Analysis.prototype.getSortedNodes = function() {
    return toposort(this.rootNode);
};

function AnalysisFactory(DatabaseServiceClass) {
    this.DatabaseServiceClass = DatabaseServiceClass;
}

AnalysisFactory.prototype.create = function(configuration, definition, callback) {
    debug('Using configuration=%j', configuration);
    var databaseService = new this.DatabaseServiceClass(configuration.user, configuration.db, configuration.batch);

    async.waterfall(
        [
            function analysis$createWithFactory(done) {
                var factory = new Factory(configuration.user, databaseService);
                factory.create(JSON.parse(JSON.stringify(definition)), done);
            },
            function analysis$validate(rootNode, done) {
                if (!validator.isValid(rootNode)) {
                    return done(new Error('Invalid analysis, cycle found'));
                }

                return done(null, new Analysis(rootNode));
            },
            function analysis$register(analysis, done) {
                databaseService.registerAnalysisInCatalog(analysis, function(err) {
                    return done(err, analysis);
                });
            },
            function analysis$queueOperations(analysis, done) {
                databaseService.queueAnalysisOperations(analysis, function(err) {
                    return done(err, analysis);
                });
            },
            function analysis$track(analysis, done) {
                databaseService.trackAnalysis(analysis, function(err) {
                    return done(err, analysis);
                });
            }
        ],
        function analysis$finish(err, analysis) {
            if (err) {
                if (err && err.message && err.message.match(/permission denied/i)) {
                    console.error('>>>>>>>>>>>>>', err);
                    err = new Error('Analysis requires authentication with API key: permission denied.');
                }
                return callback(err);
            }

            return callback(null, analysis);
        }
    );
};

module.exports = AnalysisFactory;
var analysisFactory = new AnalysisFactory(DatabaseService);
module.exports.create = analysisFactory.create.bind(analysisFactory);
module.exports.reference = require('../reference');
module.exports.version = require('../package.json').version;
<commit_msg>Fix lint error.<commit_after>'use strict';

var async = require('async');

var debug = require('./util/debug')('analysis');

var Factory = require('./workflow/factory');
var toposort = require('../lib/dag/toposort');
var validator = require('../lib/dag/validator');

var DatabaseService = require('./service/database');

function Analysis(rootNode) {
    this.rootNode = rootNode;
}

Analysis.prototype.id = function() {
    return this.rootNode.id();
};

Analysis.prototype.getQuery = function() {
    return this.rootNode.getQuery();
};

Analysis.prototype.getRoot = function() {
    return this.rootNode;
};

Analysis.prototype.getNodes = function() {
    function buildList(node, nodesList) {
        nodesList = nodesList || [node];

        node.getInputNodes().forEach(function(inputNode) {
            nodesList.push(inputNode);

            buildList(inputNode, nodesList);
        });

        return nodesList;
    }

    return buildList(this.rootNode);
};

Analysis.prototype.getSortedNodes = function() {
    return toposort(this.rootNode);
};

function AnalysisFactory(DatabaseServiceClass) {
    this.DatabaseServiceClass = DatabaseServiceClass;
}

AnalysisFactory.prototype.create = function(configuration, definition, callback) {
    debug('Using configuration=%j', configuration);
    var databaseService = new this.DatabaseServiceClass(configuration.user, configuration.db, configuration.batch);

    async.waterfall(
        [
            function analysis$createWithFactory(done) {
                var factory = new Factory(configuration.user, databaseService);
                factory.create(JSON.parse(JSON.stringify(definition)), done);
            },
            function analysis$validate(rootNode, done) {
                if (!validator.isValid(rootNode)) {
                    return done(new Error('Invalid analysis, cycle found'));
                }

                return done(null, new Analysis(rootNode));
            },
            function analysis$register(analysis, done) {
                databaseService.registerAnalysisInCatalog(analysis, function(err) {
                    return done(err, analysis);
                });
            },
            function analysis$queueOperations(analysis, done) {
                databaseService.queueAnalysisOperations(analysis, function(err) {
                    return done(err, analysis);
                });
            },
            function analysis$track(analysis, done) {
                databaseService.trackAnalysis(analysis, function(err) {
                    return done(err, analysis);
                });
            }
        ],
        function analysis$finish(err, analysis) {
            if (err) {
                if (err && err.message && err.message.match(/permission denied/i)) {
                    err = new Error('Analysis requires authentication with API key: permission denied.');
                }
                return callback(err);
            }

            return callback(null, analysis);
        }
    );
};

module.exports = AnalysisFactory;
var analysisFactory = new AnalysisFactory(DatabaseService);
module.exports.create = analysisFactory.create.bind(analysisFactory);
module.exports.reference = require('../reference');
module.exports.version = require('../package.json').version;
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var BaseDialog = require('utils/dialogs/dialog');
  var TemplateHTML = require('hbs!./import/html');
  var ContentHTML = require('hbs!./import/content');
  var Sunstone = require('sunstone');
  var Notifier = require('utils/notifier');
  var Locale = require('utils/locale');
  var ResourceSelect = require('utils/resource-select');
  var OpenNebulaImage = require('opennebula/image');
  var OpenNebulaTemplate = require('opennebula/template');
  var TemplateUtils = require('utils/template-utils');

  /*
    CONSTANTS
   */

  var DIALOG_ID = require('./import/dialogId');
  var TAB_ID = require('../tabId');

  /*
    CONSTRUCTOR
   */

  function Dialog() {
    this.dialogId = DIALOG_ID;

    BaseDialog.call(this);
  }

  Dialog.DIALOG_ID = DIALOG_ID;
  Dialog.prototype = Object.create(BaseDialog.prototype);
  Dialog.prototype.constructor = Dialog;
  Dialog.prototype.html = _html;
  Dialog.prototype.onShow = _onShow;
  Dialog.prototype.setup = _setup;
  Dialog.prototype.setParams = _setParams;
  Dialog.prototype.try_to_create_template = _try_to_create_template;

  return Dialog;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      'dialogId': this.dialogId
    });
  }

  function _setup(context) {
    var that = this;

    context.foundation('abide', 'reflow');
    $("#market_import_dialog_content", context).html(
      ContentHTML({'element': this.element})
    );

    // Filter out DS with type system (1) or file (2)
    var filter_att = ["TYPE", "TYPE"];
    var filter_val = ["1", "2"];

    ResourceSelect.insert('div#market_img_datastore', context, "Datastore",
                        null, false, null, filter_att, filter_val);

    context.off('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form');
    context.off('valid.fndtn.abide', '#' + DIALOG_ID + 'Form');

    context.on('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
      Notifier.notifyError(Locale.tr("One or more required fields are missing or malformed."));
    }).on('valid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
      that.number_of_files = that.element['files'].length;
      that.template_created = false;
      that.images_information = [];

      $("input, button", context).attr("disabled", "disabled");
      $(".market_image_result:not(.success)",  context).html(
        ''+
          ''+
          ''+
        '');
      $(".market_template_result",  context).html(
        ''+
          ''+
          ''+
        '');

      var template_context = $("#market_import_file_template", context);

      $.each(that.element['files'], function(index, value){
        var local_context = $("#market_import_file_"+index,  context);

        if ($(".market_image_result:not(.success)", local_context).length > 0) {
          img_obj = {
            "image" : {
              "NAME": $("input.name",local_context).val(),
              "PATH": that.element['links']['download']['href']+'/'+index,
              "TYPE": value['type'],
              "MD5": value['md5'],
              "SHA1": value['sha1'],
              "DRIVER": value['driver'],
              "DEV_PREFIX": value['dev_prefix'],
              "FROM_APP": that.element['_id']["$oid"],
              "FROM_APP_NAME": that.element['name'],
              "FROM_APP_FILE": index
            },
            "ds_id" : $("#market_img_datastore select", context).val()
          };

          OpenNebulaImage.create({
            timeout: true,
            data: img_obj,
            success: function (file_index, file_context){
              return function(request, response) {
                $(".market_image_result", file_context).addClass("success").html(
                  ''+
                    ''+
                    ''+
                  '');

                $(".market_image_response", file_context).html(
                  '
'+
                  Locale.tr("Image created successfully")+' ID:'+response.IMAGE.ID+
                  '
');

                that.images_information[file_index] = response;

                that.try_to_create_template(context);
              };
            }(index, local_context),
            error: function (request, error_json){
              $(".market_template_result", template_context).html('');

              $(".market_image_result", local_context).html(
                ''+
                  ''+
                  ''+
                '');

              $(".market_image_response", local_context).html(
                '
'+
                (error_json.error.message || Locale.tr("Cannot contact server: is it running and reachable?"))+
                '
');

              $("input", template_context).removeAttr("disabled");
              $("input", local_context).removeAttr("disabled");
              $("button", context).removeAttr("disabled");
            }
          });
        }
      });

      that.try_to_create_template(context);

      return false;
    });

    return false;
  }

  function _onShow(context) {

    return false;
  }

  /**
   * @param {object} params
   *        - params.element : Marketplace appliance as returned by a .show call
   */
  function _setParams(params) {
    this.element = params.element;
  }

  function _try_to_create_template(context){
    var that = this;

    var template_context = $("#market_import_file_template",  context);

    var images_created = $(".market_image_result.success", context).length;

    if ((images_created == this.number_of_files) && !that.template_created) {
      that.template_created = true;

      if (that.element['opennebula_template'] && that.element['opennebula_template'] !== "CPU=1") {
        var vm_template;
        try {
          vm_template = JSON.parse( TemplateUtils.htmlDecode(that.element['opennebula_template']) );
        } catch (error) {
          $(".market_template_result", template_context).html(
            ''+
              ''+
              ''+
            '');

          $(".market_template_response", template_context).html(
            '
'+
            (error.message || Locale.tr("Cannot contact server: is it running and reachable?"))+
            '
');

          $("input", template_context).removeAttr("disabled");
          $("button", context).removeAttr("disabled");
          that.template_created = false;
          return;
        }

        if ($.isEmptyObject(vm_template.DISK)){
          vm_template.DISK = [];
        } else if (!$.isArray(vm_template.DISK)){
          vm_template.DISK = [vm_template.DISK];
        }

        vm_template.NAME = $("input", template_context).val();
        if (!vm_template.CPU){
          vm_template.CPU = "1";
        }
        if (!vm_template.MEMORY){
          vm_template.MEMORY = "1024";
        }

        $.each(that.images_information, function(image_index, image_info){
          if (!vm_template.DISK[image_index]) {
            vm_template.DISK[image_index] = {};
          }

          vm_template.DISK[image_index].IMAGE = image_info.IMAGE.NAME;
          vm_template.DISK[image_index].IMAGE_UNAME = image_info.IMAGE.UNAME;
        });

        vm_template.FROM_APP = that.element['_id']["$oid"];
        vm_template.FROM_APP_NAME = that.element['name'];

        OpenNebulaTemplate.create({
          timeout: true,
          data: {vmtemplate: vm_template},
          success: function (request, response){
            $(".market_template_result", template_context).addClass("success").html(
              ''+
                ''+
                ''+
              '');

            $(".market_template_response", template_context).html(
              '
'+
              Locale.tr("Template created successfully")+' ID:'+response.VMTEMPLATE.ID+
              '
');

            $("button", context).hide();
          },
          error: function (request, error_json){
            $(".market_template_result", template_context).html(
              ''+
                ''+
                ''+
              '');

            $(".market_template_response", template_context).html(
              '
'+
              (error_json.error.message || Locale.tr("Cannot contact server: is it running and reachable?"))+
              '
');

            $("input", template_context).removeAttr("disabled");
            $("button", context).removeAttr("disabled");
            that.template_created = false;
          }
        });
      } else {
        $("button", context).hide();
      }
    }
  }

});
<commit_msg>Use new ResourceSelect in import from<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var BaseDialog = require('utils/dialogs/dialog');
  var TemplateHTML = require('hbs!./import/html');
  var ContentHTML = require('hbs!./import/content');
  var Sunstone = require('sunstone');
  var Notifier = require('utils/notifier');
  var Locale = require('utils/locale');
  var ResourceSelect = require('utils/resource-select');
  var OpenNebulaDatastore = require('opennebula/datastore');
  var OpenNebulaImage = require('opennebula/image');
  var OpenNebulaTemplate = require('opennebula/template');
  var TemplateUtils = require('utils/template-utils');

  /*
    CONSTANTS
   */

  var DIALOG_ID = require('./import/dialogId');
  var TAB_ID = require('../tabId');

  /*
    CONSTRUCTOR
   */

  function Dialog() {
    this.dialogId = DIALOG_ID;

    BaseDialog.call(this);
  }

  Dialog.DIALOG_ID = DIALOG_ID;
  Dialog.prototype = Object.create(BaseDialog.prototype);
  Dialog.prototype.constructor = Dialog;
  Dialog.prototype.html = _html;
  Dialog.prototype.onShow = _onShow;
  Dialog.prototype.setup = _setup;
  Dialog.prototype.setParams = _setParams;
  Dialog.prototype.try_to_create_template = _try_to_create_template;

  return Dialog;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      'dialogId': this.dialogId
    });
  }

  function _setup(context) {
    var that = this;

    context.foundation('abide', 'reflow');
    $("#market_import_dialog_content", context).html(
      ContentHTML({'element': this.element})
    );

    ResourceSelect.insert({
        context: $('#market_img_datastore', context),
        resourceName: 'Datastore',
        filterKey: 'TYPE',
        filterValue: '' + OpenNebulaDatastore.TYPES.IMAGE_DS
      });

    context.off('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form');
    context.off('valid.fndtn.abide', '#' + DIALOG_ID + 'Form');

    context.on('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
      Notifier.notifyError(Locale.tr("One or more required fields are missing or malformed."));
    }).on('valid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
      that.number_of_files = that.element['files'].length;
      that.template_created = false;
      that.images_information = [];

      $("input, button", context).attr("disabled", "disabled");
      $(".market_image_result:not(.success)",  context).html(
        ''+
          ''+
          ''+
        '');
      $(".market_template_result",  context).html(
        ''+
          ''+
          ''+
        '');

      var template_context = $("#market_import_file_template", context);

      $.each(that.element['files'], function(index, value){
        var local_context = $("#market_import_file_"+index,  context);

        if ($(".market_image_result:not(.success)", local_context).length > 0) {
          img_obj = {
            "image" : {
              "NAME": $("input.name",local_context).val(),
              "PATH": that.element['links']['download']['href']+'/'+index,
              "TYPE": value['type'],
              "MD5": value['md5'],
              "SHA1": value['sha1'],
              "DRIVER": value['driver'],
              "DEV_PREFIX": value['dev_prefix'],
              "FROM_APP": that.element['_id']["$oid"],
              "FROM_APP_NAME": that.element['name'],
              "FROM_APP_FILE": index
            },
            "ds_id" : $("#market_img_datastore select", context).val()
          };

          OpenNebulaImage.create({
            timeout: true,
            data: img_obj,
            success: function (file_index, file_context){
              return function(request, response) {
                $(".market_image_result", file_context).addClass("success").html(
                  ''+
                    ''+
                    ''+
                  '');

                $(".market_image_response", file_context).html(
                  '
'+
                  Locale.tr("Image created successfully")+' ID:'+response.IMAGE.ID+
                  '
');

                that.images_information[file_index] = response;

                that.try_to_create_template(context);
              };
            }(index, local_context),
            error: function (request, error_json){
              $(".market_template_result", template_context).html('');

              $(".market_image_result", local_context).html(
                ''+
                  ''+
                  ''+
                '');

              $(".market_image_response", local_context).html(
                '
'+
                (error_json.error.message || Locale.tr("Cannot contact server: is it running and reachable?"))+
                '
');

              $("input", template_context).removeAttr("disabled");
              $("input", local_context).removeAttr("disabled");
              $("button", context).removeAttr("disabled");
            }
          });
        }
      });

      that.try_to_create_template(context);

      return false;
    });

    return false;
  }

  function _onShow(context) {

    return false;
  }

  /**
   * @param {object} params
   *        - params.element : Marketplace appliance as returned by a .show call
   */
  function _setParams(params) {
    this.element = params.element;
  }

  function _try_to_create_template(context){
    var that = this;

    var template_context = $("#market_import_file_template",  context);

    var images_created = $(".market_image_result.success", context).length;

    if ((images_created == this.number_of_files) && !that.template_created) {
      that.template_created = true;

      if (that.element['opennebula_template'] && that.element['opennebula_template'] !== "CPU=1") {
        var vm_template;
        try {
          vm_template = JSON.parse( TemplateUtils.htmlDecode(that.element['opennebula_template']) );
        } catch (error) {
          $(".market_template_result", template_context).html(
            ''+
              ''+
              ''+
            '');

          $(".market_template_response", template_context).html(
            '
'+
            (error.message || Locale.tr("Cannot contact server: is it running and reachable?"))+
            '
');

          $("input", template_context).removeAttr("disabled");
          $("button", context).removeAttr("disabled");
          that.template_created = false;
          return;
        }

        if ($.isEmptyObject(vm_template.DISK)){
          vm_template.DISK = [];
        } else if (!$.isArray(vm_template.DISK)){
          vm_template.DISK = [vm_template.DISK];
        }

        vm_template.NAME = $("input", template_context).val();
        if (!vm_template.CPU){
          vm_template.CPU = "1";
        }
        if (!vm_template.MEMORY){
          vm_template.MEMORY = "1024";
        }

        $.each(that.images_information, function(image_index, image_info){
          if (!vm_template.DISK[image_index]) {
            vm_template.DISK[image_index] = {};
          }

          vm_template.DISK[image_index].IMAGE = image_info.IMAGE.NAME;
          vm_template.DISK[image_index].IMAGE_UNAME = image_info.IMAGE.UNAME;
        });

        vm_template.FROM_APP = that.element['_id']["$oid"];
        vm_template.FROM_APP_NAME = that.element['name'];

        OpenNebulaTemplate.create({
          timeout: true,
          data: {vmtemplate: vm_template},
          success: function (request, response){
            $(".market_template_result", template_context).addClass("success").html(
              ''+
                ''+
                ''+
              '');

            $(".market_template_response", template_context).html(
              '
'+
              Locale.tr("Template created successfully")+' ID:'+response.VMTEMPLATE.ID+
              '
');

            $("button", context).hide();
          },
          error: function (request, error_json){
            $(".market_template_result", template_context).html(
              ''+
                ''+
                ''+
              '');

            $(".market_template_response", template_context).html(
              '
'+
              (error_json.error.message || Locale.tr("Cannot contact server: is it running and reachable?"))+
              '
');

            $("input", template_context).removeAttr("disabled");
            $("button", context).removeAttr("disabled");
            that.template_created = false;
          }
        });
      } else {
        $("button", context).hide();
      }
    }
  }

});
<|endoftext|>