<commit_before>var Plotly = require('@lib/index');
var Plots = require('@src/plots/plots');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');

describe('Test Plots', function() {
    'use strict';

    describe('Plots.supplyDefaults', function() {

        var gd;

        it('should relink private keys', function() {
            var oldFullData = [{
                type: 'scatter3d',
                z: [1, 2, 3]
            }, {
                type: 'contour',
                _empties: [1, 2, 3]
            }];

            var oldFullLayout = {
                _plots: { xy: {} },
                xaxis: { c2p: function() {} },
                yaxis: { _m: 20 },
                scene: { _scene: {} },
                annotations: [{ _min: 10, }, { _max: 20 }],
                someFunc: function() {}
            };

            var newData = [{
                type: 'scatter3d',
                z: [1, 2, 3, 4]
            }, {
                type: 'contour',
                z: [[1, 2, 3], [2, 3, 4]]
            }];

            var newLayout = {
                annotations: [{}, {}, {}]
            };

            gd = {
                _fullData: oldFullData,
                _fullLayout: oldFullLayout,
                data: newData,
                layout: newLayout
            };

            Plots.supplyDefaults(gd);

            expect(gd._fullData[0].z).toBe(newData[0].z);
            expect(gd._fullData[1].z).toBe(newData[1].z);
            expect(gd._fullData[1]._empties).toBe(oldFullData[1]._empties);
            expect(gd._fullLayout.scene._scene).toBe(oldFullLayout.scene._scene);
            expect(gd._fullLayout._plots).toBe(oldFullLayout._plots);
            expect(gd._fullLayout.annotations[0]._min).toBe(oldFullLayout.annotations[0]._min);
            expect(gd._fullLayout.annotations[1]._max).toBe(oldFullLayout.annotations[1]._max);
            expect(gd._fullLayout.someFunc).toBe(oldFullLayout.someFunc);

            expect(gd._fullLayout.xaxis.c2p)
                .not.toBe(oldFullLayout.xaxis.c2p, '(set during ax.setScale');
            expect(gd._fullLayout.yaxis._m)
                .not.toBe(oldFullLayout.yaxis._m, '(set during ax.setScale');
        });
    });

    describe('Plots.supplyLayoutGlobalDefaults should', function() {
        var layoutIn,
            layoutOut,
            expected;

        var supplyLayoutDefaults = Plots.supplyLayoutGlobalDefaults;

        beforeEach(function() {
            layoutOut = {};
        });

        it('should sanitize margins when they are wider than the plot', function() {
            layoutIn = {
                width: 500,
                height: 500,
                margin: {
                    l: 400,
                    r: 200
                }
            };
            expected = {
                l: 332,
                r: 166,
                t: 100,
                b: 80,
                pad: 0,
                autoexpand: true
            };

            supplyLayoutDefaults(layoutIn, layoutOut);
            expect(layoutOut.margin).toEqual(expected);
        });

        it('should sanitize margins when they are taller than the plot', function() {
            layoutIn = {
                width: 500,
                height: 500,
                margin: {
                    l: 400,
                    r: 200,
                    t: 300,
                    b: 500
                }
            };
            expected = {
                l: 332,
                r: 166,
                t: 187,
                b: 311,
                pad: 0,
                autoexpand: true
            };

            supplyLayoutDefaults(layoutIn, layoutOut);
            expect(layoutOut.margin).toEqual(expected);
        });

    });

    describe('Plots.supplyTraceDefaults', function() {
        var supplyTraceDefaults = Plots.supplyTraceDefaults,
            layout = {};

        var traceIn, traceOut;

        describe('should coerce hoverinfo', function() {
            it('without *name* for single-trace graphs by default', function() {
                layout._dataLength = 1;

                traceIn = {};
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('x+y+z+text');

                traceIn = { hoverinfo: 'name' };
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('name');
            });

            it('without *name* for single-trace graphs by default', function() {
                layout._dataLength = 2;

                traceIn = {};
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('all');

                traceIn = { hoverinfo: 'name' };
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('name');
            });
        });
    });

    describe('Plots.getSubplotIds', function() {
        var getSubplotIds = Plots.getSubplotIds;

        it('returns scene ids in order', function() {
            var layout = {
                scene2: {},
                scene: {},
                scene3: {}
            };

            expect(getSubplotIds(layout, 'gl3d'))
                .toEqual(['scene', 'scene2', 'scene3']);

            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'geo'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'no-valid-subplot-type'))
                .toEqual([]);
        });

        it('returns geo ids in order', function() {
            var layout = {
                geo2: {},
                geo: {},
                geo3: {}
            };

            expect(getSubplotIds(layout, 'geo'))
                .toEqual(['geo', 'geo2', 'geo3']);

            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'gl3d'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'no-valid-subplot-type'))
                .toEqual([]);
        });

        it('returns cartesian ids', function() {
            var layout = {
                _has: Plots._hasPlotType,
                _plots: { xy: {}, x2y2: {} }
            };

            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);

            layout._basePlotModules = [{ name: 'cartesian' }];
            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual(['xy', 'x2y2']);
            expect(getSubplotIds(layout, 'gl2d'))
                .toEqual([]);

            layout._basePlotModules = [{ name: 'gl2d' }];
            expect(getSubplotIds(layout, 'gl2d'))
                .toEqual(['xy', 'x2y2']);
            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);

        });
    });

    describe('Plots.findSubplotIds', function() {
        var findSubplotIds = Plots.findSubplotIds;
        var ids;

        it('should return subplots ids found in the data', function() {
            var data = [{
                type: 'scatter3d',
                scene: 'scene'
            }, {
                type: 'surface',
                scene: 'scene2'
            }, {
                type: 'choropleth',
                geo: 'geo'
            }];

            ids = findSubplotIds(data, 'geo');
            expect(ids).toEqual(['geo']);

            ids = findSubplotIds(data, 'gl3d');
            expect(ids).toEqual(['scene', 'scene2']);
        });
    });

    describe('Plots.resize', function() {
        var gd;

        beforeEach(function(done) {
            gd = createGraphDiv();

            Plotly.plot(gd, [{ x: [1, 2, 3], y: [2, 3, 4] }], {})
                .then(function() {
                    gd.style.width = '400px';
                    gd.style.height = '400px';

                    return Plotly.Plots.resize(gd);
                })
                .then(done);
        });

        afterEach(destroyGraphDiv);

        it('should resize the plot clip', function() {
            var uid = gd._fullLayout._uid;

            var plotClip = document.getElementById('clip' + uid + 'xyplot'),
                clipRect = plotClip.children[0],
                clipWidth = +clipRect.getAttribute('width'),
                clipHeight = +clipRect.getAttribute('height');

            expect(clipWidth).toBe(240);
            expect(clipHeight).toBe(220);
        });

        it('should resize the main svgs', function() {
            var mainSvgs = document.getElementsByClassName('main-svg');

            for(var i = 0; i < mainSvgs.length; i++) {
                var svg = mainSvgs[i],
                    svgWidth = +svg.getAttribute('width'),
                    svgHeight = +svg.getAttribute('height');

                expect(svgWidth).toBe(400);
                expect(svgHeight).toBe(400);
            }
        });
    });

    describe('Plots.purge', function() {
        var gd;

        beforeEach(function(done) {
            gd = createGraphDiv();
            Plotly.plot(gd, [{ x: [1, 2, 3], y: [2, 3, 4] }], {}).then(done);
        });

        afterEach(destroyGraphDiv);

        it('should unset everything in the gd except _context', function() {
            var expectedKeys = [
                '_ev', 'on', 'once', 'removeListener', 'removeAllListeners',
                'emit', '_context', '_replotPending', '_mouseDownTime',
                '_hmpixcount', '_hmlumcount'
            ];

            Plots.purge(gd);
            expect(Object.keys(gd)).toEqual(expectedKeys);
            expect(gd.data).toBeUndefined();
            expect(gd.layout).toBeUndefined();
            expect(gd._fullData).toBeUndefined();
            expect(gd._fullLayout).toBeUndefined();
            expect(gd.calcdata).toBeUndefined();
            expect(gd.framework).toBeUndefined();
            expect(gd.empty).toBeUndefined();
            expect(gd.fid).toBeUndefined();
            expect(gd.undoqueue).toBeUndefined();
            expect(gd.undonum).toBeUndefined();
            expect(gd.autoplay).toBeUndefined();
            expect(gd.changed).toBeUndefined();
            expect(gd._tester).toBeUndefined();
            expect(gd._testref).toBeUndefined();
            expect(gd._promises).toBeUndefined();
            expect(gd._redrawTimer).toBeUndefined();
            expect(gd._replotting).toBeUndefined();
            expect(gd.firstscatter).toBeUndefined();
            expect(gd.hmlumcount).toBeUndefined();
            expect(gd.hmpixcount).toBeUndefined();
            expect(gd.numboxes).toBeUndefined();
            expect(gd._hoverTimer).toBeUndefined();
            expect(gd._lastHoverTime).toBeUndefined();
        });
    });
});
<commit_msg>Add a couple more purge tests<commit_after>var Plotly = require('@lib/index');
var Plots = require('@src/plots/plots');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');

