<commit_before>var express = require('express');
var router = express.Router();
var config = require('../scripts/config.js');

var orion = require('fiware-orion-mintaka');
orion.configure(config.ORION);

var json = {
	"attributes" : [
		{
			"name" : "temperature",
			"type" : "float",
			"value" : "23"
		},
		{
			"name" : "pressure",
			"type" : "integer",
			"value" : "720"
		}
	]
};

/* GET users listing. */
router.get('/', function(req, res, next) {
	orion.requestEntities().then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/register/:type/entity/:entity',function(req, res, next){
	var e = req.params.entity;
	var t = req.params.type;
	//console.log('register', e);
	orion.registerEntityWithType(e, t, json).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/register/:entity/attribute/:attribute', function(req, res, next){
	var e = req.params.entity;
	var a = req.params.attribute;
	orion.registerAttribute(e, a, 34).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/:entity/attributes',function(req, res, next){
	var e = req.params.entity;
	orion.queryAttributes(e).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/:entity/attributes/:attribute',function(req, res, next){
	var e = req.params.entity;
	var a = req.params.attribute;
	orion.querySingleAttribute(e, a).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/register/:entity', function(req, res, next){
	var e = req.params.entity;
	//console.log('register', e);
	orion.registerEntity(e, json).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/type/:type', function(req, res, next){
	var t = req.params.type;
	orion.queryEntitiesByType(t).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/type/:type/attribute/:attribute',function(req, res, next){
	var t = req.params.type;
	var a = req.params.attribute;
	orion.querySingleAttributeByEntityType(t, a).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/delete/:entity', function(req, res, next){
	var e = req.params.entity;
	//console.log('delete', e);
	orion.deleteEntity(e).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

module.exports = router;
<commit_msg>adjustments<commit_after>/**
 * routes for controlling the context broker - mostly for feedback/control in development
 */

var express = require('express');
var router = express.Router();
var config = require('../config/config.js');

var orion = require('fiware-orion-mintaka');
orion.configure(config.ORION);

var json = {"attributes":[{"name":"free","type":"integer","value":0},{"name":"occupied","type":"integer","value":0},{"name":"percentage_free","type":"float","value":0},{"name":"percentage_occupied","type":"float","value":0},{"name":"highest","type":"string","value":"-"},{"name":"lowest","type":"string","value":"-"},{"name":"change","type":"string","value":"-"}]};

/* GET listing. */
router.get('/', function(req, res, next) {
	orion.requestEntities().then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/register/:type/entity/:entity',function(req, res, next){
	var e = req.params.entity;
	var t = req.params.type;
	//console.log('register', e);
	orion.registerEntityWithType(e, t, json).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/register/:entity/attribute/:attribute', function(req, res, next){
	var e = req.params.entity;
	var a = req.params.attribute;
	orion.registerAttribute(e, a, 34).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/:entity/attributes',function(req, res, next){
	var e = req.params.entity;
	orion.queryAttributes(e).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/:entity/attributes/:attribute',function(req, res, next){
	var e = req.params.entity;
	var a = req.params.attribute;
	orion.querySingleAttribute(e, a).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/register/:entity', function(req, res, next){
	var e = req.params.entity;
	//console.log('register', e);
	orion.registerEntity(e, json).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/type/:type', function(req, res, next){
	var t = req.params.type;
	orion.queryEntitiesByType(t).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/type/:type/attribute/:attribute',function(req, res, next){
	var t = req.params.type;
	var a = req.params.attribute;
	orion.querySingleAttributeByEntityType(t, a).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

router.get('/delete/:entity', function(req, res, next){
	var e = req.params.entity;
	//console.log('delete', e);
	orion.deleteEntity(e).then(
		function(success){
			res.send(success);
		},
		function(error){
			res.send(error);
		}
	);
});

module.exports = router;
<|endoftext|>


<commit_before>if (!global.Promise) global.Promise = require('promise-polyfill');
if (!global.fetch) global.fetch = require('isomorphic-unfetch');
<commit_msg>Fix Promise polyfill not working in IE11 (#860)<commit_after>if (!global.Promise) global.Promise = require('promise-polyfill').default;
if (!global.fetch) global.fetch = require('isomorphic-unfetch');
<|endoftext|>


<commit_before>import {consoleLogger} from 'tocco-util'

const handleError = (response, acceptedErrorCodes = [], acceptedStatusCodes = []) => {
  if (!response.ok
    && !acceptedStatusCodes.includes(response.status)
    && !(response.body && acceptedErrorCodes.includes(response.body.errorCode))) {
    const msg = `${response.statusText} ${response.body ? response.body.message : ''}`
    throw new Error(msg)
  }

  return response
}

const extractBody = response => {
  const {ok, headers, status, statusText} = response
  const filteredResponse = {ok, headers, status, statusText}
  if (status === 204) {
    return {...filteredResponse, body: null}
  }
  return response.json()
    .then(body => ({...filteredResponse, body}))
    .catch(exception => {
      consoleLogger.log('Unable to extract request body', exception, response)
      return {...filteredResponse}
    })
}

export function sendRequest(url, options, acceptedErrorCodes, acceptedStatusCodes) {
  return fetch(url, options)
    .then(response => (extractBody(response)))
    .then(response => (handleError(response, acceptedErrorCodes, acceptedStatusCodes)))
}
<commit_msg>refactor(app-extensions): remove unnecessary log<commit_after>const handleError = (response, acceptedErrorCodes = [], acceptedStatusCodes = []) => {
  if (!response.ok
    && !acceptedStatusCodes.includes(response.status)
    && !(response.body && acceptedErrorCodes.includes(response.body.errorCode))) {
    const msg = `${response.statusText} ${response.body ? response.body.message : ''}`
    throw new Error(msg)
  }

  return response
}

const extractBody = response => {
  const {ok, headers, status, statusText} = response
  const filteredResponse = {ok, headers, status, statusText}
  if (status === 204) {
    return {...filteredResponse, body: null}
  }
  return response.json()
    .then(body => ({...filteredResponse, body}))
    .catch(exception => {
      return {...filteredResponse, body: null}
    })
}

export function sendRequest(url, options, acceptedErrorCodes, acceptedStatusCodes) {
  return fetch(url, options)
    .then(response => (extractBody(response)))
    .then(response => (handleError(response, acceptedErrorCodes, acceptedStatusCodes)))
}
<|endoftext|>


<commit_before>import request from 'request-promise';
import {DatabaseConnector} from 'cloud-core';

let db = null // cache this.

/**
 * This is the validateFunc for https://github.com/hapijs/hapi-auth-basic
 *
 * API requests are of the form:
 * https://username:pass@n1.nylas.com/some/route
 *
 * The username field is the AccountToken of the N1 Cloud Account (aka
 * email account)
 * The password field is the N1 Identity Token.
 *
 * Then cb callback param must be called with the signature of:
 * function(err, isValid, credentials)
 */
export async function apiAuthenticate(req, username, password, cb) {
  const accountToken = username
  const n1IdentityToken = password
  if (!db) { db = await DatabaseConnector.forShared() }

  const token = await db.AccountToken.find({where: {value: accountToken}})
  if (!token) return cb(null, false, {});

  const account = await token.getAccount();
  account.n1IdentityToken = n1IdentityToken;
  req.logger = req.logger.forAccount(account);

  let identPath = "https://billing.nylas.com";
  if (process.env.NODE_ENV === "staging") {
    identPath = "https://billing-staging.nylas.com"
  } else if (process.env.NODE_ENV === "development") {
    identPath = "http://billing.lvh.me:5555"
  }

  identPath = "https://billing-staging.nylas.com"

  try {
    const identity = await request(`${identPath}/n1/user`, {
      auth: {username: n1IdentityToken, password: ''},
    })
    // req.logger.debug({identity}, `Got ${identPath} identity response`)
    return cb(null, true, {account, identity});
  } catch (err) {
    let statusCode = err;
    let responseBody = err;
    if (err && err.response) {
      statusCode = err.response.statusCode
      try {
        responseBody = JSON.parse(err.response.body);
      } catch (e) {
        responseBody = err.response.body;
      }
    }
    const responseDetails = {
      status_code: statusCode,
      body: responseBody,
    }

    let identityReqUri = "";
    if (err & err.options) {
      identityReqUri = err.options.uri
    }

    // cannot log entire err object because it contains sensitive information
    // such as the account token & auth headers - see example below
    req.logger.error({
      error_name: err.name,
      identity_req_uri: identityReqUri,
      response_details: responseDetails,
    }, `Invalid credentials, can't authenticate`)
    return cb(null, false, {})
  }
}

// Example `error` object querying identity server (from above):
//
// {
//     "error": "{\n  \"message\": \"Invalid credentials.\",\n  \"type\": \"invalid_request_error\"\n}",
//     "message": "400 - \"{\\n  \\\"message\\\": \\\"Invalid credentials.\\\",\\n  \\\"type\\\": \\\"invalid_request_error\\\"\\n}\"",
//     "name": "StatusCodeError",
//     "options": {
//         "auth": {
//             "pass": "",
//             "password": "",
//             "user": "KQPTpmOsPeTneqFAcNh9dbvU4OGZSd",
//             "username": "KQPTpmOsPeTneqFAcNh9dbvU4OGZSd"
//         },
//         "resolveWithFullResponse": false,
//         "simple": true,
//         "transform2xxOnly": false,
//         "uri": "https://billing-staging.nylas.com/n1/user"
//     },
//     "response": {
//         "body": " {\n  \"message\": \"Invalid credentials.\",\n  \"type\": \"invalid_request_error\"\n}",
//         "headers": {
//             "connection": "close",
//             "content-length": "74",
//             "content-type": "application/json",
//             "date": "Fri, 03 Feb 2017 22:19:44 GMT",
//             "server": "nginx/1.6.2",
//             "strict-transport-security": "max-age=31536000;",
//             "x-frame-options": "SAMEORIGIN, SAMEORIGIN"
//         },
//         "request": {
//             "headers": {
//                 "authorization": "Basic S1FQVHBtT3NQZVRuZXFGQWNOaDlkYnZVNE9HWlNkOg=="
//             },
//             "method": "GET",
//             "uri": {
//                 "auth": null,
//                 "hash": null,
//                 "host": "billing-staging.nylas.com",
//                 "hostname": "billing-staging.nylas.com",
//                 "href": "https://billing-staging.nylas.com/n1/user",
//                 "path": "/n1/user",
//                 "pathname": "/n1/user",
//                 "port": 443,
//                 "protocol": "https:",
//                 "query": null,
//                 "search": null,
//                 "slashes": true
//             }
//         },
//         "statusCode": 400
//     },
//     "statusCode": 400
// }
<commit_msg>[cloud-api] Remove global override of billing identity URL<commit_after>import request from 'request-promise';
import {DatabaseConnector} from 'cloud-core';

let db = null // cache this.

/**
 * This is the validateFunc for https://github.com/hapijs/hapi-auth-basic
 *
 * API requests are of the form:
 * https://username:pass@n1.nylas.com/some/route
 *
 * The username field is the AccountToken of the N1 Cloud Account (aka
 * email account)
 * The password field is the N1 Identity Token.
 *
 * Then cb callback param must be called with the signature of:
 * function(err, isValid, credentials)
 */
export async function apiAuthenticate(req, username, password, cb) {
  const accountToken = username
  const n1IdentityToken = password
  if (!db) { db = await DatabaseConnector.forShared() }

  const token = await db.AccountToken.find({where: {value: accountToken}})
  if (!token) return cb(null, false, {});

  const account = await token.getAccount();
  account.n1IdentityToken = n1IdentityToken;
  req.logger = req.logger.forAccount(account);

  let identPath = "https://billing.nylas.com";
  if (process.env.NODE_ENV === "staging") {
    identPath = "https://billing-staging.nylas.com"
  } else if (process.env.NODE_ENV === "development") {
    identPath = "http://billing.lvh.me:5555"
  }

  try {
    const identity = await request(`${identPath}/n1/user`, {
      auth: {username: n1IdentityToken, password: ''},
    })
    // req.logger.debug({identity}, `Got ${identPath} identity response`)
    return cb(null, true, {account, identity});
  } catch (err) {
    let statusCode = err;
    let responseBody = err;
    if (err && err.response) {
      statusCode = err.response.statusCode
      try {
        responseBody = JSON.parse(err.response.body);
      } catch (e) {
        responseBody = err.response.body;
      }
    }
    const responseDetails = {
      status_code: statusCode,
      body: responseBody,
    }

    let identityReqUri = "";
    if (err & err.options) {
      identityReqUri = err.options.uri
    }

    // cannot log entire err object because it contains sensitive information
    // such as the account token & auth headers - see example below
    req.logger.error({
      error_name: err.name,
      identity_req_uri: identityReqUri,
      response_details: responseDetails,
    }, `Invalid credentials, can't authenticate`)
    return cb(null, false, {})
  }
}

// Example `error` object querying identity server (from above):
//
// {
//     "error": "{\n  \"message\": \"Invalid credentials.\",\n  \"type\": \"invalid_request_error\"\n}",
//     "message": "400 - \"{\\n  \\\"message\\\": \\\"Invalid credentials.\\\",\\n  \\\"type\\\": \\\"invalid_request_error\\\"\\n}\"",
//     "name": "StatusCodeError",
//     "options": {
//         "auth": {
//             "pass": "",
//             "password": "",
//             "user": "KQPTpmOsPeTneqFAcNh9dbvU4OGZSd",
//             "username": "KQPTpmOsPeTneqFAcNh9dbvU4OGZSd"
//         },
//         "resolveWithFullResponse": false,
//         "simple": true,
//         "transform2xxOnly": false,
//         "uri": "https://billing-staging.nylas.com/n1/user"
//     },
//     "response": {
//         "body": " {\n  \"message\": \"Invalid credentials.\",\n  \"type\": \"invalid_request_error\"\n}",
//         "headers": {
//             "connection": "close",
//             "content-length": "74",
//             "content-type": "application/json",
//             "date": "Fri, 03 Feb 2017 22:19:44 GMT",
//             "server": "nginx/1.6.2",
//             "strict-transport-security": "max-age=31536000;",
//             "x-frame-options": "SAMEORIGIN, SAMEORIGIN"
//         },
//         "request": {
//             "headers": {
//                 "authorization": "Basic S1FQVHBtT3NQZVRuZXFGQWNOaDlkYnZVNE9HWlNkOg=="
//             },
//             "method": "GET",
//             "uri": {
//                 "auth": null,
//                 "hash": null,
//                 "host": "billing-staging.nylas.com",
//                 "hostname": "billing-staging.nylas.com",
//                 "href": "https://billing-staging.nylas.com/n1/user",
//                 "path": "/n1/user",
//                 "pathname": "/n1/user",
//                 "port": 443,
//                 "protocol": "https:",
//                 "query": null,
//                 "search": null,
//                 "slashes": true
//             }
//         },
//         "statusCode": 400
//     },
//     "statusCode": 400
// }
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';

import Popup, {
    PurePopup,
    PopupMessage,
    PopupIcon,
    PopupButton,
    BEM as POPUP_BEM,
} from '../Popup';

import Button from '../Button';
import Icon from '../Icon';
import Overlay from '../Overlay';
import TextLabel from '../TextLabel';

describe('<Popup> with mixins', () => {
    it('should render without crashing', () => {
        const div = document.createElement('div');
        const element = <Popup />;

        ReactDOM.render(element, div);
    });
});

describe('Pure <Popup>', () => {
    it('contains an <Overlay>', () => {
        const wrapper = shallow(<PurePopup message="foo" />);

        expect(wrapper.find(Overlay).exists()).toBeTruthy();
    });

    it('renders a string message with <PopupMessage>', () => {
        const wrapper = shallow(<PurePopup message="foo" />);

        expect(wrapper.find(PopupMessage).exists()).toBeTruthy();
        expect(wrapper.find(PopupMessage).prop('text')).toBe('foo');
    });

    it('takes a valid element for message prop', () => {
        const label = <TextLabel data-target basic="Foo" aside="bar" />;
        const wrapper = shallow(<PurePopup message={label} />);

        expect(wrapper.find(PopupMessage).exists()).toBeFalsy();
        expect(wrapper.find('[data-target]').exists()).toBeTruthy();
    });

    it('renders a string icon with <PopupIcon>', () => {
        const wrapper = shallow(<PurePopup icon="success" />);

        expect(wrapper.find(PopupIcon).exists()).toBeTruthy();
        expect(wrapper.find(PopupIcon).prop('type')).toBe('success');
    });

    it('takes a valid element for icon prop', () => {
        const icon = <Icon data-target type="success" />;
        const wrapper = shallow(<PurePopup icon={icon} />);

        expect(wrapper.find(PopupIcon).exists()).toBeFalsy();
        expect(wrapper.find('[data-target]').exists()).toBeTruthy();
    });

    it('renders buttons with <PopupButton> in a buttons-group section when specified', () => {
        const buttons = [
            <Button key="a" basic="Label A" />,
            <Button key="b" basic="Label B" />,
        ];
        const wrapper = shallow(<PurePopup message="foo" />);
        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).exists()).toBeFalsy();

        wrapper.setProps({ buttons });
        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).exists()).toBeTruthy();

        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).children()).toHaveLength(2);
        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).containsAllMatchingElements([
            <PopupButton basic="Label A" />,
            <PopupButton basic="Label B" />,
        ])).toBeTruthy();
    });
});
<commit_msg>Add tests for helper components in <Popup><commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';