describe('Test Plots', function() {
    'use strict';

    describe('Plots.supplyDefaults', function() {

        var gd;

        it('should relink private keys', function() {
            var oldFullData = [{
                type: 'scatter3d',
                z: [1, 2, 3]
            }, {
                type: 'contour',
                _empties: [1, 2, 3]
            }];

            var oldFullLayout = {
                _plots: { xy: {} },
                xaxis: { c2p: function() {} },
                yaxis: { _m: 20 },
                scene: { _scene: {} },
                annotations: [{ _min: 10, }, { _max: 20 }],
                someFunc: function() {}
            };

            var newData = [{
                type: 'scatter3d',
                z: [1, 2, 3, 4]
            }, {
                type: 'contour',
                z: [[1, 2, 3], [2, 3, 4]]
            }];

            var newLayout = {
                annotations: [{}, {}, {}]
            };

            gd = {
                _fullData: oldFullData,
                _fullLayout: oldFullLayout,
                data: newData,
                layout: newLayout
            };

            Plots.supplyDefaults(gd);

            expect(gd._fullData[0].z).toBe(newData[0].z);
            expect(gd._fullData[1].z).toBe(newData[1].z);
            expect(gd._fullData[1]._empties).toBe(oldFullData[1]._empties);
            expect(gd._fullLayout.scene._scene).toBe(oldFullLayout.scene._scene);
            expect(gd._fullLayout._plots).toBe(oldFullLayout._plots);
            expect(gd._fullLayout.annotations[0]._min).toBe(oldFullLayout.annotations[0]._min);
            expect(gd._fullLayout.annotations[1]._max).toBe(oldFullLayout.annotations[1]._max);
            expect(gd._fullLayout.someFunc).toBe(oldFullLayout.someFunc);

            expect(gd._fullLayout.xaxis.c2p)
                .not.toBe(oldFullLayout.xaxis.c2p, '(set during ax.setScale');
            expect(gd._fullLayout.yaxis._m)
                .not.toBe(oldFullLayout.yaxis._m, '(set during ax.setScale');
        });
    });

    describe('Plots.supplyLayoutGlobalDefaults should', function() {
        var layoutIn,
            layoutOut,
            expected;

        var supplyLayoutDefaults = Plots.supplyLayoutGlobalDefaults;

        beforeEach(function() {
            layoutOut = {};
        });

        it('should sanitize margins when they are wider than the plot', function() {
            layoutIn = {
                width: 500,
                height: 500,
                margin: {
                    l: 400,
                    r: 200
                }
            };
            expected = {
                l: 332,
                r: 166,
                t: 100,
                b: 80,
                pad: 0,
                autoexpand: true
            };

            supplyLayoutDefaults(layoutIn, layoutOut);
            expect(layoutOut.margin).toEqual(expected);
        });

        it('should sanitize margins when they are taller than the plot', function() {
            layoutIn = {
                width: 500,
                height: 500,
                margin: {
                    l: 400,
                    r: 200,
                    t: 300,
                    b: 500
                }
            };
            expected = {
                l: 332,
                r: 166,
                t: 187,
                b: 311,
                pad: 0,
                autoexpand: true
            };

            supplyLayoutDefaults(layoutIn, layoutOut);
            expect(layoutOut.margin).toEqual(expected);
        });

    });

    describe('Plots.supplyTraceDefaults', function() {
        var supplyTraceDefaults = Plots.supplyTraceDefaults,
            layout = {};

        var traceIn, traceOut;

        describe('should coerce hoverinfo', function() {
            it('without *name* for single-trace graphs by default', function() {
                layout._dataLength = 1;

                traceIn = {};
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('x+y+z+text');

                traceIn = { hoverinfo: 'name' };
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('name');
            });

            it('without *name* for single-trace graphs by default', function() {
                layout._dataLength = 2;

                traceIn = {};
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('all');

                traceIn = { hoverinfo: 'name' };
                traceOut = supplyTraceDefaults(traceIn, 0, layout);
                expect(traceOut.hoverinfo).toEqual('name');
            });
        });
    });

    describe('Plots.getSubplotIds', function() {
        var getSubplotIds = Plots.getSubplotIds;

        it('returns scene ids in order', function() {
            var layout = {
                scene2: {},
                scene: {},
                scene3: {}
            };

            expect(getSubplotIds(layout, 'gl3d'))
                .toEqual(['scene', 'scene2', 'scene3']);

            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'geo'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'no-valid-subplot-type'))
                .toEqual([]);
        });

        it('returns geo ids in order', function() {
            var layout = {
                geo2: {},
                geo: {},
                geo3: {}
            };

            expect(getSubplotIds(layout, 'geo'))
                .toEqual(['geo', 'geo2', 'geo3']);

            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'gl3d'))
                .toEqual([]);
            expect(getSubplotIds(layout, 'no-valid-subplot-type'))
                .toEqual([]);
        });

        it('returns cartesian ids', function() {
            var layout = {
                _has: Plots._hasPlotType,
                _plots: { xy: {}, x2y2: {} }
            };

            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);

            layout._basePlotModules = [{ name: 'cartesian' }];
            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual(['xy', 'x2y2']);
            expect(getSubplotIds(layout, 'gl2d'))
                .toEqual([]);

            layout._basePlotModules = [{ name: 'gl2d' }];
            expect(getSubplotIds(layout, 'gl2d'))
                .toEqual(['xy', 'x2y2']);
            expect(getSubplotIds(layout, 'cartesian'))
                .toEqual([]);

        });
    });

    describe('Plots.findSubplotIds', function() {
        var findSubplotIds = Plots.findSubplotIds;
        var ids;

        it('should return subplots ids found in the data', function() {
            var data = [{
                type: 'scatter3d',
                scene: 'scene'
            }, {
                type: 'surface',
                scene: 'scene2'
            }, {
                type: 'choropleth',
                geo: 'geo'
            }];

            ids = findSubplotIds(data, 'geo');
            expect(ids).toEqual(['geo']);

            ids = findSubplotIds(data, 'gl3d');
            expect(ids).toEqual(['scene', 'scene2']);
        });
    });

    describe('Plots.resize', function() {
        var gd;

        beforeEach(function(done) {
            gd = createGraphDiv();

            Plotly.plot(gd, [{ x: [1, 2, 3], y: [2, 3, 4] }], {})
                .then(function() {
                    gd.style.width = '400px';
                    gd.style.height = '400px';

                    return Plotly.Plots.resize(gd);
                })
                .then(done);
        });

        afterEach(destroyGraphDiv);

        it('should resize the plot clip', function() {
            var uid = gd._fullLayout._uid;

            var plotClip = document.getElementById('clip' + uid + 'xyplot'),
                clipRect = plotClip.children[0],
                clipWidth = +clipRect.getAttribute('width'),
                clipHeight = +clipRect.getAttribute('height');

            expect(clipWidth).toBe(240);
            expect(clipHeight).toBe(220);
        });

        it('should resize the main svgs', function() {
            var mainSvgs = document.getElementsByClassName('main-svg');

            for(var i = 0; i < mainSvgs.length; i++) {
                var svg = mainSvgs[i],
                    svgWidth = +svg.getAttribute('width'),
                    svgHeight = +svg.getAttribute('height');

                expect(svgWidth).toBe(400);
                expect(svgHeight).toBe(400);
            }
        });
    });

    describe('Plots.purge', function() {
        var gd;

        beforeEach(function(done) {
            gd = createGraphDiv();
            Plotly.plot(gd, [{ x: [1, 2, 3], y: [2, 3, 4] }], {}).then(done);
        });

        afterEach(destroyGraphDiv);

        it('should unset everything in the gd except _context', function() {
            var expectedKeys = [
                '_ev', 'on', 'once', 'removeListener', 'removeAllListeners',
                'emit', '_context', '_replotPending', '_mouseDownTime',
                '_hmpixcount', '_hmlumcount'
            ];

            Plots.purge(gd);
            expect(Object.keys(gd)).toEqual(expectedKeys);
            expect(gd.data).toBeUndefined();
            expect(gd.layout).toBeUndefined();
            expect(gd._fullData).toBeUndefined();
            expect(gd._fullLayout).toBeUndefined();
            expect(gd.calcdata).toBeUndefined();
            expect(gd.framework).toBeUndefined();
            expect(gd.empty).toBeUndefined();
            expect(gd.fid).toBeUndefined();
            expect(gd.undoqueue).toBeUndefined();
            expect(gd.undonum).toBeUndefined();
            expect(gd.autoplay).toBeUndefined();
            expect(gd.changed).toBeUndefined();
            expect(gd._tester).toBeUndefined();
            expect(gd._testref).toBeUndefined();
            expect(gd._promises).toBeUndefined();
            expect(gd._redrawTimer).toBeUndefined();
            expect(gd._replotting).toBeUndefined();
            expect(gd.firstscatter).toBeUndefined();
            expect(gd.hmlumcount).toBeUndefined();
            expect(gd.hmpixcount).toBeUndefined();
            expect(gd.numboxes).toBeUndefined();
            expect(gd._hoverTimer).toBeUndefined();
            expect(gd._lastHoverTime).toBeUndefined();
            expect(gd._transitionData).toBeUndefined();
            expect(gd._transitioning).toBeUndefined();
        });
    });
});
<|endoftext|>


<commit_before>/* globals expect: true, describe: true, it: true */
/* eslint no-unused-expressions: 0 */
const { isBlank } = require('../../src/lib/controllerutils')

describe('isBlank', function () {
  it('should detects undefined variables', function () {
    let e
    expect(isBlank(e)).to.be.true
  })
  it('should detect passing an unknown key', function () {
    let e = {}
    expect(isBlank(e.x)).to.be.true
  })
  it('should detect an empty string', function () {
    expect(isBlank('')).to.be.true
  })
  it('should detect undefined', function () {
    expect(isBlank(undefined)).to.be.true
  })
  it('should know when it is sent a valid string', function () {
    expect(isBlank('test')).to.be.false
  })
  it('should know when it is sent a valid object', function () {
    expect(isBlank({x: 1})).to.be.false
  })
})
<commit_msg>v2 error testing part 1<commit_after>/* globals expect: true, describe: true, it: true */
/* eslint no-unused-expressions: 0 */
const { isBlank, transformV2Errors } = require('../../src/lib/controllerutils')

describe('isBlank', function () {
  it('should detects undefined variables', function () {
    let e
    expect(isBlank(e)).to.be.true
  })
  it('should detect passing an unknown key', function () {
    let e = {}
    expect(isBlank(e.x)).to.be.true
  })
  it('should detect an empty string', function () {
    expect(isBlank('')).to.be.true
  })
  it('should detect undefined', function () {
    expect(isBlank(undefined)).to.be.true
  })
  it('should know when it is sent a valid string', function () {
    expect(isBlank('test')).to.be.false
  })
  it('should know when it is sent a valid object', function () {
    expect(isBlank({x: 1})).to.be.false
  })
})

describe('transformV2Errors: Formatting V2 service delivery endpoint errors', function () {
  it('Should warn if the Service Delivery triple does not exist', function () {
    const source = [
      {
        'detail': 'This combination of service and service provider does not exist.',
        'source': {
          'pointer': '/data/relationships/service'
        }
      }
    ]
    const actual = transformV2Errors(source)
    expect(actual.Alert).to.exist
    expect(actual.Alert).to.equal('This combination of service and service provider does not exist.')
  })
})
<|endoftext|>