import Popup, {
    PurePopup,
    PopupMessage,
    PopupIcon,
    PopupButton,
    BEM as POPUP_BEM,
} from '../Popup';

import Button from '../Button';
import Icon from '../Icon';
import Overlay from '../Overlay';
import TextLabel from '../TextLabel';

describe('<Popup> with mixins', () => {
    it('should render without crashing', () => {
        const div = document.createElement('div');
        const element = <Popup />;

        ReactDOM.render(element, div);
    });
});

describe('Pure <Popup>', () => {
    it('contains an <Overlay>', () => {
        const wrapper = shallow(<PurePopup message="foo" />);

        expect(wrapper.find(Overlay).exists()).toBeTruthy();
    });

    it('renders a string message with <PopupMessage>', () => {
        const wrapper = shallow(<PurePopup message="foo" />);

        expect(wrapper.find(PopupMessage).exists()).toBeTruthy();
        expect(wrapper.find(PopupMessage).prop('text')).toBe('foo');
    });

    it('takes a valid element for message prop', () => {
        const label = <TextLabel data-target basic="Foo" aside="bar" />;
        const wrapper = shallow(<PurePopup message={label} />);

        expect(wrapper.find(PopupMessage).exists()).toBeFalsy();
        expect(wrapper.find('[data-target]').exists()).toBeTruthy();
    });

    it('renders a string icon with <PopupIcon>', () => {
        const wrapper = shallow(<PurePopup icon="success" />);

        expect(wrapper.find(PopupIcon).exists()).toBeTruthy();
        expect(wrapper.find(PopupIcon).prop('type')).toBe('success');
    });

    it('takes a valid element for icon prop', () => {
        const icon = <Icon data-target type="success" />;
        const wrapper = shallow(<PurePopup icon={icon} />);

        expect(wrapper.find(PopupIcon).exists()).toBeFalsy();
        expect(wrapper.find('[data-target]').exists()).toBeTruthy();
    });

    it('renders buttons with <PopupButton> in a buttons-group section when specified', () => {
        const buttons = [
            <Button key="a" basic="Label A" />,
            <Button key="b" basic="Label B" />,
        ];
        const wrapper = shallow(<PurePopup message="foo" />);
        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).exists()).toBeFalsy();

        wrapper.setProps({ buttons });
        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).exists()).toBeTruthy();

        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).children()).toHaveLength(2);
        expect(wrapper.find(`.${POPUP_BEM.buttonsGroup}`).containsAllMatchingElements([
            <PopupButton basic="Label A" />,
            <PopupButton basic="Label B" />,
        ])).toBeTruthy();
    });
});

describe('<PopupIcon>', () => {
    it('returns a pre-configured <Icon> of given type', () => {
        const wrapper = shallow(<PopupIcon type="foo" />);
        expect(wrapper.matchesElement(<Icon large type="foo" />)).toBeTruthy();
    });
});

describe('<PopupMessage>', () => {
    it('returns a pre-configured <TextLabel> of given text', () => {
        const wrapper = shallow(<PopupMessage text="foo" />);
        expect(wrapper.matchesElement(<TextLabel align="center" basic="foo" />)).toBeTruthy();
    });
});

describe('<PopupButton>', () => {
    it('returns a pre-configured <Button> extending given props', () => {
        const wrapper = shallow(<PopupButton basic="foo" aside="bar" />);
        expect(wrapper.matchesElement(
            <Button
                minified={false}
                align="center"
                basic="foo"
                aside="bar" />
        )).toBeTruthy();
    });

    it('mixes className with BEM class from Popup', () => {
        const wrapper = shallow(<PopupButton basic="foo" className="bar" />);

        expect(wrapper.hasClass(POPUP_BEM.button.toString()));
        expect(wrapper.hasClass('bar'));
    });
});
<|endoftext|>


<commit_before>/**
 * Main App Controller for the Angular Material Starter App
 * @param UsersDataService
 * @param $mdSidenav
 * @constructor
 */