<commit_before>

THREE.ObjectSelection = function(parameters) {
  var parameters = parameters || {};

  var mouse = { x: 0, y: 0 };
  this.projector = new THREE.Projector;
  this.INTERSECTED;

  var callbackSelected = parameters.selected;

  document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  function onDocumentMouseMove( event ) {
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  }

  this.render = function(scene, camera) {
    // find intersections
    camera.update();

    var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
    this.projector.unprojectVector( vector, camera );

    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );

    var intersects = ray.intersectScene( scene );
    if( intersects.length > 0 ) {
      if ( this.INTERSECTED != intersects[ 0 ].object ) {
        if ( this.INTERSECTED ) {
          this.INTERSECTED.materials[ 0 ].color.setHex( this.INTERSECTED.currentHex );
        }

        this.INTERSECTED = intersects[ 0 ].object;
        this.INTERSECTED.currentHex = this.INTERSECTED.materials[ 0 ].color.getHex();
        this.INTERSECTED.materials[ 0 ].color.setHex( 0xff0000 );
        callbackSelected(this.INTERSECTED);
      }
    } else {
      if ( this.INTERSECTED ) {
        this.INTERSECTED.materials[ 0 ].color.setHex( this.INTERSECTED.currentHex );
      }
      this.INTERSECTED = null;
      callbackSelected(this.INTERSECTED);
    }
  }
}

<commit_msg>Added domElement for events.<commit_after>

THREE.ObjectSelection = function(parameters) {
  var parameters = parameters || {};

  this.domElement = parameters.domElement || document;
  this.projector = new THREE.Projector;
  this.INTERSECTED;

  var callbackSelected = parameters.selected;
  var mouse = { x: 0, y: 0 };

  this.domElement.addEventListener( 'mousemove', onDocumentMouseMove, false );
  function onDocumentMouseMove( event ) {
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  }

  this.render = function(scene, camera) {
    // find intersections
    camera.update();

    var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
    this.projector.unprojectVector( vector, camera );

    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );

    var intersects = ray.intersectScene( scene );
    if( intersects.length > 0 ) {
      if ( this.INTERSECTED != intersects[ 0 ].object ) {
        if ( this.INTERSECTED ) {
          this.INTERSECTED.materials[ 0 ].color.setHex( this.INTERSECTED.currentHex );
        }

        this.INTERSECTED = intersects[ 0 ].object;
        this.INTERSECTED.currentHex = this.INTERSECTED.materials[ 0 ].color.getHex();
        this.INTERSECTED.materials[ 0 ].color.setHex( 0xff0000 );
        callbackSelected(this.INTERSECTED);
      }
    } else {
      if ( this.INTERSECTED ) {
        this.INTERSECTED.materials[ 0 ].color.setHex( this.INTERSECTED.currentHex );
      }
      this.INTERSECTED = null;
      callbackSelected(this.INTERSECTED);
    }
  }
}

<|endoftext|>


<commit_before>// steps:
// - get application template
// - create admin user if not exists
// - install application in admin user
var args = process.argv.slice(2);
gitPath = args[0];

if (!gitPath) {
    return console.log(
        'No git path!\n' +
        'Please specify a git path as first parameter.\n' +
        'example: node install_app.js https://github.com/jillix/admin.git'

    );
}

// 1. create/get user
// 2. clone and install admin app

return;

var EventEmitter = require('events').EventEmitter;
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var MongoServer = mongo.Server;

var newApp = require('./application.json');

if (!newApp.application || !newApp.application.uid || !newApp.application.domains || !newApp.application.name) {
    return;
}

// TODO install mono dev under admin user, which has access to the mono database
// TODO one apy key per user, not per application to share databases

// TODO this is only temporary, until the database api is implemented
var appId = mongo.ObjectID('52a357298eb3ce0b18000001');

var mongoClient = new MongoClient(new MongoServer('localhost', 27017));
mongoClient.open(function(err, mongoClient) {

    // simulate API
    var API = new EventEmitter();
    API.db = {
        mono: mongoClient.db('mono'),
        // TODO this should be created with the database api
        app: mongoClient.db('app_' + appId)
    };

    // clear data
    API.db.mono.collection('m_applications').remove({_id: appId}, function () {
        API.db.app.dropDatabase(function () {

            // test creating a new app
            create.call(API, newApp.application.name, newApp.application.domains, function (err) {
                mongoClient.close();
            });
        });
    });
});

function insertToDb (db, collection, data, event) {
    var self = this;

    if (self.error) {
        return;
    }

    // insert public role
    self.db[db].collection(collection).insert(data, function (err) {
        if (err) {
            return self.emit('app.create_error', err);
        }

        if (event) {
            self.emit('app.create_' + event);
        }
    });
}

function create (name, domains, callback) {
    var self = this;

    // TODO check if domain exists

    // collect mongodb ids for rollback
    var rollBack = []; // collection.remove({$in: rollBack});

    // copy newApp
    var template = JSON.parse(JSON.stringify(newApp));

    // add name to application
    template.application.name = name;

    // add domains to application
    template.application.domains = domains;

    // get a mongodb id for the application
    template.application._id = appId;
    rollBack.push(template.application._id);

    // create public role
    var publicRoleId = mongo.ObjectID();
    rollBack.push(publicRoleId);

    if (!template.roles) {
        template.roles = [];
    }
    template.roles.push({
        _id: publicRoleId,
        name: 'public'
    });

    // add public role to session config
    template.application.process.session.publicRole = publicRoleId;

    // get and set ids for modules
    var modules = {};
    for (var mi = 0, ml = template.modules.length; mi < ml; ++mi) {
        template.modules[mi]._id = modules[template.modules[mi]._id] = mongo.ObjectID();
        rollBack.push(template.modules[mi]._id);

        // add public role to modules
        template.modules[mi].roles = [publicRoleId];
    }

    // add module and role ids to module instances
    var instances = {};
    for (var ii = 0, il = template.instances.length; ii < il; ++ii) {
        if (modules[template.instances[ii].module]) {
            template.instances[ii].module = modules[template.instances[ii].module];
        } else {
            throw new Error('Module for instance not found: ' + template.instances[ii].module);
        }

        // create ids for instances
        template.instances[ii]._id = mongo.ObjectID();
        rollBack.push(template.instances[ii]._id);

        // add public role to instances
        template.instances[ii].roles = [publicRoleId];
    }

    // convert object id and add public role to views
    for (var vi = 0, vl = template.views.length; vi < vl; ++vi) {
        template.views[vi]._id = mongo.ObjectID(template.views[vi]._id);
        template.views[vi].roles = [publicRoleId];
    }

    // convert object id and add public role to models
    for (var dm = 0, dl = template.models.length; dm < dl; ++dm) {
        template.models[dm]._id = mongo.ObjectID(template.models[dm]._id);

        if (template.models[dm].schema) {
            template.models[dm].schema = mongo.ObjectID(template.models[dm].schema);
        }

        template.models[dm].roles = [publicRoleId];
    }

    // convert object id and add public role to schemas
    for (var si = 0, sl = template.schemas.length; si < sl; ++si) {
        template.schemas[si]._id = mongo.ObjectID(template.schemas[si]._id);
        template.schemas[si].roles = [publicRoleId];
    }

    // TODO create a user and get uid (API)
    // TODO give app user read rights in lib/application and lib/client
    template.application.uid = 1000;
    template.application.gid = 1000;
    template.application.process.user = 'app_' + template.application._id;

    // TODO create apiKey (or set an existing one?) (API)
    template.application.process.apiKey = '1234';

    // TODO get mongodb connection string (API)
    // - create mongodb database
    // - create mongodb user
    // - add mongodb user to the created database
    if (!template.application.process.databases) {
        template.application.process.databases = {};
    }
    template.application.process.databases.app = 'mongodb://localhost:27017/' + template.application.process.user;

    // create application folder
    // copy instance files in public folder (html, css, js, images, ..)
    // TODO set rights (wait with this step until spawner uses uid/giu)

    // TODO template ids (set ids when the templates are known)

    // TODO insert data in db
    var eventPrefix = 'app.create_';
    self.on(eventPrefix + 'mongoDbUser', function () {
        insertToDb.call(self, 'app', 'm_roles', template.roles, 'rolesInDb');
    });
    self.on(eventPrefix + 'rolesInDb', function () {
        insertToDb.call(self, 'mono', 'm_applications', template.application, 'applicationInDb');
    });
    self.on(eventPrefix + 'applicationInDb', function () {
        insertToDb.call(self, 'app', 'm_modules', template.modules, 'modulesInDb');
    });
    self.on(eventPrefix + 'modulesInDb', function () {
        insertToDb.call(self, 'app', 'm_instances', template.instances, 'instancesInDb');
    });
    self.on(eventPrefix + 'instancesInDb', function () {
        insertToDb.call(self, 'app', 'm_views', template.views, 'viewsInDb');
    });
    self.on(eventPrefix + 'viewsInDb', function () {
        insertToDb.call(self, 'app', 'm_models', template.models, 'modelsInDb');
    });
    self.on(eventPrefix + 'modelsInDb', function () {
        insertToDb.call(self, 'app', 'm_schemas', template.schemas, 'schemasInDb');
    });
    self.on(eventPrefix + 'schemasInDb', function () {

        // all saved
        mongoClient.close();
        callback(null);
    });

    self.on('app.create_error', function (err) {
        self.error = true;

        // TODO roll back
        console.log(err, rollBack);
        mongoClient.close();
    });

    // TODO this has to be done with the API
    // insert mongodb user
    self.db.app.addUser(
        template.application.process.user,
        template.application.process.apiKey,
        {"roles" : ["readWrite"]},
        function (err) {
            if (err) {
                return self.emit(eventPrefix + 'error', err);
            }

            self.emit(eventPrefix + 'mongoDbUser');
        }
    );

    // TODO install modules (API)
}

exports.create = create;
<commit_msg>start using the admin api to create user and install admin app<commit_after>var fs = require('fs');
var path = require('path');

var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var MongoServer = mongo.Server;
var mongoClient = new MongoClient(new MongoServer('localhost', 27017));

var root = path.normalize(__dirname + '/../');
var appCache = root + '/cache/apps/';
var appName = 'admin';
var repo = 'https://github.com/jillix/admin.git';
var userName = 'admin@jillix.com';
var userPwd = '1234';
var systemDb = 'mono';