function EthereumService($q) {

    var self = this;

    self.abi = [ { "constant": true, "inputs": [], "name": "getRequestCount", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "serial", "type": "string" } ], "name": "getCustomer", "outputs": [ { "name": "", "type": "address", "value": "0x0000000000000000000000000000000000000000" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "id", "type": "uint256" } ], "name": "getClaim", "outputs": [ { "name": "", "type": "address", "value": "0x0000000000000000000000000000000000000000" }, { "name": "", "type": "uint256", "value": "0" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "serial", "type": "string" }, { "name": "amount", "type": "uint256" } ], "name": "claimWaranty", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "contractAddress", "type": "address" } ], "name": "updateCalculator", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "getClaimCount", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "serial", "type": "string" } ], "name": "getEndDate", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "id", "type": "uint256" } ], "name": "getRequest", "outputs": [ { "name": "", "type": "uint256", "value": "0" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "address", "value": "0x0000000000000000000000000000000000000000" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "uint256", "value": "0" }, { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "serial", "type": "string" } ], "name": "isWarrantyValid", "outputs": [ { "name": "", "type": "bool", "value": true } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "serial", "type": "string" }, { "name": "customer", "type": "address" }, { "name": "endDate", "type": "uint256" }, { "name": "price", "type": "uint256" } ], "name": "requestWarranty", "outputs": [], "payable": false, "type": "function" }, { "inputs": [], "type": "constructor" } ];
    self.dappId = "epam.hackathon";

    self.contractAddress = "0xC27a02556661134ea38A2FdC82906D855842E4C6";
    self.walletBar = new WalletBar({
        containerName: '#signInId',
        dappNamespace: self.dappId,
        blockchain: "morden"
    });

    self.web3 = new Web3();
    self.WarrantyContract;
    self.waitForWallet = self.walletBar.applyHook(self.web3)
        .then(function () {
            self.WarrantyContract = self.web3.eth.contract(self.abi).at(self.contractAddress);
            return self.WarrantyContract;
        })
        .catch(function (err) {
            console.log(err);
        });

    function prepareForTransaction() {
        var account = self.walletBar.getCurrentAccount(); // get account selected in wallet bar
        if (!account) return alert("You must log in to transact");
        self.walletBar.createSecureSigner();
        return account;
    }

    self.getInfo = function (serial) {
        return self.waitForWallet.then(function () {
            return $q.all({
                isWarrantyValid: self.isWarrantyValid(serial),
                customer: self.getCustomer(serial),
                warrantyEndDate: self.getWarrantyEndDate(serial)
            });
        });
    }

    self.getReportData = function (month) {
        return $q.all({
            requests: self.getRequestCount(),
            claims: self.getClaimCount()
        }).then(function (counts) {
            var getClaims = [];
            for (var i = 0; i < counts.claims; i++) {
                getClaims.push(self.WarrantyContract.getClaim(idx, function (err, result) {
                        if (err) {
                            defer.reject(err);
                        } else {
                            defer.resolve(result);
                        }
                    })
                )
            }
            var getRequests = [];
            for (var i = 0; i < counts.requests; i++) {
                getClaims.push(self.WarrantyContract.getRequest(idx, function (err, result) {
                        if (err) {
                            defer.reject(err);
                        } else {
                            defer.resolve(result);
                        }
                    })
                )
            }
            return $q.all({
                claims: getClaims,
                requests: getRequests
            });
        }).then(function(results){
            var report = "productType,productName,serial,pricePaid,claimDate,claimAmount,claimantId\n";
            results.claims.forEach(function (claim) {
                report += "," //productType
                report += "," //productName
                report += claim.serial + "," //productSerial
            });
            return $q(function (resolve, reject) {
                resolve(report);
            });
        });

    }

    self.isWarrantyValid = function (serial) {
        console.log('is warranty valid');
        var defer = $q.defer();

        self.WarrantyContract.isWarrantyValid(serial, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getCustomer = function (serial) {
        var defer = $q.defer();

        self.WarrantyContract.getCustomer(serial, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getRequestCount = function () {
        var defer = $q.defer();

        self.WarrantyContract.getRequestCount(function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getClaimCount = function () {
        var defer = $q.defer();

        self.WarrantyContract.getClaimCount(function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getRequest = function (idx) {
        var defer = $q.defer();

        self.WarrantyContract.getRequest(idx, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getClaim = function (idx) {
        var defer = $q.defer();

        self.WarrantyContract.getClaim(idx, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getWarrantyEndDate = function (serial) {
        var defer = $q.defer();

        self.WarrantyContract.getEndDate(serial, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.requestWarranty = function (serial, owner, endDate) {
        var defer = $q.defer();
        var account = prepareForTransaction();
        self.WarrantyContract.requestWarranty(serial, owner, endDate.getTime(), {from: account}, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    return self;
}

export default ['$q', EthereumService];
<commit_msg>update<commit_after>/**
 * Main App Controller for the Angular Material Starter App
 * @param UsersDataService
 * @param $mdSidenav
 * @constructor
 */
function EthereumService($q) {

    var self = this;

    self.abi = [ { "constant": true, "inputs": [], "name": "getRequestCount", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "serial", "type": "string" } ], "name": "getCustomer", "outputs": [ { "name": "", "type": "address", "value": "0x0000000000000000000000000000000000000000" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "id", "type": "uint256" } ], "name": "getClaim", "outputs": [ { "name": "", "type": "address", "value": "0x0000000000000000000000000000000000000000" }, { "name": "", "type": "uint256", "value": "0" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "serial", "type": "string" }, { "name": "amount", "type": "uint256" } ], "name": "claimWaranty", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "contractAddress", "type": "address" } ], "name": "updateCalculator", "outputs": [], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "getClaimCount", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "serial", "type": "string" } ], "name": "getEndDate", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "id", "type": "uint256" } ], "name": "getRequest", "outputs": [ { "name": "", "type": "uint256", "value": "0" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "address", "value": "0x0000000000000000000000000000000000000000" }, { "name": "", "type": "string", "value": "" }, { "name": "", "type": "uint256", "value": "0" }, { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "serial", "type": "string" } ], "name": "isWarrantyValid", "outputs": [ { "name": "", "type": "bool", "value": true } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "serial", "type": "string" }, { "name": "customer", "type": "address" }, { "name": "endDate", "type": "uint256" }, { "name": "price", "type": "uint256" } ], "name": "requestWarranty", "outputs": [], "payable": false, "type": "function" }, { "inputs": [], "type": "constructor" } ];
    self.dappId = "epam.hackathon";

    self.contractAddress = "0xC27a02556661134ea38A2FdC82906D855842E4C6";
    self.walletBar = new WalletBar({
        containerName: '#signInId',
        dappNamespace: self.dappId,
        blockchain: "morden"
    });

    self.web3 = new Web3();
    self.WarrantyContract;
    self.waitForWallet = self.walletBar.applyHook(self.web3)
        .then(function () {
            self.WarrantyContract = self.web3.eth.contract(self.abi).at(self.contractAddress);
            return self.WarrantyContract;
        })
        .catch(function (err) {
            console.log(err);
        });

    function prepareForTransaction() {
        var account = self.walletBar.getCurrentAccount(); // get account selected in wallet bar
        if (!account) return alert("You must log in to transact");
        self.walletBar.createSecureSigner();
        return account;
    }

    self.getInfo = function (serial) {
        return self.waitForWallet.then(function () {
            return $q.all({
                isWarrantyValid: self.isWarrantyValid(serial),
                customer: self.getCustomer(serial),
                warrantyEndDate: self.getWarrantyEndDate(serial)
            });
        });
    }

    self.getReportData = function (month) {
        return $q.all({
            requests: self.getRequestCount(),
            claims: self.getClaimCount()
        }).then(function (counts) {
            var getClaims = [];
            for (var i = 0; i < counts.claims; i++) {
                getClaims.push(self.WarrantyContract.getClaim(idx, function (err, result) {
                        if (err) {
                            defer.reject(err);
                        } else {
                            defer.resolve(result);
                        }
                    })
                )
            }
            var getRequests = [];
            for (var i = 0; i < counts.requests; i++) {
                getClaims.push(self.WarrantyContract.getRequest(idx, function (err, result) {
                        if (err) {
                            defer.reject(err);
                        } else {
                            defer.resolve(result);
                        }
                    })
                )
            }
            return $q.all({
                claims: getClaims,
                requests: getRequests
            });
        }).then(function(results){
            var report = "productType,productName,serial,pricePaid,claimDate,claimAmount,claimantId\n";
            results.claims.forEach(function (claim) {
                report += "," //productType
                report += "," //productName
                report += claim.serial + "," //productSerial
            });
            return $q(function (resolve, reject) {
                resolve(report);
            });
        });

    }

    self.isWarrantyValid = function (serial) {
        console.log('is warranty valid');
        var defer = $q.defer();

        self.WarrantyContract.isWarrantyValid(serial, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getCustomer = function (serial) {
        var defer = $q.defer();

        self.WarrantyContract.getCustomer(serial, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getRequestCount = function () {
        var defer = $q.defer();

        self.WarrantyContract.getRequestCount(function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getClaimCount = function () {
        var defer = $q.defer();

        self.WarrantyContract.getClaimCount(function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getRequest = function (idx) {
        var defer = $q.defer();

        self.WarrantyContract.getRequest(idx, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getClaim = function (idx) {
        var defer = $q.defer();

        self.WarrantyContract.getClaim(idx, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.getWarrantyEndDate = function (serial) {
        var defer = $q.defer();

        self.WarrantyContract.getEndDate(serial, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    self.requestWarranty = function (serial, owner, endDate) {
        var defer = $q.defer();
        var account = prepareForTransaction();
        self.WarrantyContract.requestWarranty(serial, owner, endDate.getTime() / 1000, {from: account}, function (err, result) {
            if (err) {
                defer.reject(err);
            } else {
                defer.resolve(result);
            }
        });

        return defer.promise;
    }

    return self;
}

export default ['$q', EthereumService];
<|endoftext|>


<commit_before>import { System } from '../System';
import { RenderTexturePool } from '../renderTexture/RenderTexturePool';
import { Quad } from '../utils/Quad';
import { QuadUv } from '../utils/QuadUv';
import { Rectangle, Matrix } from '@pixi/math';
import { UniformGroup } from '../shader/UniformGroup';
import { DRAW_MODES } from '@pixi/constants';

/**
 * System plugin to the renderer to manage filter states.
 *
 * @class
 * @private
 */
class FilterState
{
    constructor()
    {
        this.renderTexture = null;

        /**
         * Target of the filters
         * We store for case when custom filter wants to know the element it was applied on
         * @member {PIXI.DisplayObject}
         * @private
         */
        this.target = null;

        /**
         * Compatibility with PixiJS v4 filters
         * @member {boolean}
         * @default false
         * @private
         */
        this.legacy = false;

        /**
         * Resolution of filters
         * @member {number}
         * @default 1
         * @private
         */
        this.resolution = 1;

        // next three fields are created only for root
        // re-assigned for everything else

        /**
         * Source frame
         * @member {PIXI.Rectangle}
         * @private
         */
        this.sourceFrame = new Rectangle();

        /**
         * Destination frame
         * @member {PIXI.Rectangle}
         * @private
         */
        this.destinationFrame = new Rectangle();

        /**
         * Collection of filters
         * @member {PIXI.Filter[]}
         * @private
         */
        this.filters = [];
    }

    /**
     * clears the state
     * @private
     */
    clear()
    {
        this.target = null;
        this.filters = null;
        this.renderTexture = null;
    }
}

/**
 * System plugin to the renderer to manage the filters.
 *
 * @class
 * @memberof PIXI.systems
 * @extends PIXI.System
 */
export class FilterSystem extends System
{
    /**
     * @param {PIXI.Renderer} renderer - The renderer this System works for.
     */
    constructor(renderer)
    {
        super(renderer);

        /**
         * List of filters for the FilterSystem
         * @member {Object[]}
         * @readonly
         */
        this.defaultFilterStack = [{}];

        /**
         * stores a bunch of PO2 textures used for filtering
         * @member {Object}
         */
        this.texturePool = new RenderTexturePool();

        this.texturePool.setScreenSize(renderer.view);

        /**
         * a pool for storing filter states, save us creating new ones each tick
         * @member {Object[]}
         */
        this.statePool = [];

        /**
         * A very simple geometry used when drawing a filter effect to the screen
         * @member {PIXI.Quad}
         */
        this.quad = new Quad();

        /**
         * Quad UVs
         * @member {PIXI.QuadUv}
         */
        this.quadUv = new QuadUv();

        /**
         * Temporary rect for maths
         * @type {PIXI.Rectangle}
         */
        this.tempRect = new Rectangle();

        /**
         * Active state
         * @member {object}
         */
        this.activeState = {};

        /**
         * This uniform group is attached to filter uniforms when used
         * @member {PIXI.UniformGroup}
         * @property {PIXI.Rectangle} outputFrame
         * @property {Float32Array} inputSize
         * @property {Float32Array} inputPixel
         * @property {Float32Array} inputClamp
         * @property {Number} resolution
         * @property {Float32Array} filterArea
         * @property {Fload32Array} filterClamp
         */
        this.globalUniforms = new UniformGroup({
            outputFrame: this.tempRect,
            inputSize: new Float32Array(4),
            inputPixel: new Float32Array(4),
            inputClamp: new Float32Array(4),
            resolution: 1,

            // legacy variables
            filterArea: new Float32Array(4),
            filterClamp: new Float32Array(4),
        }, true);

        this._pixelsWidth = renderer.view.width;
        this._pixelsHeight = renderer.view.height;
    }

    /**
     * Adds a new filter to the System.
     *
     * @param {PIXI.DisplayObject} target - The target of the filter to render.
     * @param {PIXI.Filter[]} filters - The filters to apply.
     */
    push(target, filters)
    {
        const renderer = this.renderer;
        const filterStack = this.defaultFilterStack;
        const state = this.statePool.pop() || new FilterState();

        let resolution = filters[0].resolution;
        let padding = filters[0].padding;
        let autoFit = filters[0].autoFit;
        let legacy = filters[0].legacy;

        for (let i = 1; i < filters.length; i++)
        {
            const filter =  filters[i];

            // lets use the lowest resolution..
            resolution = Math.min(resolution, filter.resolution);
            // and the largest amount of padding!
            padding = Math.max(padding, filter.padding);
            // only auto fit if all filters are autofit
            autoFit = autoFit || filter.autoFit;

            legacy = legacy || filter.legacy;
        }

        if (filterStack.length === 1)
        {
            this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current;
        }

        filterStack.push(state);

        state.resolution = resolution;

        state.legacy = legacy;

        state.target = target;

        state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true));

        state.sourceFrame.pad(padding);
        if (autoFit)
        {
            state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame);
        }

        // round to whole number based on resolution
        state.sourceFrame.ceil(resolution);

        state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution);
        state.filters = filters;

        state.destinationFrame.width = state.renderTexture.width;
        state.destinationFrame.height = state.renderTexture.height;

        state.renderTexture.filterFrame = state.sourceFrame;

        renderer.renderTexture.bind(state.renderTexture, state.sourceFrame);// /, state.destinationFrame);
        renderer.renderTexture.clear();
    }

    /**
     * Pops off the filter and applies it.
     *
     */
    pop()
    {
        const filterStack = this.defaultFilterStack;
        const state = filterStack.pop();
        const filters = state.filters;

        this.activeState = state;

        const globalUniforms = this.globalUniforms.uniforms;

        globalUniforms.outputFrame = state.sourceFrame;
        globalUniforms.resolution = state.resolution;

        const inputSize = globalUniforms.inputSize;
        const inputPixel = globalUniforms.inputPixel;
        const inputClamp = globalUniforms.inputClamp;

        inputSize[0] = state.destinationFrame.width;
        inputSize[1] = state.destinationFrame.height;
        inputSize[2] = 1.0 / inputSize[0];
        inputSize[3] = 1.0 / inputSize[1];

        inputPixel[0] = inputSize[0] * state.resolution;
        inputPixel[1] = inputSize[1] * state.resolution;
        inputPixel[2] = 1.0 / inputPixel[0];
        inputPixel[3] = 1.0 / inputPixel[1];

        inputClamp[0] = 0.5 * inputPixel[2];
        inputClamp[1] = 0.5 * inputPixel[3];
        inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]);
        inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]);

        // only update the rect if its legacy..
        if (state.legacy)
        {
            const filterArea = globalUniforms.filterArea;

            filterArea[0] = state.destinationFrame.width;
            filterArea[1] = state.destinationFrame.height;
            filterArea[2] = state.sourceFrame.x;
            filterArea[3] = state.sourceFrame.y;

            globalUniforms.filterClamp = globalUniforms.inputClamp;
        }

        this.globalUniforms.update();

        const lastState = filterStack[filterStack.length - 1];

        if (filters.length === 1)
        {
            filters[0].apply(this, state.renderTexture, lastState.renderTexture, false, state);

            this.returnFilterTexture(state.renderTexture);
        }
        else
        {
            let flip = state.renderTexture;
            let flop = this.getOptimalFilterTexture(
                flip.width,
                flip.height,
                state.resolution
            );

            flop.filterFrame = flip.filterFrame;

            let i = 0;

            for (i = 0; i < filters.length - 1; ++i)
            {
                filters[i].apply(this, flip, flop, true, state);

                const t = flip;

                flip = flop;
                flop = t;
            }

            filters[i].apply(this, flip, lastState.renderTexture, false, state);

            this.returnFilterTexture(flip);
            this.returnFilterTexture(flop);
        }

        state.clear();
        this.statePool.push(state);
    }

    /**
     * Draws a filter.
     *
     * @param {PIXI.Filter} filter - The filter to draw.
     * @param {PIXI.RenderTexture} input - The input render target.
     * @param {PIXI.RenderTexture} output - The target to output to.
     * @param {boolean} clear - Should the output be cleared before rendering to it
     */
    applyFilter(filter, input, output, clear)
    {
        const renderer = this.renderer;

        renderer.renderTexture.bind(output, output ? output.filterFrame : null);

        if (clear)
        {
            // gl.disable(gl.SCISSOR_TEST);
            renderer.renderTexture.clear();
            // gl.enable(gl.SCISSOR_TEST);
        }

        // set the uniforms..
        filter.uniforms.uSampler = input;
        filter.uniforms.filterGlobals = this.globalUniforms;

        // TODO make it so that the order of this does not matter..
        // because it does at the moment cos of global uniforms.
        // they need to get resynced

        renderer.state.set(filter.state);
        renderer.shader.bind(filter);

        if (filter.legacy)
        {
            this.quadUv.map(input._frame, input.filterFrame);

            renderer.geometry.bind(this.quadUv);
            renderer.geometry.draw(DRAW_MODES.TRIANGLES);
        }
        else
        {
            renderer.geometry.bind(this.quad);
            renderer.geometry.draw(DRAW_MODES.TRIANGLE_STRIP);
        }
    }

    /**
     * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
     *
     * Use `outputMatrix * vTextureCoord` in the shader.
     *
     * @param {PIXI.Matrix} outputMatrix - The matrix to output to.
     * @param {PIXI.Sprite} sprite - The sprite to map to.
     * @return {PIXI.Matrix} The mapped matrix.
     */
    calculateSpriteMatrix(outputMatrix, sprite)
    {
        const { sourceFrame, destinationFrame } = this.activeState;
        const { orig } = sprite._texture;
        const mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0,
            destinationFrame.height, sourceFrame.x, sourceFrame.y);
        const worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX);

        worldTransform.invert();
        mappedMatrix.prepend(worldTransform);
        mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height);
        mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y);

        return mappedMatrix;
    }

    /**
     * Destroys this Filter System.
     */
    destroy()
    {
        // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem
        this.texturePool.clear(false);
    }

    /**
     * Gets a Power-of-Two render texture or fullScreen texture
     *
     * @protected
     * @param {number} minWidth - The minimum width of the render texture in real pixels.
     * @param {number} minHeight - The minimum height of the render texture in real pixels.
     * @param {number} [resolution=1] - The resolution of the render texture.
     * @return {PIXI.RenderTexture} The new render texture.
     */
    getOptimalFilterTexture(minWidth, minHeight, resolution = 1)
    {
        return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution);
    }

    /**
     * Gets extra render texture to use inside current filter
     * To be compliant with older filters, you can use params in any order
     *
     * @param {PIXI.RenderTexture} [input] renderTexture from which size and resolution will be copied
     * @param {number} [resolution] override resolution of the renderTexture
     * @returns {PIXI.RenderTexture}
     */
    getFilterTexture(input, resolution)
    {
        if (typeof input === 'number')
        {
            const swap = input;

            input = resolution;
            resolution = swap;
        }

        input = input || this.activeState.renderTexture;

        const filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution);

        filterTexture.filterFrame = input.filterFrame;

        return filterTexture;
    }

    /**
     * Frees a render texture back into the pool.
     *
     * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free
     */
    returnFilterTexture(renderTexture)
    {
        this.texturePool.returnTexture(renderTexture);
    }

    /**
     * Empties the texture pool.
     */
    emptyPool()
    {
        this.texturePool.clear(true);
    }

    /**
     * calls `texturePool.resize()`, affects fullScreen renderTextures
     */
    resize()
    {
        this.texturePool.setScreenSize(this.renderer.view);
    }
}
<commit_msg>Fix filters to sum padding instead of max padding (#6520)<commit_after>import { System } from '../System';
import { RenderTexturePool } from '../renderTexture/RenderTexturePool';
import { Quad } from '../utils/Quad';
import { QuadUv } from '../utils/QuadUv';
import { Rectangle, Matrix } from '@pixi/math';
import { UniformGroup } from '../shader/UniformGroup';
import { DRAW_MODES } from '@pixi/constants';

/**
 * System plugin to the renderer to manage filter states.
 *
 * @class
 * @private
 */
class FilterState
{
    constructor()
    {
        this.renderTexture = null;

        /**
         * Target of the filters
         * We store for case when custom filter wants to know the element it was applied on
         * @member {PIXI.DisplayObject}
         * @private
         */
        this.target = null;

        /**
         * Compatibility with PixiJS v4 filters
         * @member {boolean}
         * @default false
         * @private
         */
        this.legacy = false;

        /**
         * Resolution of filters
         * @member {number}
         * @default 1
         * @private
         */
        this.resolution = 1;

        // next three fields are created only for root
        // re-assigned for everything else

        /**
         * Source frame
         * @member {PIXI.Rectangle}
         * @private
         */
        this.sourceFrame = new Rectangle();

        /**
         * Destination frame
         * @member {PIXI.Rectangle}
         * @private
         */
        this.destinationFrame = new Rectangle();

        /**
         * Collection of filters
         * @member {PIXI.Filter[]}
         * @private
         */
        this.filters = [];
    }

    /**
     * clears the state
     * @private
     */
    clear()
    {
        this.target = null;
        this.filters = null;
        this.renderTexture = null;
    }
}

/**
 * System plugin to the renderer to manage the filters.
 *
 * @class
 * @memberof PIXI.systems
 * @extends PIXI.System
 */
export class FilterSystem extends System
{
    /**
     * @param {PIXI.Renderer} renderer - The renderer this System works for.
     */
    constructor(renderer)
    {
        super(renderer);

        /**
         * List of filters for the FilterSystem
         * @member {Object[]}
         * @readonly
         */
        this.defaultFilterStack = [{}];

        /**
         * stores a bunch of PO2 textures used for filtering
         * @member {Object}
         */
        this.texturePool = new RenderTexturePool();

        this.texturePool.setScreenSize(renderer.view);

        /**
         * a pool for storing filter states, save us creating new ones each tick
         * @member {Object[]}
         */
        this.statePool = [];

        /**
         * A very simple geometry used when drawing a filter effect to the screen
         * @member {PIXI.Quad}
         */
        this.quad = new Quad();

        /**
         * Quad UVs
         * @member {PIXI.QuadUv}
         */
        this.quadUv = new QuadUv();

        /**
         * Temporary rect for maths
         * @type {PIXI.Rectangle}
         */
        this.tempRect = new Rectangle();

        /**
         * Active state
         * @member {object}
         */
        this.activeState = {};

        /**
         * This uniform group is attached to filter uniforms when used
         * @member {PIXI.UniformGroup}
         * @property {PIXI.Rectangle} outputFrame
         * @property {Float32Array} inputSize
         * @property {Float32Array} inputPixel
         * @property {Float32Array} inputClamp
         * @property {Number} resolution
         * @property {Float32Array} filterArea
         * @property {Fload32Array} filterClamp
         */
        this.globalUniforms = new UniformGroup({
            outputFrame: this.tempRect,
            inputSize: new Float32Array(4),
            inputPixel: new Float32Array(4),
            inputClamp: new Float32Array(4),
            resolution: 1,

            // legacy variables
            filterArea: new Float32Array(4),
            filterClamp: new Float32Array(4),
        }, true);

        /**
         * Whether to clear output renderTexture in AUTO/BLIT mode. See {@link PIXI.CLEAR_MODES}
         * @member {boolean}
         */
        this.forceClear = false;

        /**
         * Old padding behavior is to use the max amount instead of sum padding.
         * Use this flag if you need the old behavior.
         * @member {boolean}
         * @default false
         */
        this.useMaxPadding = false;
    }

    /**
     * Adds a new filter to the System.
     *
     * @param {PIXI.DisplayObject} target - The target of the filter to render.
     * @param {PIXI.Filter[]} filters - The filters to apply.
     */
    push(target, filters)
    {
        const renderer = this.renderer;
        const filterStack = this.defaultFilterStack;
        const state = this.statePool.pop() || new FilterState();

        let resolution = filters[0].resolution;
        let padding = filters[0].padding;
        let autoFit = filters[0].autoFit;
        let legacy = filters[0].legacy;

        for (let i = 1; i < filters.length; i++)
        {
            const filter =  filters[i];

            // lets use the lowest resolution..
            resolution = Math.min(resolution, filter.resolution);
            // figure out the padding required for filters
            padding = this.useMaxPadding
                // old behavior: use largest amount of padding!
                ? Math.max(padding, filter.padding)
                // new behavior: sum the padding
                : padding + filter.padding;
            // only auto fit if all filters are autofit
            autoFit = autoFit || filter.autoFit;

            legacy = legacy || filter.legacy;
        }

        if (filterStack.length === 1)
        {
            this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current;
        }

        filterStack.push(state);

        state.resolution = resolution;

        state.legacy = legacy;

        state.target = target;

        state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true));

        state.sourceFrame.pad(padding);
        if (autoFit)
        {
            state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame);
        }

        // round to whole number based on resolution
        state.sourceFrame.ceil(resolution);

        state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution);
        state.filters = filters;

        state.destinationFrame.width = state.renderTexture.width;
        state.destinationFrame.height = state.renderTexture.height;

        state.renderTexture.filterFrame = state.sourceFrame;

        renderer.renderTexture.bind(state.renderTexture, state.sourceFrame);// /, state.destinationFrame);
        renderer.renderTexture.clear();
    }

    /**
     * Pops off the filter and applies it.
     *
     */
    pop()
    {
        const filterStack = this.defaultFilterStack;
        const state = filterStack.pop();
        const filters = state.filters;

        this.activeState = state;

        const globalUniforms = this.globalUniforms.uniforms;

        globalUniforms.outputFrame = state.sourceFrame;
        globalUniforms.resolution = state.resolution;

        const inputSize = globalUniforms.inputSize;
        const inputPixel = globalUniforms.inputPixel;
        const inputClamp = globalUniforms.inputClamp;

        inputSize[0] = state.destinationFrame.width;
        inputSize[1] = state.destinationFrame.height;
        inputSize[2] = 1.0 / inputSize[0];
        inputSize[3] = 1.0 / inputSize[1];

        inputPixel[0] = inputSize[0] * state.resolution;
        inputPixel[1] = inputSize[1] * state.resolution;
        inputPixel[2] = 1.0 / inputPixel[0];
        inputPixel[3] = 1.0 / inputPixel[1];

        inputClamp[0] = 0.5 * inputPixel[2];
        inputClamp[1] = 0.5 * inputPixel[3];
        inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]);
        inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]);

        // only update the rect if its legacy..
        if (state.legacy)
        {
            const filterArea = globalUniforms.filterArea;

            filterArea[0] = state.destinationFrame.width;
            filterArea[1] = state.destinationFrame.height;
            filterArea[2] = state.sourceFrame.x;
            filterArea[3] = state.sourceFrame.y;

            globalUniforms.filterClamp = globalUniforms.inputClamp;
        }

        this.globalUniforms.update();

        const lastState = filterStack[filterStack.length - 1];

        if (filters.length === 1)
        {
            filters[0].apply(this, state.renderTexture, lastState.renderTexture, false, state);

            this.returnFilterTexture(state.renderTexture);
        }
        else
        {
            let flip = state.renderTexture;
            let flop = this.getOptimalFilterTexture(
                flip.width,
                flip.height,
                state.resolution
            );

            flop.filterFrame = flip.filterFrame;

            let i = 0;

            for (i = 0; i < filters.length - 1; ++i)
            {
                filters[i].apply(this, flip, flop, true, state);

                const t = flip;

                flip = flop;
                flop = t;
            }

            filters[i].apply(this, flip, lastState.renderTexture, false, state);

            this.returnFilterTexture(flip);
            this.returnFilterTexture(flop);
        }

        state.clear();
        this.statePool.push(state);
    }

    /**
     * Draws a filter.
     *
     * @param {PIXI.Filter} filter - The filter to draw.
     * @param {PIXI.RenderTexture} input - The input render target.
     * @param {PIXI.RenderTexture} output - The target to output to.
     * @param {boolean} clear - Should the output be cleared before rendering to it
     */
    applyFilter(filter, input, output, clear)
    {
        const renderer = this.renderer;

        renderer.renderTexture.bind(output, output ? output.filterFrame : null);

        if (clear)
        {
            // gl.disable(gl.SCISSOR_TEST);
            renderer.renderTexture.clear();
            // gl.enable(gl.SCISSOR_TEST);
        }

        // set the uniforms..
        filter.uniforms.uSampler = input;
        filter.uniforms.filterGlobals = this.globalUniforms;

        // TODO make it so that the order of this does not matter..
        // because it does at the moment cos of global uniforms.
        // they need to get resynced

        renderer.state.set(filter.state);
        renderer.shader.bind(filter);

        if (filter.legacy)
        {
            this.quadUv.map(input._frame, input.filterFrame);

            renderer.geometry.bind(this.quadUv);
            renderer.geometry.draw(DRAW_MODES.TRIANGLES);
        }
        else
        {
            renderer.geometry.bind(this.quad);
            renderer.geometry.draw(DRAW_MODES.TRIANGLE_STRIP);
        }
    }

    /**
     * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
     *
     * Use `outputMatrix * vTextureCoord` in the shader.
     *
     * @param {PIXI.Matrix} outputMatrix - The matrix to output to.
     * @param {PIXI.Sprite} sprite - The sprite to map to.
     * @return {PIXI.Matrix} The mapped matrix.
     */
    calculateSpriteMatrix(outputMatrix, sprite)
    {
        const { sourceFrame, destinationFrame } = this.activeState;
        const { orig } = sprite._texture;
        const mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0,
            destinationFrame.height, sourceFrame.x, sourceFrame.y);
        const worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX);

        worldTransform.invert();
        mappedMatrix.prepend(worldTransform);
        mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height);
        mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y);

        return mappedMatrix;
    }

    /**
     * Destroys this Filter System.
     */
    destroy()
    {
        // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem
        this.texturePool.clear(false);
    }

    /**
     * Gets a Power-of-Two render texture or fullScreen texture
     *
     * @protected
     * @param {number} minWidth - The minimum width of the render texture in real pixels.
     * @param {number} minHeight - The minimum height of the render texture in real pixels.
     * @param {number} [resolution=1] - The resolution of the render texture.
     * @return {PIXI.RenderTexture} The new render texture.
     */
    getOptimalFilterTexture(minWidth, minHeight, resolution = 1)
    {
        return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution);
    }

    /**
     * Gets extra render texture to use inside current filter
     * To be compliant with older filters, you can use params in any order
     *
     * @param {PIXI.RenderTexture} [input] renderTexture from which size and resolution will be copied
     * @param {number} [resolution] override resolution of the renderTexture
     * @returns {PIXI.RenderTexture}
     */
    getFilterTexture(input, resolution)
    {
        if (typeof input === 'number')
        {
            const swap = input;

            input = resolution;
            resolution = swap;
        }

        input = input || this.activeState.renderTexture;

        const filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution);

        filterTexture.filterFrame = input.filterFrame;

        return filterTexture;
    }

    /**
     * Frees a render texture back into the pool.
     *
     * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free
     */
    returnFilterTexture(renderTexture)
    {
        this.texturePool.returnTexture(renderTexture);
    }

    /**
     * Empties the texture pool.
     */
    emptyPool()
    {
        this.texturePool.clear(true);
    }

    /**
     * calls `texturePool.resize()`, affects fullScreen renderTextures
     */
    resize()
    {
        this.texturePool.setScreenSize(this.renderer.view);
    }
}
<|endoftext|>


<commit_before>const { League } = require('../model/postgresDB');

const leagueController = {};
leagueController.allLeagues = (req, res) = {
	League.findAll({})
				.then(data => res.end(data))
				.catch(err => res.statusCode(404).end());
}

leagueController.addLeague = (req, res) => {
  const { name } = req.body;
  League.create({ name })
       .then(() =>  res.end())
       .catch( err => console.error(err));
};

leagueController.findLeague = (req, res) => {
  const { name } = req.body;
  League.findOne({ name })
        .then(() => res.send('FOUND LEAGUE'))
        .catch(() => res.end(404));
}

module.exports = leagueController;
<commit_msg>Clean leaguecontroller whitespace, fix incorrectly named methods<commit_after>const { League } = require('../model/postgresDB');

const leagueController = {};

leagueController.findAll = (req, res) => {
League.findAll({})
			.then(data => res.end(data))
			.catch(err => res.statusCode(404).end());
}

leagueController.findOne = (req, res) => {
  const { name } = req.body;
  League.findOne({ name })
        .then(() => res.send('FOUND LEAGUE'))
        .catch(() => res.end(404));
}

leagueController.addLeague = (req, res) => {
  const { name } = req.body;
  League.create({ name })
       .then(() =>  res.end())
       .catch( err => console.error(err));
};