// TODO set unique index on mono/m_users.name

// check if application repo exists
if (!fs.existsSync(appCache + appName)) {
    return console.log(
        'No admin app "' + appName + '" found!\n' +
        'Please clone your admin app to mono/cache/apps/.\n' +
        'example: git clone git@github.com:jillix/admin.git'
    );
}

// get the mono database
getDatabases(function (err, dbs) {

    if (err) {
        return finish(err);
    }

    // mimic process.mono
    process.mono = {
        db: dbs,
        paths: {MONO_ROOT: root}
    };

    // get api
    var API = require(appCache + appName + '/api');
    API(function (err, api) {

        // create/get user
        api.user.get(userName, function (err, user) {

            if (err) {
                return finish(err);
            }

            // reset admin app if admin user exists
            if (user) {
                return api.app.resetDev(user, repo, function (err, appId) {
                    finish(err, appId);
                });
            }

            // create new user
            api.user.create(userName, userPwd, function (err, user) {

                if (err) {
                    return finish(err);
                }

                finish(err, appId);

                // clone and install admin app
                api.app.cloneDev(user, repo, function (err, appId) {
                    finish(err, appId);
                });
            });
        });
    });
});

function finish (err, appId) {

    mongoClient.close();

    if (err) {
        return console.error(err);
    }

    console.log('Admin app "' + appId + '" succesfully installed.');
}

function getDatabases (callback) {
    mongoClient.open(function(err, mongoClient) {

        if (err) {
            callback(err);
        }

        callback(null, {
            mono: mongoClient.db(systemDb)
        });
    });
}

return;

var EventEmitter = require('events').EventEmitter;

var newApp = require('./application.json');

if (!newApp.application || !newApp.application.uid || !newApp.application.domains || !newApp.application.name) {
    return;
}

// TODO install mono dev under admin user, which has access to the mono database
// TODO one apy key per user, not per application to share databases

// TODO this is only temporary, until the database api is implemented
var appId = mongo.ObjectID('52a357298eb3ce0b18000001');

var mongoClient = new MongoClient(new MongoServer('localhost', 27017));
mongoClient.open(function(err, mongoClient) {

    // simulate API
    var API = new EventEmitter();
    API.db = {
        mono: mongoClient.db('mono'),
        // TODO this should be created with the database api
        app: mongoClient.db('app_' + appId)
    };

    // clear data
    API.db.mono.collection('m_applications').remove({_id: appId}, function () {
        API.db.app.dropDatabase(function () {

            // test creating a new app
            create.call(API, newApp.application.name, newApp.application.domains, function (err) {
                mongoClient.close();
            });
        });
    });
});

function insertToDb (db, collection, data, event) {
    var self = this;

    if (self.error) {
        return;
    }

    // insert public role
    self.db[db].collection(collection).insert(data, function (err) {
        if (err) {
            return self.emit('app.create_error', err);
        }

        if (event) {
            self.emit('app.create_' + event);
        }
    });
}

function create (name, domains, callback) {
    var self = this;

    // TODO check if domain exists

    // collect mongodb ids for rollback
    var rollBack = []; // collection.remove({$in: rollBack});

    // copy newApp
    var template = JSON.parse(JSON.stringify(newApp));

    // add name to application
    template.application.name = name;

    // add domains to application
    template.application.domains = domains;

    // get a mongodb id for the application
    template.application._id = appId;
    rollBack.push(template.application._id);

    // create public role
    var publicRoleId = mongo.ObjectID();
    rollBack.push(publicRoleId);

    if (!template.roles) {
        template.roles = [];
    }
    template.roles.push({
        _id: publicRoleId,
        name: 'public'
    });

    // add public role to session config
    template.application.process.session.publicRole = publicRoleId;

    // get and set ids for modules
    var modules = {};
    for (var mi = 0, ml = template.modules.length; mi < ml; ++mi) {
        template.modules[mi]._id = modules[template.modules[mi]._id] = mongo.ObjectID();
        rollBack.push(template.modules[mi]._id);

        // add public role to modules
        template.modules[mi].roles = [publicRoleId];
    }

    // add module and role ids to module instances
    var instances = {};
    for (var ii = 0, il = template.instances.length; ii < il; ++ii) {
        if (modules[template.instances[ii].module]) {
            template.instances[ii].module = modules[template.instances[ii].module];
        } else {
            throw new Error('Module for instance not found: ' + template.instances[ii].module);
        }

        // create ids for instances
        template.instances[ii]._id = mongo.ObjectID();
        rollBack.push(template.instances[ii]._id);

        // add public role to instances
        template.instances[ii].roles = [publicRoleId];
    }

    // convert object id and add public role to views
    for (var vi = 0, vl = template.views.length; vi < vl; ++vi) {
        template.views[vi]._id = mongo.ObjectID(template.views[vi]._id);
        template.views[vi].roles = [publicRoleId];
    }

    // convert object id and add public role to models
    for (var dm = 0, dl = template.models.length; dm < dl; ++dm) {
        template.models[dm]._id = mongo.ObjectID(template.models[dm]._id);

        if (template.models[dm].schema) {
            template.models[dm].schema = mongo.ObjectID(template.models[dm].schema);
        }

        template.models[dm].roles = [publicRoleId];
    }

    // convert object id and add public role to schemas
    for (var si = 0, sl = template.schemas.length; si < sl; ++si) {
        template.schemas[si]._id = mongo.ObjectID(template.schemas[si]._id);
        template.schemas[si].roles = [publicRoleId];
    }

    // TODO create a user and get uid (API)
    // TODO give app user read rights in lib/application and lib/client
    template.application.uid = 1000;
    template.application.gid = 1000;
    template.application.process.user = 'app_' + template.application._id;

    // TODO create apiKey (or set an existing one?) (API)
    template.application.process.apiKey = '1234';

    // TODO get mongodb connection string (API)
    // - create mongodb database
    // - create mongodb user
    // - add mongodb user to the created database
    if (!template.application.process.databases) {
        template.application.process.databases = {};
    }
    template.application.process.databases.app = 'mongodb://localhost:27017/' + template.application.process.user;

    // create application folder
    // copy instance files in public folder (html, css, js, images, ..)
    // TODO set rights (wait with this step until spawner uses uid/giu)

    // TODO template ids (set ids when the templates are known)

    // TODO insert data in db
    var eventPrefix = 'app.create_';
    self.on(eventPrefix + 'mongoDbUser', function () {
        insertToDb.call(self, 'app', 'm_roles', template.roles, 'rolesInDb');
    });
    self.on(eventPrefix + 'rolesInDb', function () {
        insertToDb.call(self, 'mono', 'm_applications', template.application, 'applicationInDb');
    });
    self.on(eventPrefix + 'applicationInDb', function () {
        insertToDb.call(self, 'app', 'm_modules', template.modules, 'modulesInDb');
    });
    self.on(eventPrefix + 'modulesInDb', function () {
        insertToDb.call(self, 'app', 'm_instances', template.instances, 'instancesInDb');
    });
    self.on(eventPrefix + 'instancesInDb', function () {
        insertToDb.call(self, 'app', 'm_views', template.views, 'viewsInDb');
    });
    self.on(eventPrefix + 'viewsInDb', function () {
        insertToDb.call(self, 'app', 'm_models', template.models, 'modelsInDb');
    });
    self.on(eventPrefix + 'modelsInDb', function () {
        insertToDb.call(self, 'app', 'm_schemas', template.schemas, 'schemasInDb');
    });
    self.on(eventPrefix + 'schemasInDb', function () {

        // all saved
        mongoClient.close();
        callback(null);
    });

    self.on('app.create_error', function (err) {
        self.error = true;

        // TODO roll back
        console.log(err, rollBack);
        mongoClient.close();
    });

    // TODO this has to be done with the API
    // insert mongodb user
    self.db.app.addUser(
        template.application.process.user,
        template.application.process.apiKey,
        {"roles" : ["readWrite"]},
        function (err) {
            if (err) {
                return self.emit(eventPrefix + 'error', err);
            }

            self.emit(eventPrefix + 'mongoDbUser');
        }
    );

    // TODO install modules (API)
}

exports.create = create;
<|endoftext|>