module.exports = leagueController;
<|endoftext|>


<commit_before>import { uid, BaseTextureCache, TextureCache } from '@pixi/utils';

import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '@pixi/constants';
import BufferResource from './resources/BufferResource';
import createResource from './resources/createResource';

import { settings } from '@pixi/settings';
import EventEmitter from 'eventemitter3';
import bitTwiddle from 'bit-twiddle';

export default class BaseTexture extends EventEmitter
{
    constructor(resource,
        scaleMode = settings.SCALE_MODE,
        resolution,
        width,
        height,
        format,
        type,
        mipmap = settings.MIPMAP_TEXTURES)
    {
        super();

        this.uid = uid();

        this.touched = 0;

        /**
         * The width of texture
         *
         * @member {Number}
         */
        this.width = width || -1;
        /**
         * The height of texture
         *
         * @member {Number}
         */
        this.height = height || -1;

        /**
         * The resolution / device pixel ratio of the texture
         *
         * @member {number}
         * @default 1
         */
        this.resolution = resolution || settings.RESOLUTION;

        /**
         * Whether or not the texture is a power of two, try to use power of two textures as much
         * as you can
         *
         * @private
         * @member {boolean}
         */
        this.isPowerOfTwo = false;

        /**
         * If mipmapping was used for this texture, enable and disable with enableMipmap()
         *
         * @member {Boolean}
         */
        //  TODO fix mipmapping..
        mipmap = false;
        this.mipmap = mipmap;

        /**
         * Set to true to enable pre-multiplied alpha
         *
         * @member {Boolean}
         */
        this.premultiplyAlpha = true;

        /**
         * [wrapMode description]
         * @type {number}
         */
        this.wrapMode = settings.WRAP_MODE;

        /**
         * The scale mode to apply when scaling this texture
         *
         * @member {number}
         * @default PIXI.settings.SCALE_MODE
         * @see PIXI.SCALE_MODES
         */
        this.scaleMode = scaleMode;// || settings.SCALE_MODE;

        /**
         * The pixel format of the texture. defaults to gl.RGBA
         *
         * @member {Number}
         */
        this.format = format || FORMATS.RGBA;
        this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE

        this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D

        this._glTextures = {};

        this._new = true;

        this.dirtyId = 0;

        this.valid = false;

        this.resource = null;

        if (resource)
        {
            // lets convert this to a resource..
            resource = createResource(resource);
            this.setResource(resource);
        }

        this.cacheId = null;

        this.validate();

        this.textureCacheIds = [];

        /**
         * Fired when a not-immediately-available source finishes loading.
         *
         * @protected
         * @event PIXI.BaseTexture#loaded
         * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
         */

        /**
         * Fired when a not-immediately-available source fails to load.
         *
         * @protected
         * @event PIXI.BaseTexture#error
         * @param {PIXI.BaseTexture} baseTexture - Resource errored.
         */

        /**
         * Fired when BaseTexture is updated.
         *
         * @protected
         * @event PIXI.BaseTexture#loaded
         * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
         */

        /**
         * Fired when BaseTexture is destroyed.
         *
         * @protected
         * @event PIXI.BaseTexture#error
         * @param {PIXI.BaseTexture} baseTexture - Resource errored.
         */

        /**
         * Fired when BaseTexture is updated.
         *
         * @protected
         * @event PIXI.BaseTexture#update
         * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated.
         */

        /**
         * Fired when BaseTexture is destroyed.
         *
         * @protected
         * @event PIXI.BaseTexture#dispose
         * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed.
         */
    }