<commit_before>wwt.controllers.controller('LayerManagerController',
  ['$scope',
    'AppState',
    '$timeout',
    'Util',
    function ($scope, appState, $timeout, util) {
    var version = 12;

      function treeNode(args) {
        this.name = args.name;
        this.checked = getSticky(args.name, args.action,args.checked);
        this.children = args.children || [];
        this.action = args.action;
        this.collapsed = args.collapsed || false;
        this.disabled = false;
        if (args.mergeWith){
          //console.log({mergedFound:args})
          this.mergeWith = args.mergeWith;
        }
        if (args.v) this.v = args.v;
      }
      var getSticky = function (name, action, defaultState) {
        var sticky = appState.get('layerMgr_' + name + action)
        if (name && action && sticky !== undefined) {
          return sticky;
        } else if (defaultState !== undefined) {
          return defaultState;
        } else {
          return true;
        }
      }
      var setSticky = function (name, action, checked) {
        if (name && action) {
          appState.set('layerMgr_' + name + action, checked);
        }
      }
      var allMaps = {};
      var constellations = [];

      $scope.initLayerManager = function () {
        if (!wwtlib.Constellations.abbreviations) {
          setTimeout($scope.initLayerManager, 333);
          return;
        }
        $.each(wwtlib.Constellations.abbreviations, function (name, abbrev) {
          constellations.push(new treeNode({
            name: name
          }));
        });
        $scope.tree = initTree();//appState.get('layerManager');

    $scope.scrubber = {left:' ',right:' ',table:[0,1,2,3,4,5]};

        $timeout(function () {

          wwt.wc.add_timeScrubberHook(function(prop,val){
            switch (prop){
              case 'left':
              case 'right':
              case 'title':
                $scope.$applyAsync(function() {
                  $scope.scrubber[prop] = val;
                });
                break;
              default:
                var el =  $('.scrubber-slider');
                el.find('.btn').css('left', val * el.width());
                break;
            }
          });

          initTreeNode(0, $scope.tree);
          $timeout(function () {
            var w = $('.scrubber-slider').width();
            var bar = $('.scrubber-slider a.btn');
            var scrubberMover = new wwt.Move({
              el:bar,
              bounds: {
                x: [0, w],
                y: [0, 0]
              },
              onmove:function(){
                wwt.wc.setTimeScrubberPosition(this.css.left/w);
              }
            });

            allMaps = wwtlib.LayerManager.get_allMaps();
            var sunTree = {Sun: (allMaps.Sun)};

            sunTree.Sun.collapsed = false;
            $scope.skyNode = allMaps.Sky;
            //$scope.tree = skyNode;
            //console.log(skyNode);
            $.each(sunTree.Sun.childMaps, function (name, node) {
              node.collapsed = false;
              //node.name = name;
              $.each(node.childMaps, function (childName, child) {
                child.collapsed = true;
                //child.name = childName;
              });
            });
            $scope.sunTree = sunTree;

          }, 123);
        });
        wwt.resize();
      };
      $scope.getChildren = function(node){
        if (!node)return {};
        var children  = node.children || {};
        if (children.length){

          if (node.mergeWith){
            //console.log('mergeWith',node.mergeWith);
            allMaps = wwtlib.LayerManager.get_allMaps();
            if (allMaps && allMaps[node.mergeWith]) {
              //console.log(allMaps[node.mergeWith]);
              var addedChildren = $scope.getChildren(allMaps[node.mergeWith]);
              $.each(children, function (i, childNode) {
                addedChildren[childNode.name] = childNode;
              });
              return addedChildren;
            }
          }
          return children;
        }
        if (node.childMaps && Object.keys(node.childMaps).length){
          children = node.childMaps;
        }
        if (node.layers && node.layers.length){
          node.layers.forEach(function(l){
            children[l._name] = l;
          });
        }
          return children;
      };
      var initTree = function () {
        return new treeNode({
          v: version,
          name: $scope.getFromEn('Sky'),
          mergeWith: 'Sky',// key of node in wwtlib.LayerManager.get_allMaps() to merge into settings. Set this on any settings node
          action: 'showSkyNode',
          checked:true,
          children: [
            new treeNode({
              name: $scope.getFromEn('Overlays'),
              action: 'showSkyOverlays',
              children: [
                new treeNode({
                  name: $scope.getFromEn('Constellations'),
                  action: 'constellationsEnabled',
                  children: [
                    new treeNode({
                      name: $scope.getFromEn('Constellation Pictures'),
                      //children: picturesFilter,
                      action: 'showConstellationPictures',
                      checked: false
                    }), new treeNode({
                      name: $scope.getFromEn('Constellation Figures'),
                      //children: figuresFilter,
                      action: 'showConstellationFigures'
                    }), new treeNode({
                      name: $scope.getFromEn('Constellation Boundaries'),
                      collapsed: true,
                      children: [
                        new treeNode({name: $scope.getFromEn('Focused Only'), action: 'showConstellationSelection'})
                      ],
                      action: 'showConstellationBoundries'
                    }), new treeNode({
                      name: $scope.getFromEn('Constellation Names'),
                      checked: false,
                      action: 'showConstellationLabels'
                    })
                  ]
                }),
                new treeNode({
                  name: $scope.getFromEn('Grids'),
                  action: 'showSkyGrids',
                  children: [
                    new treeNode({
                      name: $scope.getFromEn('Equatorial Grid'),
                      checked: false,
                      collapsed: true,
                      action: 'showGrid',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showEquatorialGridText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('Galactic Grid'),
                      checked: false,
                      collapsed: true,
                      action: 'showGalacticGrid',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showGalacticGridText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('AltAz Grid'),
                      checked: false,
                      collapsed: true,
                      action: 'showAltAzGrid',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showAltAzGridText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('Ecliptic Grid'),
                      checked: false,
                      collapsed: true,
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showEclipticGridText'
                        })
                      ],
                      action: 'showEclipticGrid'
                    }), new treeNode({
                      name: $scope.getFromEn('Ecliptic Overview'),
                      checked: true,
                      collapsed: true,
                      action: 'showEcliptic',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Month Labels'),
                          checked: false,
                          action: 'showEclipticOverviewText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('Precession Chart'),
                      checked: false,
                      action: 'showPrecessionChart'
                    })
                  ]
                }), new treeNode({
                  name: $scope.getFromEn('Crosshairs'),
                  checked: true,
                  action: 'showCrosshairs'
                })
              ]
            }),
            new treeNode({
              name: $scope.getFromEn('2d Sky'),
              checked: true,
              action: 'showSkyNode',
              children: [
                new treeNode({
                  name: $scope.getFromEn('Show Solar System'),
                  checked: true,
                  action: 'showSolarSystem'
                }) /*,
						new treeNode({
							name: $scope.getFromEn('Field of View Indicators'),
							checked: true,
							action: 'showFieldOfView'
						})*/
              ]
            }),
            new treeNode({
              name: $scope.getFromEn('3d Solar System'),
              checked: true,
              action: 'showSolarSystem',
              children: [
                new treeNode({
                  name: $scope.getFromEn('Milky Way (Dr. R. Hurt)'),
                  checked: true,
                  action: 'solarSystemMilkyWay'
                }), new treeNode({
                  name: $scope.getFromEn('Stars (Hipparcos, ESA)'),
                  checked: true,
                  action: 'solarSystemStars'
                }), new treeNode({
                  name: $scope.getFromEn('Planets (NASA, ETAL)'),
                  checked: true,
                  action: 'solarSystemPlanets'
                }), new treeNode({
                  name: $scope.getFromEn('Planetary Orbits'),
                  checked: true,
                  action: 'solarSystemOrbits'
                }), new treeNode({
                  name: $scope.getFromEn('Moon & Satellite Orbits'),
                  checked: false,
                  action: 'solarSystemMinorOrbits'
                }), new treeNode({
                  name: $scope.getFromEn('Asteroids (IAU MPC)'),
                  checked: false,
                  action: 'solarSystemMinorPlanets'
                }), new treeNode({
                  name: $scope.getFromEn('Lighting and Shadows'),
                  checked: true,
                  action: 'solarSystemLighting'
                }), new treeNode({
                  name: $scope.getFromEn('Multi-Res Solar System Bodies'),
                  checked: true,
                  action: 'solarSystemMultiRes'
                })
              ]
            })
          ]
        });
      };

      $scope.showMenu = function (layerMap, event) {
        if ($scope.activeLayer) {
          $scope.activeLayer.active = false;
        }
        $scope.$applyAsync(function () {
          layerMap.active = true;
          $scope.activeLayer = layerMap;
        });

        //ensure selection is changed first.
        wwtlib.LayerManager.layerSelectionChanged(layerMap);

        //console.log('invoke context menu on node', event, layerMap);
        wwtlib.LayerManager.showLayerMenu(layerMap, event.pageX, event.pageY);
      }

      $scope.selectionChanged = function (layerMap, event) {
        if (event.currentTarget.tagName==='LABEL' && event.offsetX > 17){
          //console.log(event);
          event.preventDefault();
          event.stopImmediatePropagation();

          if ($scope.activeLayer) {
            $scope.activeLayer.active = false;
          }
          $scope.$applyAsync(function () {
            if (layerMap && $scope.isObjectNode(layerMap)) {
              wwtlib.LayerManager.layerSelectionChanged(layerMap);
            }
            layerMap.active = true;
            $scope.activeLayer = layerMap;
          });
        }
      };

      $scope.hasChildren = function (node) {
        if (!node){return false;}
        var children = $scope.getChildren(node);
        return children.length || Object.keys(children).length > 0;
      };

      $scope.isObjectNode = function(node){
        if (!node){return false;}
        return node.action == undefined || node.layers || node.childMaps;
      };

      $scope.nodeChange = function (node) {
        //appState.set('layerManager', $scope.tree);
        invokeSetting(node);
      };

      $scope.collapsed = function(node){
        return $scope.isObjectNode(node) ? !node.open : node.collapsed;
      };
      $scope.collapse = function(node){
        var key = 'collapsed';
        var collapse = !$scope.collapsed(node);
        if ($scope.isObjectNode(node)){
          key = 'open';
          collapse = !collapse;
        }
        node[key] = collapse;
      };

      var invokeSetting = function (node) {
        if (!node.disabled && node.action &&
          wwt.wc.settings['set_' + node.action]) {
          var settingFlag = node.checked && !node.disabled;
          wwt.wc.settings['set_' + node.action](settingFlag);
          setSticky(node.name, node.action, settingFlag);
        }
        setChildState(node);
      };

      // enable/disable all child settings based on parent
      var setChildState = function (node) {
        if (node.children) {
          $.each(node.children, function (i, child) {
            child.disabled = !node.checked || node.disabled;
            if (child.action && wwt.wc.settings['set_' + child.action]) {
              var settingFlag = child.checked && !child.disabled;
              wwt.wc.settings['set_' + child.action](settingFlag);
            }
            setChildState(child);
          });
        }
      };

      function initTreeNode(i, node) {
        $.each(node.children, initTreeNode);
        invokeSetting(node);
      }
      wwt.detectNewLayers = function(){
        $scope.$applyAsync(function(){
          //console.log('detecting new layers',wwtlib.LayerManager.get_allMaps(),{newMaps:wwtlib.LayerManager.get_allMaps() !== allMaps});
          allMaps = wwtlib.LayerManager.get_allMaps();
        })
      }
    }]
);
<commit_msg>Add ability to paste into sky layer.<commit_after>wwt.controllers.controller('LayerManagerController',
  ['$scope',
    'AppState',
    '$timeout',
    'Util',
    function ($scope, appState, $timeout, util) {
    var version = 12;

      function treeNode(args) {
        this.name = args.name;
        this.checked = getSticky(args.name, args.action,args.checked);
        this.children = args.children || [];
        this.action = args.action;
        this.collapsed = args.collapsed || false;
        this.disabled = false;
        if (args.mergeWith){
          //console.log({mergedFound:args})
          this.mergeWith = args.mergeWith;
        }
        if (args.v) this.v = args.v;
      }
      var getSticky = function (name, action, defaultState) {
        var sticky = appState.get('layerMgr_' + name + action)
        if (name && action && sticky !== undefined) {
          return sticky;
        } else if (defaultState !== undefined) {
          return defaultState;
        } else {
          return true;
        }
      }
      var setSticky = function (name, action, checked) {
        if (name && action) {
          appState.set('layerMgr_' + name + action, checked);
        }
      }
      var allMaps = {};
      var constellations = [];

      $scope.initLayerManager = function () {
        if (!wwtlib.Constellations.abbreviations) {
          setTimeout($scope.initLayerManager, 333);
          return;
        }
        $.each(wwtlib.Constellations.abbreviations, function (name, abbrev) {
          constellations.push(new treeNode({
            name: name
          }));
        });
        $scope.tree = initTree();//appState.get('layerManager');

    $scope.scrubber = {left:' ',right:' ',table:[0,1,2,3,4,5]};

        $timeout(function () {

          wwt.wc.add_timeScrubberHook(function(prop,val){
            switch (prop){
              case 'left':
              case 'right':
              case 'title':
                $scope.$applyAsync(function() {
                  $scope.scrubber[prop] = val;
                });
                break;
              default:
                var el =  $('.scrubber-slider');
                el.find('.btn').css('left', val * el.width());
                break;
            }
          });

          initTreeNode(0, $scope.tree);
          $timeout(function () {
            var w = $('.scrubber-slider').width();
            var bar = $('.scrubber-slider a.btn');
            var scrubberMover = new wwt.Move({
              el:bar,
              bounds: {
                x: [0, w],
                y: [0, 0]
              },
              onmove:function(){
                wwt.wc.setTimeScrubberPosition(this.css.left/w);
              }
            });

            allMaps = wwtlib.LayerManager.get_allMaps();
            var sunTree = {Sun: (allMaps.Sun)};

            sunTree.Sun.collapsed = false;
            $scope.skyNode = allMaps.Sky;
            //$scope.tree = skyNode;
            //console.log(skyNode);
            $.each(sunTree.Sun.childMaps, function (name, node) {
              node.collapsed = false;
              //node.name = name;
              $.each(node.childMaps, function (childName, child) {
                child.collapsed = true;
                //child.name = childName;
              });
            });
            $scope.sunTree = sunTree;

          }, 123);
        });
        wwt.resize();
      };
      $scope.getChildren = function(node){
        if (!node)return {};
        var children  = node.children || {};
        if (children.length){

          if (node.mergeWith){
            //console.log('mergeWith',node.mergeWith);
            allMaps = wwtlib.LayerManager.get_allMaps();
            if (allMaps && allMaps[node.mergeWith]) {
              //console.log(allMaps[node.mergeWith]);
              var addedChildren = $scope.getChildren(allMaps[node.mergeWith]);
              $.each(children, function (i, childNode) {
                addedChildren[childNode.name] = childNode;
              });
              return addedChildren;
            }
          }
          return children;
        }
        if (node.childMaps && Object.keys(node.childMaps).length){
          children = node.childMaps;
        }
        if (node.layers && node.layers.length){
          node.layers.forEach(function(l){
            children[l._name] = l;
          });
        }
          return children;
      };
      var initTree = function () {
        return new treeNode({
          v: version,
          name: $scope.getFromEn('Sky'),
          mergeWith: 'Sky',// key of node in wwtlib.LayerManager.get_allMaps() to merge into settings. Set this on any settings node
          action: 'showSkyNode',
          checked:true,
          children: [
            new treeNode({
              name: $scope.getFromEn('Overlays'),
              action: 'showSkyOverlays',
              children: [
                new treeNode({
                  name: $scope.getFromEn('Constellations'),
                  action: 'constellationsEnabled',
                  children: [
                    new treeNode({
                      name: $scope.getFromEn('Constellation Pictures'),
                      //children: picturesFilter,
                      action: 'showConstellationPictures',
                      checked: false
                    }), new treeNode({
                      name: $scope.getFromEn('Constellation Figures'),
                      //children: figuresFilter,
                      action: 'showConstellationFigures'
                    }), new treeNode({
                      name: $scope.getFromEn('Constellation Boundaries'),
                      collapsed: true,
                      children: [
                        new treeNode({name: $scope.getFromEn('Focused Only'), action: 'showConstellationSelection'})
                      ],
                      action: 'showConstellationBoundries'
                    }), new treeNode({
                      name: $scope.getFromEn('Constellation Names'),
                      checked: false,
                      action: 'showConstellationLabels'
                    })
                  ]
                }),
                new treeNode({
                  name: $scope.getFromEn('Grids'),
                  action: 'showSkyGrids',
                  children: [
                    new treeNode({
                      name: $scope.getFromEn('Equatorial Grid'),
                      checked: false,
                      collapsed: true,
                      action: 'showGrid',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showEquatorialGridText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('Galactic Grid'),
                      checked: false,
                      collapsed: true,
                      action: 'showGalacticGrid',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showGalacticGridText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('AltAz Grid'),
                      checked: false,
                      collapsed: true,
                      action: 'showAltAzGrid',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showAltAzGridText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('Ecliptic Grid'),
                      checked: false,
                      collapsed: true,
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Axis Labels'),
                          checked: true,
                          action: 'showEclipticGridText'
                        })
                      ],
                      action: 'showEclipticGrid'
                    }), new treeNode({
                      name: $scope.getFromEn('Ecliptic Overview'),
                      checked: true,
                      collapsed: true,
                      action: 'showEcliptic',
                      children: [
                        new treeNode({
                          name: $scope.getFromEn('Month Labels'),
                          checked: false,
                          action: 'showEclipticOverviewText'
                        })
                      ]
                    }), new treeNode({
                      name: $scope.getFromEn('Precession Chart'),
                      checked: false,
                      action: 'showPrecessionChart'
                    })
                  ]
                }), new treeNode({
                  name: $scope.getFromEn('Crosshairs'),
                  checked: true,
                  action: 'showCrosshairs'
                })
              ]
            }),
            new treeNode({
              name: $scope.getFromEn('2d Sky'),
              checked: true,
              action: 'showSkyNode',
              children: [
                new treeNode({
                  name: $scope.getFromEn('Show Solar System'),
                  checked: true,
                  action: 'showSolarSystem'
                }) /*,
						new treeNode({
							name: $scope.getFromEn('Field of View Indicators'),
							checked: true,
							action: 'showFieldOfView'
						})*/
              ]
            }),
            new treeNode({
              name: $scope.getFromEn('3d Solar System'),
              checked: true,
              action: 'showSolarSystem',
              children: [
                new treeNode({
                  name: $scope.getFromEn('Milky Way (Dr. R. Hurt)'),
                  checked: true,
                  action: 'solarSystemMilkyWay'
                }), new treeNode({
                  name: $scope.getFromEn('Stars (Hipparcos, ESA)'),
                  checked: true,
                  action: 'solarSystemStars'
                }), new treeNode({
                  name: $scope.getFromEn('Planets (NASA, ETAL)'),
                  checked: true,
                  action: 'solarSystemPlanets'
                }), new treeNode({
                  name: $scope.getFromEn('Planetary Orbits'),
                  checked: true,
                  action: 'solarSystemOrbits'
                }), new treeNode({
                  name: $scope.getFromEn('Moon & Satellite Orbits'),
                  checked: false,
                  action: 'solarSystemMinorOrbits'
                }), new treeNode({
                  name: $scope.getFromEn('Asteroids (IAU MPC)'),
                  checked: false,
                  action: 'solarSystemMinorPlanets'
                }), new treeNode({
                  name: $scope.getFromEn('Lighting and Shadows'),
                  checked: true,
                  action: 'solarSystemLighting'
                }), new treeNode({
                  name: $scope.getFromEn('Multi-Res Solar System Bodies'),
                  checked: true,
                  action: 'solarSystemMultiRes'
                })
              ]
            })
          ]
        });
      };

      $scope.showMenu = function (layerMap, event) {
        if ($scope.activeLayer) {
          $scope.activeLayer.active = false;
        }
        $scope.$applyAsync(function () {
          layerMap.active = true;
          $scope.activeLayer = layerMap;
        });

        //ensure selection is changed first.
        wwtlib.LayerManager.layerSelectionChanged(layerMap);

        //console.log('invoke context menu on node', event, layerMap);
        wwtlib.LayerManager.showLayerMenu(layerMap, event.pageX, event.pageY);
      }

      $scope.selectionChanged = function (layerMap, event) {
        if (event.currentTarget.tagName==='LABEL' && event.offsetX > 17){
          //console.log(event);
          event.preventDefault();
          event.stopImmediatePropagation();

          if ($scope.activeLayer) {
            $scope.activeLayer.active = false;
          }
          $scope.$applyAsync(function () {
            if (layerMap && $scope.isObjectNode(layerMap)) {
              wwtlib.LayerManager.layerSelectionChanged(layerMap);
            }
            layerMap.active = true;
            $scope.activeLayer = layerMap;
          });
        }
      };

      $scope.hasChildren = function (node) {
        if (!node){return false;}
        var children = $scope.getChildren(node);
        return children.length || Object.keys(children).length > 0;
      };

      $scope.isObjectNode = function(node){
        if (!node){return false;}
        return node.action == undefined || node.layers || node.childMaps;
      };

      $scope.nodeChange = function (node) {
        //appState.set('layerManager', $scope.tree);
        invokeSetting(node);
      };

      $scope.collapsed = function(node){
        return !node ? true : $scope.isObjectNode(node) ? !node.open : node.collapsed;
      };
      $scope.collapse = function(node){
        var key = 'collapsed';
        var collapse = !$scope.collapsed(node);
        if ($scope.isObjectNode(node)){
          key = 'open';
          collapse = !collapse;
        }
        node[key] = collapse;
      };

      var invokeSetting = function (node) {
        if (!node.disabled && node.action &&
          wwt.wc.settings['set_' + node.action]) {
          var settingFlag = node.checked && !node.disabled;
          wwt.wc.settings['set_' + node.action](settingFlag);
          setSticky(node.name, node.action, settingFlag);
        }
        setChildState(node);
      };

      // enable/disable all child settings based on parent
      var setChildState = function (node) {
        if (node.children) {
          $.each(node.children, function (i, child) {
            child.disabled = !node.checked || node.disabled;
            if (child.action && wwt.wc.settings['set_' + child.action]) {
              var settingFlag = child.checked && !child.disabled;
              wwt.wc.settings['set_' + child.action](settingFlag);
            }
            setChildState(child);
          });
        }
      };

      function initTreeNode(i, node) {
        $.each(node.children, initTreeNode);
        invokeSetting(node);
      }
      wwt.detectNewLayers = function(){
        $scope.$applyAsync(function(){
          //console.log('detecting new layers',wwtlib.LayerManager.get_allMaps(),{newMaps:wwtlib.LayerManager.get_allMaps() !== allMaps});
          allMaps = wwtlib.LayerManager.get_allMaps();
        })
      }
    }]
);
<|endoftext|>