    updateResolution()
    {
        const resource = this.resource;

        if (resource && resource.width !== -1 && resource.hight !== -1)
        {
            this.width = resource.width / this.resolution;
            this.height = resource.height / this.resolution;
        }
    }

    setResource(resource)
    {
        // TODO currently a resource can only be set once..

        if (this.resource)
        {
            this.resource.resourceUpdated.remove(this);
        }

        this.resource = resource;

        resource.resourceUpdated.add(this); // calls resourceUpaded

        if (resource.loaded)
        {
            this.resourceLoaded(resource);
        }

        resource.load
            .then(this.resourceLoaded.bind(this))
            .catch((reason) =>
            {
            // failed to load - maybe resource was destroyed before it loaded.
                console.warn(reason);
            });
    }

    resourceLoaded(resource)
    {
        if (this.resource === resource)
        {
            this.updateResolution();

            this.validate();

            if (this.valid)
            {
                this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight);

                // we have not swapped half way!
                this.dirtyId++;

                this.emit('loaded', this);
            }
        }
    }

    resourceUpdated()
    {
        // the resource was updated..
        this.dirtyId++;
    }

    update()
    {
        this.dirtyId++;
    }

    resize(width, height)
    {
        this.width = width;
        this.height = height;

        this.dirtyId++;
    }

    validate()
    {
        let valid = true;

        if (this.width === -1 || this.height === -1)
        {
            valid = false;
        }

        this.valid = valid;
    }

    get realWidth()
    {
        return this.width * this.resolution;
    }

    get realHeight()
    {
        return this.height * this.resolution;
    }

    /**
     * Destroys this base texture
     *
     */
    destroy()
    {
        if (this.cacheId)
        {
            delete BaseTextureCache[this.cacheId];
            delete TextureCache[this.cacheId];

            this.cacheId = null;
        }

        // remove and destroy the resource

        if (this.resource)
        {
            this.resource.destroy();
            this.resource = null;
        }

        // finally let the webGL renderer know..
        this.dispose();

        BaseTexture.removeFromCache(this);
        this.textureCacheIds = null;
    }

    /**
     * Frees the texture from WebGL memory without destroying this texture object.
     * This means you can still use the texture later which will upload it to GPU
     * memory again.
     *
     * @fires PIXI.BaseTexture#dispose
     */
    dispose()
    {
        this.emit('dispose', this);
    }

    /**
     * Helper function that creates a base texture based on the source you provide.
     * The source can be - image url, image element, canvas element.
     *
     * @static
     * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from.
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images.
     * @return {PIXI.BaseTexture} The new base texture.
     */
    static from(source, scaleMode)
    {
        let cacheId = null;

        if (typeof source === 'string')
        {
            cacheId = source;
        }
        else
        {
            if (!source._pixiId)
            {
                source._pixiId = `pixiid_${uid()}`;
            }

            cacheId = source._pixiId;
        }

        let baseTexture = BaseTextureCache[cacheId];

        if (!baseTexture)
        {
            baseTexture = new BaseTexture(source, scaleMode);
            baseTexture.cacheId = cacheId;
            BaseTexture.addToCache(baseTexture, cacheId);
        }

        return baseTexture;
    }

    static fromFloat32Array(width, height, float32Array)
    {
        float32Array = float32Array || new Float32Array(width * height * 4);

        const texture = new BaseTexture(new BufferResource(float32Array),
            SCALE_MODES.NEAREST,
            1,
            width,
            height,
            FORMATS.RGBA,
            TYPES.FLOAT);

        return texture;
    }

    static fromUint8Array(width, height, uint8Array)
    {
        uint8Array = uint8Array || new Uint8Array(width * height * 4);

        const texture = new BaseTexture(new BufferResource(uint8Array),
            SCALE_MODES.NEAREST,
            1,
            width,
            height,
            FORMATS.RGBA,
            TYPES.UNSIGNED_BYTE);

        return texture;
    }

    /**
     * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object.
     *
     * @static
     * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache.
     * @param {string} id - The id that the BaseTexture will be stored against.
     */
    static addToCache(baseTexture, id)
    {
        if (id)
        {
            if (baseTexture.textureCacheIds.indexOf(id) === -1)
            {
                baseTexture.textureCacheIds.push(id);
            }

            // @if DEV
            /* eslint-disable no-console */
            if (BaseTextureCache[id])
            {
                console.warn(`BaseTexture added to the cache with an id [${id}] that already had an entry`);
            }
            /* eslint-enable no-console */
            // @endif

            BaseTextureCache[id] = baseTexture;
        }
    }

    /**
     * Remove a BaseTexture from the global BaseTextureCache.
     *
     * @static
     * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself.
     * @return {PIXI.BaseTexture|null} The BaseTexture that was removed.
     */
    static removeFromCache(baseTexture)
    {
        if (typeof baseTexture === 'string')
        {
            const baseTextureFromCache = BaseTextureCache[baseTexture];

            if (baseTextureFromCache)
            {
                const index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);

                if (index > -1)
                {
                    baseTextureFromCache.textureCacheIds.splice(index, 1);
                }

                delete BaseTextureCache[baseTexture];

                return baseTextureFromCache;
            }
        }
        else if (baseTexture && baseTexture.textureCacheIds)
        {
            for (let i = 0; i < baseTexture.textureCacheIds.length; ++i)
            {
                delete BaseTextureCache[baseTexture.textureCacheIds[i]];
            }

            baseTexture.textureCacheIds.length = 0;

            return baseTexture;
        }

        return null;
    }
}

BaseTexture.fromFrame = BaseTexture.fromFrame;
BaseTexture.fromImage = BaseTexture.from;
BaseTexture.fromSVG = BaseTexture.from;
BaseTexture.fromCanvas = BaseTexture.from;
<commit_msg>Document caching behavior of BaseTexture.from (#4390)<commit_after>import { uid, BaseTextureCache, TextureCache } from '@pixi/utils';

import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '@pixi/constants';
import BufferResource from './resources/BufferResource';
import createResource from './resources/createResource';

import { settings } from '@pixi/settings';
import EventEmitter from 'eventemitter3';
import bitTwiddle from 'bit-twiddle';

export default class BaseTexture extends EventEmitter
{
    constructor(resource,
        scaleMode = settings.SCALE_MODE,
        resolution,
        width,
        height,
        format,
        type,
        mipmap = settings.MIPMAP_TEXTURES)
    {
        super();

        this.uid = uid();

        this.touched = 0;

        /**
         * The width of texture
         *
         * @member {Number}
         */
        this.width = width || -1;
        /**
         * The height of texture
         *
         * @member {Number}
         */
        this.height = height || -1;

        /**
         * The resolution / device pixel ratio of the texture
         *
         * @member {number}
         * @default 1
         */
        this.resolution = resolution || settings.RESOLUTION;

        /**
         * Whether or not the texture is a power of two, try to use power of two textures as much
         * as you can
         *
         * @private
         * @member {boolean}
         */
        this.isPowerOfTwo = false;

        /**
         * If mipmapping was used for this texture, enable and disable with enableMipmap()
         *
         * @member {Boolean}
         */
        //  TODO fix mipmapping..
        mipmap = false;
        this.mipmap = mipmap;

        /**
         * Set to true to enable pre-multiplied alpha
         *
         * @member {Boolean}
         */
        this.premultiplyAlpha = true;

        /**
         * [wrapMode description]
         * @type {number}
         */
        this.wrapMode = settings.WRAP_MODE;

        /**
         * The scale mode to apply when scaling this texture
         *
         * @member {number}
         * @default PIXI.settings.SCALE_MODE
         * @see PIXI.SCALE_MODES
         */
        this.scaleMode = scaleMode;// || settings.SCALE_MODE;

        /**
         * The pixel format of the texture. defaults to gl.RGBA
         *
         * @member {Number}
         */
        this.format = format || FORMATS.RGBA;
        this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE

        this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D

        this._glTextures = {};

        this._new = true;

        this.dirtyId = 0;

        this.valid = false;

        this.resource = null;

        if (resource)
        {
            // lets convert this to a resource..
            resource = createResource(resource);
            this.setResource(resource);
        }

        this.cacheId = null;

        this.validate();

        this.textureCacheIds = [];

        /**
         * Fired when a not-immediately-available source finishes loading.
         *
         * @protected
         * @event PIXI.BaseTexture#loaded
         * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
         */

        /**
         * Fired when a not-immediately-available source fails to load.
         *
         * @protected
         * @event PIXI.BaseTexture#error
         * @param {PIXI.BaseTexture} baseTexture - Resource errored.
         */

        /**
         * Fired when BaseTexture is updated.
         *
         * @protected
         * @event PIXI.BaseTexture#loaded
         * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
         */

        /**
         * Fired when BaseTexture is destroyed.
         *
         * @protected
         * @event PIXI.BaseTexture#error
         * @param {PIXI.BaseTexture} baseTexture - Resource errored.
         */

        /**
         * Fired when BaseTexture is updated.
         *
         * @protected
         * @event PIXI.BaseTexture#update
         * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated.
         */

        /**
         * Fired when BaseTexture is destroyed.
         *
         * @protected
         * @event PIXI.BaseTexture#dispose
         * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed.
         */
    }

    updateResolution()
    {
        const resource = this.resource;

        if (resource && resource.width !== -1 && resource.hight !== -1)
        {
            this.width = resource.width / this.resolution;
            this.height = resource.height / this.resolution;
        }
    }

    setResource(resource)
    {
        // TODO currently a resource can only be set once..

        if (this.resource)
        {
            this.resource.resourceUpdated.remove(this);
        }

        this.resource = resource;

        resource.resourceUpdated.add(this); // calls resourceUpaded

        if (resource.loaded)
        {
            this.resourceLoaded(resource);
        }

        resource.load
            .then(this.resourceLoaded.bind(this))
            .catch((reason) =>
            {
            // failed to load - maybe resource was destroyed before it loaded.
                console.warn(reason);
            });
    }

    resourceLoaded(resource)
    {
        if (this.resource === resource)
        {
            this.updateResolution();

            this.validate();

            if (this.valid)
            {
                this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight);

                // we have not swapped half way!
                this.dirtyId++;

                this.emit('loaded', this);
            }
        }
    }

    resourceUpdated()
    {
        // the resource was updated..
        this.dirtyId++;
    }

    update()
    {
        this.dirtyId++;
    }

    resize(width, height)
    {
        this.width = width;
        this.height = height;

        this.dirtyId++;
    }

    validate()
    {
        let valid = true;

        if (this.width === -1 || this.height === -1)
        {
            valid = false;
        }

        this.valid = valid;
    }

    get realWidth()
    {
        return this.width * this.resolution;
    }

    get realHeight()
    {
        return this.height * this.resolution;
    }

    /**
     * Destroys this base texture
     *
     */
    destroy()
    {
        if (this.cacheId)
        {
            delete BaseTextureCache[this.cacheId];
            delete TextureCache[this.cacheId];

            this.cacheId = null;
        }

        // remove and destroy the resource

        if (this.resource)
        {
            this.resource.destroy();
            this.resource = null;
        }

        // finally let the webGL renderer know..
        this.dispose();

        BaseTexture.removeFromCache(this);
        this.textureCacheIds = null;
    }

    /**
     * Frees the texture from WebGL memory without destroying this texture object.
     * This means you can still use the texture later which will upload it to GPU
     * memory again.
     *
     * @fires PIXI.BaseTexture#dispose
     */
    dispose()
    {
        this.emit('dispose', this);
    }

    /**
     * Helper function that creates a base texture based on the source you provide.
     * The source can be - image url, image element, canvas element. If the
     * source is an image url or an image element and not in the base texture
     * cache, it will be created and loaded.
     *
     * @static
     * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from.
     * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
     * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images.
     * @return {PIXI.BaseTexture} The new base texture.
     */
    static from(source, scaleMode)
    {
        let cacheId = null;

        if (typeof source === 'string')
        {
            cacheId = source;
        }
        else
        {
            if (!source._pixiId)
            {
                source._pixiId = `pixiid_${uid()}`;
            }

            cacheId = source._pixiId;
        }

        let baseTexture = BaseTextureCache[cacheId];

        if (!baseTexture)
        {
            baseTexture = new BaseTexture(source, scaleMode);
            baseTexture.cacheId = cacheId;
            BaseTexture.addToCache(baseTexture, cacheId);
        }

        return baseTexture;
    }

    static fromFloat32Array(width, height, float32Array)
    {
        float32Array = float32Array || new Float32Array(width * height * 4);

        const texture = new BaseTexture(new BufferResource(float32Array),
            SCALE_MODES.NEAREST,
            1,
            width,
            height,
            FORMATS.RGBA,
            TYPES.FLOAT);

        return texture;
    }

    static fromUint8Array(width, height, uint8Array)
    {
        uint8Array = uint8Array || new Uint8Array(width * height * 4);

        const texture = new BaseTexture(new BufferResource(uint8Array),
            SCALE_MODES.NEAREST,
            1,
            width,
            height,
            FORMATS.RGBA,
            TYPES.UNSIGNED_BYTE);

        return texture;
    }

    /**
     * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object.
     *
     * @static
     * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache.
     * @param {string} id - The id that the BaseTexture will be stored against.
     */
    static addToCache(baseTexture, id)
    {
        if (id)
        {
            if (baseTexture.textureCacheIds.indexOf(id) === -1)
            {
                baseTexture.textureCacheIds.push(id);
            }

            // @if DEV
            /* eslint-disable no-console */
            if (BaseTextureCache[id])
            {
                console.warn(`BaseTexture added to the cache with an id [${id}] that already had an entry`);
            }
            /* eslint-enable no-console */
            // @endif

            BaseTextureCache[id] = baseTexture;
        }
    }

    /**
     * Remove a BaseTexture from the global BaseTextureCache.
     *
     * @static
     * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself.
     * @return {PIXI.BaseTexture|null} The BaseTexture that was removed.
     */
    static removeFromCache(baseTexture)
    {
        if (typeof baseTexture === 'string')
        {
            const baseTextureFromCache = BaseTextureCache[baseTexture];

            if (baseTextureFromCache)
            {
                const index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);

                if (index > -1)
                {
                    baseTextureFromCache.textureCacheIds.splice(index, 1);
                }

                delete BaseTextureCache[baseTexture];

                return baseTextureFromCache;
            }
        }
        else if (baseTexture && baseTexture.textureCacheIds)
        {
            for (let i = 0; i < baseTexture.textureCacheIds.length; ++i)
            {
                delete BaseTextureCache[baseTexture.textureCacheIds[i]];
            }

            baseTexture.textureCacheIds.length = 0;

            return baseTexture;
        }

        return null;
    }
}

BaseTexture.fromFrame = BaseTexture.fromFrame;
BaseTexture.fromImage = BaseTexture.from;
BaseTexture.fromSVG = BaseTexture.from;
BaseTexture.fromCanvas = BaseTexture.from;
<|endoftext|>