<commit_before>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

'use strict';

export type ResolvedAssetSource = {|
  +__packager_asset: boolean,
  +width: ?number,
  +height: ?number,
  +uri: string,
  +scale: number,
|};

import type {PackagerAsset} from '@react-native/assets/registry';

const PixelRatio = require('../Utilities/PixelRatio');
const {pickScale} = require('./AssetUtils');
const Platform = require('../Utilities/Platform');

const invariant = require('invariant');

const {
  getAndroidResourceFolderName,
  getAndroidResourceIdentifier,
  getBasePath,
} = require('@react-native/assets/path-support');

/**
 * Returns a path like 'assets/AwesomeModule/icon@2x.png'
 */
function getScaledAssetPath(asset: PackagerAsset): string {
  const scale = pickScale(asset.scales, PixelRatio.get());
  const scaleSuffix = scale === 1 ? '' : '@' + scale + 'x';
  const assetDir = getBasePath(asset);
  return assetDir + '/' + asset.name + scaleSuffix + '.' + asset.type;
}

/**
 * Returns a path like 'drawable-mdpi/icon.png'
 */
function getAssetPathInDrawableFolder(asset: PackagerAsset): string {
  const scale = pickScale(asset.scales, PixelRatio.get());
  const drawbleFolder = getAndroidResourceFolderName(asset, scale);
  const fileName = getAndroidResourceIdentifier(asset);
  return drawbleFolder + '/' + fileName + '.' + asset.type;
}

class AssetSourceResolver {
  serverUrl: ?string;
  // where the jsbundle is being run from
  jsbundleUrl: ?string;
  // the asset to resolve
  asset: PackagerAsset;

  constructor(serverUrl: ?string, jsbundleUrl: ?string, asset: PackagerAsset) {
    this.serverUrl = serverUrl;
    this.jsbundleUrl = jsbundleUrl;
    this.asset = asset;
  }

  isLoadedFromServer(): boolean {
    return !!this.serverUrl;
  }

  isLoadedFromFileSystem(): boolean {
    return !!(this.jsbundleUrl && this.jsbundleUrl.startsWith('file://'));
  }

  defaultAsset(): ResolvedAssetSource {
    if (this.isLoadedFromServer()) {
      return this.assetServerURL();
    }

    if (Platform.OS === 'android') {
      return this.isLoadedFromFileSystem()
        ? this.drawableFolderInBundle()
        : this.resourceIdentifierWithoutScale();
    } else {
      return this.scaledAssetURLNearBundle();
    }
  }

  /**
   * Returns an absolute URL which can be used to fetch the asset
   * from the devserver
   */
  assetServerURL(): ResolvedAssetSource {
    invariant(!!this.serverUrl, 'need server to load from');
    return this.fromSource(
      this.serverUrl +
        getScaledAssetPath(this.asset) +
        '?platform=' +
        Platform.OS +
        '&hash=' +
        this.asset.hash,
    );
  }

  /**
   * Resolves to just the scaled asset filename
   * E.g. 'assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetPath(): ResolvedAssetSource {
    return this.fromSource(getScaledAssetPath(this.asset));
  }

  /**
   * Resolves to where the bundle is running from, with a scaled asset filename
   * E.g. 'file:///sdcard/bundle/assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetURLNearBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(
      // Assets can have relative paths outside of the project root.
      // When bundling them we replace `../` with `_` to make sure they
      // don't end up outside of the expected assets directory.
      path + getScaledAssetPath(this.asset).replace(/\.\.\//g, '_'),
    );
  }

  /**
   * The default location of assets bundled with the app, located by
   * resource identifier
   * The Android resource system picks the correct scale.
   * E.g. 'assets_awesomemodule_icon'
   */
  resourceIdentifierWithoutScale(): ResolvedAssetSource {
    invariant(
      Platform.OS === 'android',
      'resource identifiers work on Android',
    );
    return this.fromSource(getAndroidResourceIdentifier(this.asset));
  }

  /**
   * If the jsbundle is running from a sideload location, this resolves assets
   * relative to its location
   * E.g. 'file:///sdcard/AwesomeModule/drawable-mdpi/icon.png'
   */
  drawableFolderInBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(path + getAssetPathInDrawableFolder(this.asset));
  }

  fromSource(source: string): ResolvedAssetSource {
    return {
      __packager_asset: true,
      width: this.asset.width,
      height: this.asset.height,
      uri: source,
      scale: pickScale(this.asset.scales, PixelRatio.get()),
    };
  }

  static pickScale: (scales: Array<number>, deviceScale?: number) => number =
    pickScale;
}

module.exports = AssetSourceResolver;
<commit_msg>fix: asset source resolver typo (#34520)<commit_after>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

'use strict';

export type ResolvedAssetSource = {|
  +__packager_asset: boolean,
  +width: ?number,
  +height: ?number,
  +uri: string,
  +scale: number,
|};

import type {PackagerAsset} from '@react-native/assets/registry';

const PixelRatio = require('../Utilities/PixelRatio');
const {pickScale} = require('./AssetUtils');
const Platform = require('../Utilities/Platform');

const invariant = require('invariant');

const {
  getAndroidResourceFolderName,
  getAndroidResourceIdentifier,
  getBasePath,
} = require('@react-native/assets/path-support');

/**
 * Returns a path like 'assets/AwesomeModule/icon@2x.png'
 */
function getScaledAssetPath(asset: PackagerAsset): string {
  const scale = pickScale(asset.scales, PixelRatio.get());
  const scaleSuffix = scale === 1 ? '' : '@' + scale + 'x';
  const assetDir = getBasePath(asset);
  return assetDir + '/' + asset.name + scaleSuffix + '.' + asset.type;
}

/**
 * Returns a path like 'drawable-mdpi/icon.png'
 */
function getAssetPathInDrawableFolder(asset: PackagerAsset): string {
  const scale = pickScale(asset.scales, PixelRatio.get());
  const drawableFolder = getAndroidResourceFolderName(asset, scale);
  const fileName = getAndroidResourceIdentifier(asset);
  return drawableFolder + '/' + fileName + '.' + asset.type;
}

class AssetSourceResolver {
  serverUrl: ?string;
  // where the jsbundle is being run from
  jsbundleUrl: ?string;
  // the asset to resolve
  asset: PackagerAsset;

  constructor(serverUrl: ?string, jsbundleUrl: ?string, asset: PackagerAsset) {
    this.serverUrl = serverUrl;
    this.jsbundleUrl = jsbundleUrl;
    this.asset = asset;
  }

  isLoadedFromServer(): boolean {
    return !!this.serverUrl;
  }

  isLoadedFromFileSystem(): boolean {
    return !!(this.jsbundleUrl && this.jsbundleUrl.startsWith('file://'));
  }

  defaultAsset(): ResolvedAssetSource {
    if (this.isLoadedFromServer()) {
      return this.assetServerURL();
    }

    if (Platform.OS === 'android') {
      return this.isLoadedFromFileSystem()
        ? this.drawableFolderInBundle()
        : this.resourceIdentifierWithoutScale();
    } else {
      return this.scaledAssetURLNearBundle();
    }
  }

  /**
   * Returns an absolute URL which can be used to fetch the asset
   * from the devserver
   */
  assetServerURL(): ResolvedAssetSource {
    invariant(!!this.serverUrl, 'need server to load from');
    return this.fromSource(
      this.serverUrl +
        getScaledAssetPath(this.asset) +
        '?platform=' +
        Platform.OS +
        '&hash=' +
        this.asset.hash,
    );
  }

  /**
   * Resolves to just the scaled asset filename
   * E.g. 'assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetPath(): ResolvedAssetSource {
    return this.fromSource(getScaledAssetPath(this.asset));
  }

  /**
   * Resolves to where the bundle is running from, with a scaled asset filename
   * E.g. 'file:///sdcard/bundle/assets/AwesomeModule/icon@2x.png'
   */
  scaledAssetURLNearBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(
      // Assets can have relative paths outside of the project root.
      // When bundling them we replace `../` with `_` to make sure they
      // don't end up outside of the expected assets directory.
      path + getScaledAssetPath(this.asset).replace(/\.\.\//g, '_'),
    );
  }

  /**
   * The default location of assets bundled with the app, located by
   * resource identifier
   * The Android resource system picks the correct scale.
   * E.g. 'assets_awesomemodule_icon'
   */
  resourceIdentifierWithoutScale(): ResolvedAssetSource {
    invariant(
      Platform.OS === 'android',
      'resource identifiers work on Android',
    );
    return this.fromSource(getAndroidResourceIdentifier(this.asset));
  }

  /**
   * If the jsbundle is running from a sideload location, this resolves assets
   * relative to its location
   * E.g. 'file:///sdcard/AwesomeModule/drawable-mdpi/icon.png'
   */
  drawableFolderInBundle(): ResolvedAssetSource {
    const path = this.jsbundleUrl || 'file://';
    return this.fromSource(path + getAssetPathInDrawableFolder(this.asset));
  }

  fromSource(source: string): ResolvedAssetSource {
    return {
      __packager_asset: true,
      width: this.asset.width,
      height: this.asset.height,
      uri: source,
      scale: pickScale(this.asset.scales, PixelRatio.get()),
    };
  }

  static pickScale: (scales: Array<number>, deviceScale?: number) => number =
    pickScale;
}

module.exports = AssetSourceResolver;
<|endoftext|>


<commit_before>module("vie.js - Schema.org Ontology");

test("Initialization", function() {
    var z = new VIE();

    ok(z.loadSchemaOrg);
    equal(typeof z.loadSchemaOrg, "function");

    z.loadSchemaOrg();

    equal(z.types.list().length, 296);

    //just pick some and test them:
    ok (z.types.get("Person"));
    ok (z.types.get("Corporation"));
    ok (z.types.get("Corporation").isof("Thing"));
    ok (z.types.get("Organization").subsumes("Corporation"));

    ok (z.types.get("Person").id.indexOf("http://schema.org/") === 0);

    var hospital = z.types.get("Hospital");
    ok (hospital);
    equal( hospital.attributes.list().length, 27);

    equal(hospital.attributes.get('description').range.length, 1);
    equal(hospital.attributes.get('description').range[0], "Text");
    equal(hospital.attributes.get('geo').range.length, 1);
    equal(hospital.attributes.get('geo').range[0], "GeoCoordinates");
    equal(hospital.attributes.get('location').range.length, 2);
    equal(hospital.attributes.get('location').range[0], "Place");
    equal(hospital.attributes.get('location').range[1], "PostalAddress");

    raises(function () {
        hospital.attributes.remove("description");
    });

    z.types.get("Organization").attributes.remove("founders");

    equal( hospital.attributes.list().length, 26);
});
<commit_msg>fixed schemaOrg test<commit_after>module("vie.js - Schema.org Ontology");

test("Initialization", function() {
    var z = new VIE();

    ok(z.loadSchemaOrg);
    equal(typeof z.loadSchemaOrg, "function");

    z.loadSchemaOrg();

    equal(z.types.list().length, 296);

    //just pick some and test them:
    ok (z.types.get("Person"));
    ok (z.types.get("Corporation"));
    ok (z.types.get("Corporation").isof("Thing"));
    ok (z.types.get("Organization").subsumes("Corporation"));

    ok (z.types.get("Person").id.indexOf("<http://schema.org/") === 0);

    var hospital = z.types.get("Hospital");
    ok (hospital);
    equal( hospital.attributes.list().length, 27);

    equal(hospital.attributes.get('description').range.length, 1);
    equal(hospital.attributes.get('description').range[0], "Text");
    equal(hospital.attributes.get('geo').range.length, 1);
    equal(hospital.attributes.get('geo').range[0], "GeoCoordinates");
    equal(hospital.attributes.get('location').range.length, 2);
    equal(hospital.attributes.get('location').range[0], "Place");
    equal(hospital.attributes.get('location').range[1], "PostalAddress");

    raises(function () {
        hospital.attributes.remove("description");
    });

    z.types.get("Organization").attributes.remove("founders");

    equal( hospital.attributes.list().length, 26);
});
<|endoftext|>


<commit_before>'use strict';

var OAuth2 = require('oauth').OAuth2,
    http = require('http'),
    oauthConfig = require('../config/oauth');

var db = require('../models'),
    User = db.User;

var errors = {
  incorrectApiKey: {
    ok: false,
    error: {
      type: "invalid_request",
      message: "The API key provided is not valid"
    }
  },
  keyNotFound: {
    ok: false,
    error: {
      type: "Not Found",
      message: "No API key was found in this request"
    }
  }
};

var getApiKey = function(req) {
  var headerRegex = /^Bearer (\w+)/;

  if (headerRegex.test(req.headers.authorization)) {
    return req.headers.authorization.match(headerRegex)[1];
  }

  if (req.method === "GET") {
    if (req.query.api_key !== undefined && /\w+/.test(req.query.api_key)) {
      return req.query.api_key;
    }
  }

  if (['POST', 'DELETE', 'PUT'].indexOf(req.method) > -1) {
    if (req.body.api_key !== undefined && /\w+/.test(req.body.api_key)) {
      return req.body.api_key;
    }
  }

  return false;
};

var ApplicationController = {};

// TODO - put authenticated user in req
ApplicationController.authenticate = function(req, res, next) {
  var clientId = process.env.CLIENT_ID,
      clientSecret = process.env.CLIENT_SECRET,
      grantType = process.env.GRANT_TYPE,
      clientBasicAuth = new Buffer(clientId + ':' + clientSecret).toString('base64');

  var oauth2 = new OAuth2(
    clientId,
    clientSecret,
    oauthConfig.server,
    oauthConfig.authorisePath,
    oauthConfig.tokenPath,
    { 'Authorization': 'Basic ' + clientBasicAuth }
  );

  var profilePath = oauthConfig.server + oauthConfig.profilePath;

  req.apiKey = getApiKey(req);

  if (!req.apiKey) {
    return res.json(400, errors.keyNotFound);
  }

  User
    .find({ where: { apiKey: req.apiKey } })

    .error(function(err) {
      next(error);
    })

    .success(function(user) {
      if (user) {
        req.user = user;
        var reqPath = '/' + oauthConfig.profilePath +
          '?access_token=' + user.accessToken;
        var authGet = http.get(
          {
            host: oauthConfig.server,
            port: 3002,
            path: reqPath
          } , function (authRes) {
            authRes.setEncoding('utf8');
            authRes.on('data', function(data){
              if (JSON.parse(data).username === user.username) {
                next();
              } else {
                return res.json(400, errors.incorrectApiKey);
              }
            });
          }
        );
        authGet.on('error', function(e){
          return res.json(400, e);
        });
        authGet.end();
      } else {
        return res.json(400, errors.incorrectApiKey);
      }
    });
};

module.exports = ApplicationController;
<commit_msg>fix one of API authentication routines to treat oauthConfig.server as the URL it needs to be elsewhere (not just a host!)<commit_after>'use strict';

var OAuth2 = require('oauth').OAuth2,
    http = require('http'),
    oauthConfig = require('../config/oauth');

var db = require('../models'),
    User = db.User;

var errors = {
  incorrectApiKey: {
    ok: false,
    error: {
      type: "invalid_request",
      message: "The API key provided is not valid"
    }
  },
  keyNotFound: {
    ok: false,
    error: {
      type: "Not Found",
      message: "No API key was found in this request"
    }
  }
};

var getApiKey = function(req) {
  var headerRegex = /^Bearer (\w+)/;

  if (headerRegex.test(req.headers.authorization)) {
    return req.headers.authorization.match(headerRegex)[1];
  }

  if (req.method === "GET") {
    if (req.query.api_key !== undefined && /\w+/.test(req.query.api_key)) {
      return req.query.api_key;
    }
  }

  if (['POST', 'DELETE', 'PUT'].indexOf(req.method) > -1) {
    if (req.body.api_key !== undefined && /\w+/.test(req.body.api_key)) {
      return req.body.api_key;
    }
  }

  return false;
};

var ApplicationController = {};

// TODO - put authenticated user in req
ApplicationController.authenticate = function(req, res, next) {
  var clientId = process.env.CLIENT_ID,
      clientSecret = process.env.CLIENT_SECRET,
      grantType = process.env.GRANT_TYPE,
      clientBasicAuth = new Buffer(clientId + ':' + clientSecret).toString('base64');

  var oauth2 = new OAuth2(
    clientId,
    clientSecret,
    oauthConfig.server,
    oauthConfig.authorisePath,
    oauthConfig.tokenPath,
    { 'Authorization': 'Basic ' + clientBasicAuth }
  );

  var profilePath = oauthConfig.server + oauthConfig.profilePath;

  req.apiKey = getApiKey(req);

  if (!req.apiKey) {
    return res.json(400, errors.keyNotFound);
  }

  User
    .find({ where: { apiKey: req.apiKey } })

    .error(function(err) {
      next(error);
    })

    .success(function(user) {
      if (user) {
        req.user = user;
        var reqPath = '/' + oauthConfig.profilePath +
          '?access_token=' + user.accessToken;
        var authGet = http.get(oauthConfig.server + reqPath, function (authRes) {
            authRes.setEncoding('utf8');
            authRes.on('data', function(data){
              if (JSON.parse(data).username === user.username) {
                next();
              } else {
                return res.json(400, errors.incorrectApiKey);
              }
            });
          }
        );
        authGet.on('error', function(e){
          return res.json(400, e);
        });
        authGet.end();
      } else {
        return res.json(400, errors.incorrectApiKey);
      }
    });
};

module.exports = ApplicationController;
<|endoftext|>


<commit_before>/**
 * Created by yasirmahmood on 27/01/2014.
 */
var config = require('../Config/config');

var ConnectionConfig = function (options) {
    if (typeof options === 'string') {
        return "invalid params passed";
    }

    this.authServerUrl      = options.authServerUrl,
        this.clientUrl          = options.redirectUrl,
        this.apiServerUrl       = options.apiServerUrl,
        this.clientId           = options.clientIdentifier,
        this.clientSecret       = options.clientSecret,
        this.projectName        = options.projectName,
        this.accessType         = options.accessType,
        this.defaultScope       = (options.defaultScope === undefined)   ? config.defaultScope : options.defaultScope,
        this.responseType       = (options.responseType === undefined)   ? config.responseType : options.responseType,
        this.acceptEncoding     = (options.acceptEncoding === undefined) ? config.acceptEncoding : options.acceptEncoding,
        this.apiVersion         = (options.apiVersion === undefined) ? config.apiVersion : options.apiVersion,
        this.displayErrorLog    = (options.displayErrorLog === undefined) ? config.displayErrorLog : options.displayErrorLog
};

module.exports = ConnectionConfig;<commit_msg>style fixes<commit_after>/**
 * Created by yasirmahmood on 27/01/2014.
 */
var config = require('../Config/config');

var ConnectionConfig = function (options)
{
    if (typeof options === 'string')
    {
        return "invalid params passed";
    }

    this.authServerUrl      = options.authServerUrl,
    this.clientUrl          = options.redirectUrl,
    this.apiServerUrl       = options.apiServerUrl,
    this.clientId           = options.clientIdentifier,
    this.clientSecret       = options.clientSecret,
    this.projectName        = options.projectName,
    this.accessType         = options.accessType,
    this.defaultScope       = (options.defaultScope === undefined)   ? config.defaultScope : options.defaultScope,
    this.responseType       = (options.responseType === undefined)   ? config.responseType : options.responseType,
    this.acceptEncoding     = (options.acceptEncoding === undefined) ? config.acceptEncoding : options.acceptEncoding,
    this.apiVersion         = (options.apiVersion === undefined) ? config.apiVersion : options.apiVersion,
    this.displayErrorLog    = (options.displayErrorLog === undefined) ? config.displayErrorLog : options.displayErrorLog
};

module.exports = ConnectionConfig;<|endoftext|>