<commit_before>/**
 * Created by Martin on 2015-11-19.
 */
(function () {
    'use strict';

    angular
        .module('app.Tobbe2')
        .controller('Tobbe2Controller', Tobbe2Controller);

    Tobbe2Controller.$inject = ['$scope', 'dashboardService', 'eventService', 'spServicesService', 'operationControlService'];
    /* @ngInject */
    function Tobbe2Controller($scope, dashboardService, eventService, spServicesService, operationControlService) {
        var vm = this;
        vm.widget = $scope.$parent.$parent.$parent.vm.widget; //lol what
        var service = {
            connected: false,
            controlServiceID: '',
            state: [],
            resourceTree: [],
            latestMess: {},
            connect: connect,
            sendRawDB: sendRawDB
        };
        vm.hej = 'null'
        vm.control = operationControlService;

        //functions¨
        vm.adressToRaw = adressToRaw;
        vm.parseColour = parseColour;
        vm.sendOrder = sendOrder;
        vm.sendRawDB = sendRawDB;
        activate();
        vm.placeyplaceholder = 'Chose operation'
        vm.myFunction = myFunction;
        vm.changeColor = changeColor;
        vm.activate2 = activate2;
        vm.value = 1;
        vm.debug14 = 0;
        vm.parseColourTrueFalse = parseColourTrueFalse;
        vm.searchObj = searchObj;
        vm.reset = reset;
        vm.data = {
            resMult: [
                {
                    name: 'Robot 2',
                    resource: [
                        {id: '127 18 0 1', action: 'Set at position 1', value: '#FFFFFF'},
                        {id: '127 18 0 2', action: 'Set at position 2', value: '#FFFFFF'},
                        {id: '127 18 0 3', action: 'Set at position 3', value: '#FFFFFF'},
                        {id: '127 18 0 4', action: 'Set at position 4', value: '#FFFFFF'},
                        {id: '127 18 0 5', action: 'Set at position 5', value: '#FFFFFF'},
                        {id: '127 0 5 true', action: 'Pick at set position', value: '#FFFFFF'},
                        {id: '127 0 2 true', action: 'Place at elevator 2', value: '#FFFFFF'},
                        {id: '127 0 6 true', action: 'Place at table', value: '#FFFFFF'},
                    ],
                    currVal: 'Choose operation',
                    currID: 'null',
                    image: 'images/Industry-Robot-icon.png'
                }
            ],
            resSel: [
                {
                    name: 'Elevator 1',
                    resource: [
                        {id: '135 0 0', action: 'Up', value: '#FFFFFF'},
                        {id: '135 0 1', action: 'Down', value: '#FFFFFF'}
                    ],
                    image: 'images/elevator-icon.png'
                },
                {
                    name: 'Elevator 2',
                    resource: [
                        {id: '140 0 0', action: 'Up', value: '#FFFFFF'},
                        {id: '140 0 1', action: 'Down', value: '#FFFFFF'}
                    ],
                    image: 'images/elevator-icon.png'

                },
                {
                    name: 'Flexlink',
                    resource: [
                        {id: '138 16 0', action: 'Start', value: '#FFFFFF'},
                        {id: '138 16 1', action: 'Stop', value: '#FFFFFF'}
                    ],
                    image: 'images/conveyor-icon2.png'
                },
                {
                    name: 'Robot 3',
                    resource: [
                        {id: '128 0 2', action: 'Home', value: '#FFFFFF'},
                        {id: '128 0 3', action: 'Dodge', value: '#FFFFFF'}
                    ],
                    image: 'images/Industry-Robot-icon.png'

                },
                {
                    name: 'Robot 4',
                    resource: [
                        {id: '132 0 2', action: 'Home', value: '#FFFFFF'},
                        {id: '132 0 3', action: 'Dodge', value: '#FFFFFF'}
                    ],
        image: 'images/Industry-Robot-icon.png'
                },
                {
                    name: 'Reset PLC',
                    resource: [
                        {id: '141 0 0', action: 'Set', value: '#FFFFFF'},
                        {id: '141 0 1', action: 'Mode', value: '#FFFFFF'}
                    ],
        image: 'images/plc-icon2.png'
                }
            ]/*,
            singleShow: [
                {
                    name: 'Sensor 1',
                    id: 'db hej hej',
                    value: 'false',
                    image: 'images/elevator-icon.png'
                }
            ]*/
        };

        function changeColor(circleID, colour) {
            var property = document.getElementById(circleID);
            switch (colour) {
                case 'green':
                    property.style.background = "radial-gradient(circle at 15px 15px, #5cd65c, #000)";//green
                    break;
                case 'red':
                    property.style.background = "radial-gradient(circle at 15px 15px, #ff3333, #000)";//red
                    break;
                default:
                    break;
            }
        }

        /* When the user clicks on the button,
         toggle between hiding and showing the dropdown content */
        function myFunction(something) {
            document.getElementById(something).classList.toggle("show");
        }

        // Close the dropdown menu if the user clicks outside of it
        window.onclick = function (event) {
            if (!event.target.matches('.dropbtn')) {

                var dropdowns = document.getElementsByClassName("dropdown-content");
                var i;
                for (i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        }

        function activate2(int) {
            if (int == 1)
                vm.debug14++;
            else
                vm.debug14--;
        }

        function activate() {
            $scope.$on('closeRequest', function () {
                dashboardService.closeWidget(vm.widget.id);
            });
            eventService.addListener('ServiceError', onEvent);
            eventService.addListener('Progress', onEvent);
            eventService.addListener('Response', onEvent);
        }

    function updateItems(){
      var its = _.filter(itemService.items, function(o){
        return (angular.isDefined(o.id) && angular.isDefined(service.state[o.id]))
      });
      service.itemState = [];
      _.foreach(its, function(o){
        service.itemState.push({'item': o, 'state': service.state[o.id]})
      })
    }

    function onEvent(ev){
      //console.log("control service");
      //console.log(ev);

      if (ev.isa == "Response" && ev.service == "OperationControl" && !(_.isUndefined(ev.attributes.dbs)) ) {
        ev.attributes.dbs.forEach(vm.parseColour);

      }

      if (!_.has(ev, 'reqID') || ev.reqID !== service.controlServiceID) return;

      if (_.has(ev, 'attributes.theBus')){
        if (ev.attributes.theBus === 'Connected' && ! service.connected){
          sendTo(service.latestMess, 'subscribe');
        }

        service.connected = ev.attributes.theBus === 'Connected'
      }

      if (_.has(ev, 'attributes.state')){
        service.state = ev.attributes.state;
      }
      if (_.has(ev, 'attributes.resourceTree')){
        service.resourceTree = ev.attributes.resourceTree;
      }
    }

        function sendOrder() {

            var mess = {"data": {getNext: false, "buildOrder": vm.ButtonColour.kub}};
            spServicesService.callService(spServicesService.getService("runnerService"),
                mess,
                function (resp) {
                    if (_.has(resp, 'attributes.result')) {
                        console.log("Hej" + vm.result);
                    }
                }
            )
        }

        function connect(bus, connectionSpecID, resourcesID){
            var mess = {
                'setup': {
                    'busIP': bus.ip,
                    'publishTopic': bus.publish,
                    'subscribeTopic': bus.subscribe
                }
            };
            var conn = {};
            if (angular.isDefined(connectionSpecID)){
                conn.connectionDetails = connectionSpecID
            }
            if (angular.isDefined(resourcesID)){
                conn.resources = resourcesID
            }
            mess.connection = conn;

            sendTo(mess, 'connect').then(function(repl){
                console.log("inside first connection");
                console.log(repl);
                if (messageOK(repl) && _.has(repl, 'reqID')){
                    service.controlServiceID = repl.reqID;
                }
            });
            service.latestMess = mess;
        }

        function parseColour(item, index) {
            if (!(_.isUndefined(item.address))) {
                var theKey = adressToRaw(item.address);
                var theValue = item.value;

                if (theKey === '138 16 2') {
                    console.log(theValue)
                    theKey = '138 16 0';
                    searchObj( vm.data, theKey, theValue);
                    theKey = '138 16 1';
                    searchObj( vm.data, theKey, !theValue);
                }

                else searchObj( vm.data, theKey, theValue );
                //var oki = _.find(vm.data.resSel, hejhej);

            }
        }
        //function hejhej(param1){
        //    return !_.isUndefined(_.find(param1.resource, function(r) {return r.id == '135 0 1 true';}));
        //}

        function adressToRaw(params) {
            return params.db + ' ' + params.byte + ' ' + params.bit;
        }

        function searchObj( obj, keyToFind, data ){

            for( var key in obj ) {

                if( typeof obj[key] === 'object' ){
                    searchObj( obj[key], keyToFind, data );
                }

                if( obj[key] === keyToFind ){
                    obj.value = parseColourTrueFalse(data);
                }

            }

        }

        function reset() {
            vm.control.reset();
        }

        function parseColourTrueFalse(value) {
            if (value === true) return '#99e699';
            else if (value === false) return '#ff6666';
            else return '#FFFFFF';
        }

        function sendRawDB(params) {
            var mess = service.latestMess;
            console.log(params);
            mess.command = {
                'commandType': 'raw',
                'raw': params
            };
            spServicesService.callService('OperationControl',{'data':mess});
        }
    }
})();

<commit_msg>forgot removing stuff from debug<commit_after>/**
 * Created by Martin on 2015-11-19.
 */
(function () {
    'use strict';

    angular
        .module('app.Tobbe2')
        .controller('Tobbe2Controller', Tobbe2Controller);

    Tobbe2Controller.$inject = ['$scope', 'dashboardService', 'eventService', 'spServicesService', 'operationControlService'];
    /* @ngInject */
    function Tobbe2Controller($scope, dashboardService, eventService, spServicesService, operationControlService) {
        var vm = this;
        vm.widget = $scope.$parent.$parent.$parent.vm.widget; //lol what
        var service = {
            connected: false,
            controlServiceID: '',
            state: [],
            resourceTree: [],
            latestMess: {},
            connect: connect,
            sendRawDB: sendRawDB
        };
        vm.hej = 'null'
        vm.control = operationControlService;

        //functions¨
        vm.adressToRaw = adressToRaw;
        vm.parseColour = parseColour;
        vm.sendOrder = sendOrder;
        vm.sendRawDB = sendRawDB;
        activate();
        vm.placeyplaceholder = 'Chose operation'
        vm.myFunction = myFunction;
        vm.changeColor = changeColor;
        vm.activate2 = activate2;
        vm.value = 1;
        vm.debug14 = 0;
        vm.parseColourTrueFalse = parseColourTrueFalse;
        vm.searchObj = searchObj;
        vm.reset = reset;
        vm.data = {
            resMult: [
                {
                    name: 'Robot 2',
                    resource: [
                        {id: '127 18 0 1', action: 'Set at position 1', value: '#FFFFFF'},
                        {id: '127 18 0 2', action: 'Set at position 2', value: '#FFFFFF'},
                        {id: '127 18 0 3', action: 'Set at position 3', value: '#FFFFFF'},
                        {id: '127 18 0 4', action: 'Set at position 4', value: '#FFFFFF'},
                        {id: '127 18 0 5', action: 'Set at position 5', value: '#FFFFFF'},
                        {id: '127 0 5 true', action: 'Pick at set position', value: '#FFFFFF'},
                        {id: '127 0 2 true', action: 'Place at elevator 2', value: '#FFFFFF'},
                        {id: '127 0 6 true', action: 'Place at table', value: '#FFFFFF'},
                    ],
                    currVal: 'Choose operation',
                    currID: 'null',
                    image: 'images/Industry-Robot-icon.png'
                }
            ],
            resSel: [
                {
                    name: 'Elevator 1',
                    resource: [
                        {id: '135 0 0', action: 'Up', value: '#FFFFFF'},
                        {id: '135 0 1', action: 'Down', value: '#FFFFFF'}
                    ],
                    image: 'images/elevator-icon.png'
                },
                {
                    name: 'Elevator 2',
                    resource: [
                        {id: '140 0 0', action: 'Up', value: '#FFFFFF'},
                        {id: '140 0 1', action: 'Down', value: '#FFFFFF'}
                    ],
                    image: 'images/elevator-icon.png'

                },
                {
                    name: 'Flexlink',
                    resource: [
                        {id: '138 16 0', action: 'Start', value: '#FFFFFF'},
                        {id: '138 16 1', action: 'Stop', value: '#FFFFFF'}
                    ],
                    image: 'images/conveyor-icon2.png'
                },
                {
                    name: 'Robot 3',
                    resource: [
                        {id: '128 0 2', action: 'Home', value: '#FFFFFF'},
                        {id: '128 0 3', action: 'Dodge', value: '#FFFFFF'}
                    ],
                    image: 'images/Industry-Robot-icon.png'

                },
                {
                    name: 'Robot 4',
                    resource: [
                        {id: '132 0 2', action: 'Home', value: '#FFFFFF'},
                        {id: '132 0 3', action: 'Dodge', value: '#FFFFFF'}
                    ],
        image: 'images/Industry-Robot-icon.png'
                },
                {
                    name: 'Reset PLC',
                    resource: [
                        {id: '141 0 0', action: 'Set', value: '#FFFFFF'},
                        {id: '141 0 1', action: 'Mode', value: '#FFFFFF'}
                    ],
        image: 'images/plc-icon2.png'
                }
            ]/*,
            singleShow: [
                {
                    name: 'Sensor 1',
                    id: 'db hej hej',
                    value: 'false',
                    image: 'images/elevator-icon.png'
                }
            ]*/
        };

        function changeColor(circleID, colour) {
            var property = document.getElementById(circleID);
            switch (colour) {
                case 'green':
                    property.style.background = "radial-gradient(circle at 15px 15px, #5cd65c, #000)";//green
                    break;
                case 'red':
                    property.style.background = "radial-gradient(circle at 15px 15px, #ff3333, #000)";//red
                    break;
                default:
                    break;
            }
        }

        /* When the user clicks on the button,
         toggle between hiding and showing the dropdown content */
        function myFunction(something) {
            document.getElementById(something).classList.toggle("show");
        }

        // Close the dropdown menu if the user clicks outside of it
        window.onclick = function (event) {
            if (!event.target.matches('.dropbtn')) {

                var dropdowns = document.getElementsByClassName("dropdown-content");
                var i;
                for (i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        }

        function activate2(int) {
            if (int == 1)
                vm.debug14++;
            else
                vm.debug14--;
        }

        function activate() {
            $scope.$on('closeRequest', function () {
                dashboardService.closeWidget(vm.widget.id);
            });
            eventService.addListener('ServiceError', onEvent);
            eventService.addListener('Progress', onEvent);
            eventService.addListener('Response', onEvent);
        }

    function updateItems(){
      var its = _.filter(itemService.items, function(o){
        return (angular.isDefined(o.id) && angular.isDefined(service.state[o.id]))
      });
      service.itemState = [];
      _.foreach(its, function(o){
        service.itemState.push({'item': o, 'state': service.state[o.id]})
      })
    }

    function onEvent(ev){
      //console.log("control service");
      //console.log(ev);

      if (ev.isa == "Response" && ev.service == "OperationControl" && !(_.isUndefined(ev.attributes.dbs)) ) {
        ev.attributes.dbs.forEach(vm.parseColour);

      }

      if (!_.has(ev, 'reqID') || ev.reqID !== service.controlServiceID) return;

      if (_.has(ev, 'attributes.theBus')){
        if (ev.attributes.theBus === 'Connected' && ! service.connected){
          sendTo(service.latestMess, 'subscribe');
        }

        service.connected = ev.attributes.theBus === 'Connected'
      }

      if (_.has(ev, 'attributes.state')){
        service.state = ev.attributes.state;
      }
      if (_.has(ev, 'attributes.resourceTree')){
        service.resourceTree = ev.attributes.resourceTree;
      }
    }

        function sendOrder() {

            var mess = {"data": {getNext: false, "buildOrder": vm.ButtonColour.kub}};
            spServicesService.callService(spServicesService.getService("runnerService"),
                mess,
                function (resp) {
                    if (_.has(resp, 'attributes.result')) {
                        console.log("Hej" + vm.result);
                    }
                }
            )
        }

        function connect(bus, connectionSpecID, resourcesID){
            var mess = {
                'setup': {
                    'busIP': bus.ip,
                    'publishTopic': bus.publish,
                    'subscribeTopic': bus.subscribe
                }
            };
            var conn = {};
            if (angular.isDefined(connectionSpecID)){
                conn.connectionDetails = connectionSpecID
            }
            if (angular.isDefined(resourcesID)){
                conn.resources = resourcesID
            }
            mess.connection = conn;

            sendTo(mess, 'connect').then(function(repl){
                console.log("inside first connection");
                console.log(repl);
                if (messageOK(repl) && _.has(repl, 'reqID')){
                    service.controlServiceID = repl.reqID;
                }
            });
            service.latestMess = mess;
        }

        function parseColour(item, index) {
            if (!(_.isUndefined(item.address))) {
                var theKey = adressToRaw(item.address);
                var theValue = item.value;

                if (theKey === '138 16 2') {
                    theKey = '138 16 0';
                    searchObj( vm.data, theKey, theValue);
                    theKey = '138 16 1';
                    searchObj( vm.data, theKey, !theValue);
                }

                else searchObj( vm.data, theKey, theValue );
                //var oki = _.find(vm.data.resSel, hejhej);

            }
        }
        //function hejhej(param1){
        //    return !_.isUndefined(_.find(param1.resource, function(r) {return r.id == '135 0 1 true';}));
        //}

        function adressToRaw(params) {
            return params.db + ' ' + params.byte + ' ' + params.bit;
        }

        function searchObj( obj, keyToFind, data ){

            for( var key in obj ) {

                if( typeof obj[key] === 'object' ){
                    searchObj( obj[key], keyToFind, data );
                }

                if( obj[key] === keyToFind ){
                    obj.value = parseColourTrueFalse(data);
                }

            }

        }

        function reset() {
            vm.control.reset();
        }

        function parseColourTrueFalse(value) {
            if (value === true) return '#99e699';
            else if (value === false) return '#ff6666';
            else return '#FFFFFF';
        }

        function sendRawDB(params) {
            var mess = service.latestMess;
            console.log(params);
            mess.command = {
                'commandType': 'raw',
                'raw': params
            };
            spServicesService.callService('OperationControl',{'data':mess});
        }
    }
})();

<|endoftext|>


<commit_before>/**
 * Created by Martin on 2015-11-19.
 */
(function () {
    'use strict';

    angular
        .module('app.Tobbe2')
        .controller('Tobbe2Controller', Tobbe2Controller);

    Tobbe2Controller.$inject = ['$scope', 'dashboardService', 'eventService', 'spServicesService'];
    /* @ngInject */
    function Tobbe2Controller($scope, dashboardService, eventService, spServicesService) {
        var vm = this;
        var service = {
            connected: false,
            controlServiceID: '',
            state: [],
            resourceTree: [],
            latestMess: {},
            connect: connect,
            sendRawDB: sendRawDB
        };

        vm.widget = $scope.$parent.$parent.$parent.vm.widget; //lol what

        //functions¨
        vm.adressToRaw = adressToRaw;
        vm.parseColour = parseColour;
        vm.sendOrder = sendOrder;
        vm.sendRawDB = sendRawDB;
        activate();
        vm.placeyplaceholder = 'Chose operation'
        vm.myFunction = myFunction;
        vm.changeColor = changeColor;
        vm.activate2 = activate2;
        vm.value = 1;
        vm.debug14 = 0;
        vm.someshit = someshit;

        vm.data = {
            resMult: [
                {
                    name: 'Robot 2',
                    resource: [
                        {id: '127 18 0 1', action: 'Set at position 1', value: 'false'},
                        {id: '127 18 0 2', action: 'Set at position 2', value: 'false'},
                        {id: '127 18 0 3', action: 'Set at position 3', value: 'false'},
                        {id: '127 18 0 4', action: 'Set at position 4', value: 'false'},
                        {id: '127 18 0 5', action: 'Set at position 5', value: 'false'},
                        {id: '127 0 5 true', action: 'Pick at set position', value: 'false'},
                        {id: '127 0 2 true', action: 'Place at elevator 2', value: 'false'},
                        {id: '127 0 6 true', action: 'Place at table', value: 'false'},
                    ],
                    currVal: 'Choose operation',
                    currID: 'null'
                }
            ],
            resSel: [
                {
                    name: 'Mode',
                    resource: [
                        {id: '135 0 SAKNAS true', action: 'Manual', value: 'false'},
                        {id: '135 0 SAKNAS true', action: 'Auto', value: 'false'}
                    ]
                },
                {
                    name: 'Elevator 1',
                    resource: [
                        {id: '135 0 0 true', action: 'Up', value: 'false'},
                        {id: '135 0 1 true', action: 'Down', value: 'false'}
                    ]
                },
                {
                    name: 'Elevator 2',
                    resource: [
                        {id: '140 0 0 true', action: 'Up', value: 'false'},
                        {id: '140 0 1 true', action: 'Down', value: 'false'}
                    ]
                },
                {
                    name: 'Flexlink',
                    resource: [
                        {id: '139 0 SAKNAS true', action: 'Start', value: 'false'},
                        {id: '139 0 SAKNAS true', action: 'Stop', value: 'false'}
                    ]
                },
                {
                    name: 'Robot 3',
                    resource: [
                        {id: '128 0 2 true', action: 'Home', value: 'false'},
                        {id: '128 0 3 true', action: 'Dodge', value: 'false'}
                    ]
                },
                {
                    name: 'Robot 4',
                    resource: [
                        {id: '132 0 2 true', action: 'Home', value: 'false'},
                        {id: '132 0 3 true', action: 'Dodge', value: 'false'}
                    ]
                }
            ],
            singleShow: [
                {
                    name: 'Sensor 1',
                    id: 'db hej hej',
                    value: 'false'
                }
            ]
        };

        function changeColor(circleID, colour) {
            var property = document.getElementById(circleID);
            switch (colour) {
                case 'green':
                    property.style.background = "radial-gradient(circle at 15px 15px, #5cd65c, #000)";//green
                    break;
                case 'red':
                    property.style.background = "radial-gradient(circle at 15px 15px, #ff3333, #000)";//red
                    break;
                default:
                    break;
            }
        }

        /* When the user clicks on the button,
         toggle between hiding and showing the dropdown content */
        function myFunction(something) {
            document.getElementById(something).classList.toggle("show");
        }

        // Close the dropdown menu if the user clicks outside of it
        window.onclick = function (event) {
            if (!event.target.matches('.dropbtn')) {

                var dropdowns = document.getElementsByClassName("dropdown-content");
                var i;
                for (i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        }

        function activate2(int) {
            if (int == 1)
                vm.debug14++;
            else
                vm.debug14--;
        }

        function activate() {
            $scope.$on('closeRequest', function () {
                dashboardService.closeWidget(vm.widget.id);
            });
            eventService.addListener('ServiceError', onEvent);
            eventService.addListener('Progress', onEvent);
            eventService.addListener('Response', onEvent);
        }

    function updateItems(){
      var its = _.filter(itemService.items, function(o){
        return (angular.isDefined(o.id) && angular.isDefined(service.state[o.id]))
      });
      service.itemState = [];
      _.foreach(its, function(o){
        service.itemState.push({'item': o, 'state': service.state[o.id]})
      })
    }

    function onEvent(ev){
      //console.log("control service");
      //console.log(ev);

      if (ev.isa == "Response" && ev.service == "OperationControl" && !(_.isUndefined(ev.attributes.dbs)) ) {
        console.log(ev);
        console.log("tjohopp");
        ev.attributes.dbs.forEach(vm.parseColour);

      }

      if (!_.has(ev, 'reqID') || ev.reqID !== service.controlServiceID) return;

      if (_.has(ev, 'attributes.theBus')){
        if (ev.attributes.theBus === 'Connected' && ! service.connected){
          sendTo(service.latestMess, 'subscribe');
        }
        service.connected = ev.attributes.theBus === 'Connected'
      }

      if (_.has(ev, 'attributes.state')){
        service.state = ev.attributes.state;
      }
      if (_.has(ev, 'attributes.resourceTree')){
        service.resourceTree = ev.attributes.resourceTree;
      }
    }

        function sendOrder() {

            var mess = {"data": {getNext: false, "buildOrder": vm.ButtonColour.kub}};
            spServicesService.callService(spServicesService.getService("operatorService"),
                mess,
                function (resp) {
                    if (_.has(resp, 'attributes.result')) {
                        console.log("Hej" + vm.result);
                    }
                }
            )
        }

        function connect(bus, connectionSpecID, resourcesID){
            var mess = {
                'setup': {
                    'busIP': bus.ip,
                    'publishTopic': bus.publish,
                    'subscribeTopic': bus.subscribe
                }
            };
            var conn = {};
            if (angular.isDefined(connectionSpecID)){
                conn.connectionDetails = connectionSpecID
            }
            if (angular.isDefined(resourcesID)){
                conn.resources = resourcesID
            }
            mess.connection = conn;

            sendTo(mess, 'connect').then(function(repl){
                console.log("inside first connection");
                console.log(repl);
                if (messageOK(repl) && _.has(repl, 'reqID')){
                    service.controlServiceID = repl.reqID;
                }
            });
            service.latestMess = mess;
        }

        function parseColour(item, index) {
            if (!(_.isUndefined(item.address))) {
                console.log("here we are")
            var hej = adressToRaw(item.address) +' true';
            console.log(hej);
            console.log(vm.data.resSel);
            console.log(_.find(vm.data.resSel, someshit));
            console.log(adressToRaw(item.address)+" : " + item.value);
            }
        }
        function someshit(param1){
            console.log(param1);
            var prutt = (_.find(param1.resource, function(r) {console.log("printing r"); console.log(r); r.id == "135 0 1 true";}));
            console.log(prutt)
            return prutt
        }

        function adressToRaw(params) {
            return params.db + ' ' + params.byte + ' ' + params.bit;
        }

        function sendRawDB(params) {
            var mess = service.latestMess;
            console.log(params);
            mess.command = {
                'commandType': 'raw',
                'raw': params
            };
            spServicesService.callService('OperationControl',{'data':mess});
        }
    }
})();

<commit_msg>please help meee<commit_after>/**
 * Created by Martin on 2015-11-19.
 */
(function () {
    'use strict';

    angular
        .module('app.Tobbe2')
        .controller('Tobbe2Controller', Tobbe2Controller);

    Tobbe2Controller.$inject = ['$scope', 'dashboardService', 'eventService', 'spServicesService'];
    /* @ngInject */
    function Tobbe2Controller($scope, dashboardService, eventService, spServicesService) {
        var vm = this;
        var service = {
            connected: false,
            controlServiceID: '',
            state: [],
            resourceTree: [],
            latestMess: {},
            connect: connect,
            sendRawDB: sendRawDB
        };

        vm.widget = $scope.$parent.$parent.$parent.vm.widget; //lol what

        //functions¨
        vm.adressToRaw = adressToRaw;
        vm.parseColour = parseColour;
        vm.parseColourCompliment = parseColourCompliment;
        vm.sendOrder = sendOrder;
        vm.sendRawDB = sendRawDB;
        activate();
        vm.placeyplaceholder = 'Chose operation'
        vm.myFunction = myFunction;
        vm.changeColor = changeColor;
        vm.activate2 = activate2;
        vm.value = 1;
        vm.debug14 = 0;
        vm.someshit = someshit;

        vm.data = {
            resMult: [
                {
                    name: 'Robot 2',
                    resource: [
                        {id: '127 18 0 1', action: 'Set at position 1', value: 'false'},
                        {id: '127 18 0 2', action: 'Set at position 2', value: 'false'},
                        {id: '127 18 0 3', action: 'Set at position 3', value: 'false'},
                        {id: '127 18 0 4', action: 'Set at position 4', value: 'false'},
                        {id: '127 18 0 5', action: 'Set at position 5', value: 'false'},
                        {id: '127 0 5 true', action: 'Pick at set position', value: 'false'},
                        {id: '127 0 2 true', action: 'Place at elevator 2', value: 'false'},
                        {id: '127 0 6 true', action: 'Place at table', value: 'false'},
                    ],
                    currVal: 'Choose operation',
                    currID: 'null'
                }
            ],
            resSel: [
                {
                    name: 'Mode',
                    resource: [
                        {id: '135 0 SAKNAS true', action: 'Manual', value: 'false'},
                        {id: '135 0 SAKNAS true', action: 'Auto', value: 'false'}
                    ]
                },
                {
                    name: 'Elevator 1',
                    resource: [
                        {id: '135 0 0 true', action: 'Up', value: 'false'},
                        {id: '135 0 1 true', action: 'Down', value: 'false'}
                    ]
                },
                {
                    name: 'Elevator 2',
                    resource: [
                        {id: '140 0 0 true', action: 'Up', value: 'false'},
                        {id: '140 0 1 true', action: 'Down', value: 'false'}
                    ]
                },
                {
                    name: 'Flexlink',
                    resource: [
                        {id: '139 0 SAKNAS true', action: 'Start', value: 'false'},
                        {id: '139 0 SAKNAS true', action: 'Stop', value: 'false'}
                    ]
                },
                {
                    name: 'Robot 3',
                    resource: [
                        {id: '128 0 2 true', action: 'Home', value: 'false'},
                        {id: '128 0 3 true', action: 'Dodge', value: 'false'}
                    ]
                },
                {
                    name: 'Robot 4',
                    resource: [
                        {id: '132 0 2 true', action: 'Home', value: 'false'},
                        {id: '132 0 3 true', action: 'Dodge', value: 'false'}
                    ]
                }
            ],
            singleShow: [
                {
                    name: 'Sensor 1',
                    id: 'db hej hej',
                    value: 'false'
                }
            ]
        };

        function changeColor(circleID, colour) {
            var property = document.getElementById(circleID);
            switch (colour) {
                case 'green':
                    property.style.background = "radial-gradient(circle at 15px 15px, #5cd65c, #000)";//green
                    break;
                case 'red':
                    property.style.background = "radial-gradient(circle at 15px 15px, #ff3333, #000)";//red
                    break;
                default:
                    break;
            }
        }

        /* When the user clicks on the button,
         toggle between hiding and showing the dropdown content */
        function myFunction(something) {
            document.getElementById(something).classList.toggle("show");
        }

        // Close the dropdown menu if the user clicks outside of it
        window.onclick = function (event) {
            if (!event.target.matches('.dropbtn')) {

                var dropdowns = document.getElementsByClassName("dropdown-content");
                var i;
                for (i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        }

        function activate2(int) {
            if (int == 1)
                vm.debug14++;
            else
                vm.debug14--;
        }

        function activate() {
            $scope.$on('closeRequest', function () {
                dashboardService.closeWidget(vm.widget.id);
            });
            eventService.addListener('ServiceError', onEvent);
            eventService.addListener('Progress', onEvent);
            eventService.addListener('Response', onEvent);
        }

    function updateItems(){
      var its = _.filter(itemService.items, function(o){
        return (angular.isDefined(o.id) && angular.isDefined(service.state[o.id]))
      });
      service.itemState = [];
      _.foreach(its, function(o){
        service.itemState.push({'item': o, 'state': service.state[o.id]})
      })
    }

    function onEvent(ev){
      //console.log("control service");
      //console.log(ev);

      if (ev.isa == "Response" && ev.service == "OperationControl" && !(_.isUndefined(ev.attributes.dbs)) ) {
        console.log(ev);
        console.log("tjohopp");
        ev.attributes.dbs.forEach(vm.parseColour);

      }

      if (!_.has(ev, 'reqID') || ev.reqID !== service.controlServiceID) return;

      if (_.has(ev, 'attributes.theBus')){
        if (ev.attributes.theBus === 'Connected' && ! service.connected){
          sendTo(service.latestMess, 'subscribe');
        }
        service.connected = ev.attributes.theBus === 'Connected'
      }

      if (_.has(ev, 'attributes.state')){
        service.state = ev.attributes.state;
      }
      if (_.has(ev, 'attributes.resourceTree')){
        service.resourceTree = ev.attributes.resourceTree;
      }
    }

        function sendOrder() {

            var mess = {"data": {getNext: false, "buildOrder": vm.ButtonColour.kub}};
            spServicesService.callService(spServicesService.getService("operatorService"),
                mess,
                function (resp) {
                    if (_.has(resp, 'attributes.result')) {
                        console.log("Hej" + vm.result);
                    }
                }
            )
        }

        function connect(bus, connectionSpecID, resourcesID){
            var mess = {
                'setup': {
                    'busIP': bus.ip,
                    'publishTopic': bus.publish,
                    'subscribeTopic': bus.subscribe
                }
            };
            var conn = {};
            if (angular.isDefined(connectionSpecID)){
                conn.connectionDetails = connectionSpecID
            }
            if (angular.isDefined(resourcesID)){
                conn.resources = resourcesID
            }
            mess.connection = conn;

            sendTo(mess, 'connect').then(function(repl){
                console.log("inside first connection");
                console.log(repl);
                if (messageOK(repl) && _.has(repl, 'reqID')){
                    service.controlServiceID = repl.reqID;
                }
            });
            service.latestMess = mess;
        }

        function parseColour(item, index) {

            if (!(_.isUndefined(item.address))) {
                console.log("here we are")
            var hej = adressToRaw(item.address) +' true';
            console.log(hej);
            console.log(vm.data.resSel);
            console.log(_.find(vm.data.resSel, someshit));
            console.log(adressToRaw(item.address)+" : " + item.value);
            }
        }
        function someshit(param1){
            console.log(param1);
            var prutt = (_.find(param1.resource, function(r) {console.log("printing r"); console.log(r); r.id == "135 0 1 true";}));
            console.log(prutt)
            return prutt
        }

        function adressToRaw(params) {
            return params.db + ' ' + params.byte + ' ' + params.bit;
        }

        function sendRawDB(params) {
            var mess = service.latestMess;
            console.log(params);
            mess.command = {
                'commandType': 'raw',
                'raw': params
            };
            spServicesService.callService('OperationControl',{'data':mess});
        }
    }
})();

<|endoftext|>


<commit_before>"use strict";

const LOOP_SEPARATOR = '.';

const UPDATE_GUI_INTERVAL = 50;

// Which files are detected as metadata?
const METADATA_EXTS = [
   'loop',
   'yaml'
];

// Dummy console.
var console = window.console || {
      "log": function(stuff) {
      }
   };

// Implement (string).format .
// http://stackoverflow.com/a/4673436
if (!String.prototype.format) {
   String.prototype.format = function() {
      var args = arguments;
      return this.replace(/{(\d+)}/g, function(match, number) {
         return typeof args[number] != 'undefined' ?
            args[number] :
            match;
      });
   };
}

function arrayGetInt(array, idx) {
   if (idx < 0) {
      return parseFloat(array[array.length + idx]);
   } else {
      return parseFloat(array[idx]);
   }
}

function onloadf(callback) {
   document.addEventListener("DOMContentLoaded", callback);
}

function inArray(arr, obj) {
   return arr.indexOf(obj) !== -1;
}

function relativeUrl(a, b) {
   var aa = URI(a);
   var bb = URI(b);

   if (bb.is('absolute') || bb.toString()[0] == '/') {
      return b;
   }

   return aa.directory() + '/' + b;
}

// define class
function LoopPlayer(url, domPlayPause, domSeek, domDescription, loadedCallback) {
   var that = this;

   var ctx = that.ctx = new AudioContext();

   that.url = url;
   that.urls = [url];
   that.data = null;
   that.playing = false;

   that.loaded = function() {
      return that.data !== null;
   };

   that.source = null;

   that.loopStart = null;
   that.loopEnd = null;

   // startTime = arbitrary seconds.
   // playOffset = delta seconds (ctx.currentTime - startTime).

   that.startTime = null;
   that.playOffset = 0;

   that.domPlayPause = domPlayPause;
   that.domSeek = domSeek;
   that.domDescription = domDescription;
   that.canSeekGui = true;

   const MAX_DEPTH = 2;

   // Load a file into loopplayer.
   that.loadFile = function() {
      // If $url is specified, assume audio to avoid infinite loop.

      // Detect audio or alias by file extension.
      // .loop or .yaml at the moment
      // TODO: translate this whole thing into yield-futures?

      var request = new XMLHttpRequest();

      var urls = that.urls;
      request.open("GET", that.url, true);

      var ext = URI(that.url).suffix().toLowerCase();

      if (inArray(METADATA_EXTS, ext)) {

         // Detect recursive metadata loops.

         if (urls.length >= MAX_DEPTH) {
            console.log('error: recursive metadata.');
            console.log('URL traceback (most recent URL last):');
            for (var i = urls.length - 1; i >= 0; i--) {
               console.log('    ' + urls[i]);
            }
            return;
         }

         // Process metadata files.

         request.onload = function() {
            var response = jsyaml.safeLoad(request.response);
            if (response && response.url) {

               that.url = relativeUrl(that.url, response.url);
               that.urls.push(that.url);
               that.loadFile();

            } else {
               console.log('error: invalid metadata, missing url');
            }
         };

      } else {
         // Process audio files.

         request.responseType = "arraybuffer";
         request.onload = function() {
            ctx.decodeAudioData(request.response,
               function(data) {
                  that.data = data;
                  loadedCallback();
               },
               function() {
                  console.log('error decoding audio data');
               }
            );
         };

         that.parseLoopPoints();
      }

      request.send();
   };

   // Parses the sampling rate and loop points from URL.
   that.parseLoopPoints = function() {
      var uri = new URI(that.url);

      var filename = uri.filename();
      var filebase = filename.split('.').slice(0, -1).join('.');

      var timeArray = filebase.split(LOOP_SEPARATOR);

      var sampleRateOrig = arrayGetInt(timeArray, -3);
      console.log(sampleRateOrig);
      that.loopStart = arrayGetInt(timeArray, -2) / sampleRateOrig;
      that.loopEnd = arrayGetInt(timeArray, -1) / sampleRateOrig;

      console.log("{0} {1}".format(that.loopStart, that.loopEnd));
   };

   // Start playing from playOffset, and initialize startTime. ()
   that.play = function() {
      if (!that.loaded()) return;

      var source = that.source = ctx.createBufferSource();
      source.buffer = that.data;

      source.connect(ctx.destination);

      source.start(0, that.playOffset);
      that.startTime = ctx.currentTime;

      that.playing = true;

      // Set up looping.

      var loopStart = source.loopStart = that.loopStart;
      var loopEnd = source.loopEnd = that.loopEnd;
      source.loop = true;

      source.playTime = function() {
         var realTime = that.playOffset + (ctx.currentTime - that.startTime);
         var loopTime = realTime - loopStart;
         var loopLength = loopEnd - loopStart;

         return (loopTime > 0) ? (loopStart + loopTime % loopLength) : realTime;
      };

      that.updateGui();
   };

   that.getPlayTime = function() {
      if (that.source !== null) {
         return that.source.playTime();
      } else {
         return that.playOffset;
      }
   };

   // **** GUI FUNCTIONS ****

   that.pause = function() {
      if (!that.loaded()) return;
      that.playOffset = that.source.playTime();
      that.source.stop(0);
      that.source = null;

      that.playing = false;

      that.updateGui();
   };

   that.toggle = function() {
      if (that.playing) {
         that.pause();
      } else {
         that.play();
      }

      that.updateGui();
   };

   that.seek = function(time) {
      if (that.enableSeek()) {
         alert('Seeking when GUI update is disabled!');
      }

      var playing = that.playing;

      if (playing) that.pause();
      that.playOffset = time;
      if (playing) that.play();
   };

   that.seekMaybe = function(time) {
      if (that.enableSeek()) {
         that.seek(time);
      }
   };

   that.stop = function() {
      if (that.playing) that.pause();
      that.playOffset = 0;
      that.updateGui();
   };

   that.disableSeek = function() {
      return that.canSeekGui !== (that.canSeekGui = false);
   };

   that.enableSeek = function() {
      return that.canSeekGui !== (that.canSeekGui = true);
   };

   // **** GUI STATUS FUNCTIONS ****

   that.updateGui = function() {
      that.domPlayPause.value = that.playing ? "Pause" : "Play";
      that.updateSeek();
   };

   that.updateSeek = function() {
      if (that.canSeekGui) {
         that.domSeek.value = that.getPlayTime();
      }
   };

   that.updateGuiLoop = function() {
      that.updateSeek();
      window.setTimeout(that.updateGuiLoop, UPDATE_GUI_INTERVAL);
   };

   // **** END CONSTRUCTOR

   that.loadFile();
}
<commit_msg>Added error logging for failed XHR requests.<commit_after>"use strict";

const LOOP_SEPARATOR = '.';

const UPDATE_GUI_INTERVAL = 50;

// Which files are detected as metadata?
const METADATA_EXTS = [
   'loop',
   'yaml'
];

// Dummy console.
var console = window.console || {
      "log": function(stuff) {
      }
   };

// Implement (string).format .
// http://stackoverflow.com/a/4673436
if (!String.prototype.format) {
   String.prototype.format = function() {
      var args = arguments;
      return this.replace(/{(\d+)}/g, function(match, number) {
         return typeof args[number] != 'undefined' ?
            args[number] :
            match;
      });
   };
}

function arrayGetInt(array, idx) {
   if (idx < 0) {
      return parseFloat(array[array.length + idx]);
   } else {
      return parseFloat(array[idx]);
   }
}

function onloadf(callback) {
   document.addEventListener("DOMContentLoaded", callback);
}

function inArray(arr, obj) {
   return arr.indexOf(obj) !== -1;
}

function relativeUrl(a, b) {
   var aa = URI(a);
   var bb = URI(b);

   if (bb.is('absolute') || bb.toString()[0] == '/') {
      return b;
   }

   return aa.directory() + '/' + b;
}

// define class
function LoopPlayer(url, domPlayPause, domSeek, domDescription, loadedCallback) {
   var that = this;

   var ctx = that.ctx = new AudioContext();

   that.url = url;
   that.urls = [url];
   that.data = null;
   that.playing = false;

   that.loaded = function() {
      return that.data !== null;
   };

   that.source = null;

   that.loopStart = null;
   that.loopEnd = null;

   // startTime = arbitrary seconds.
   // playOffset = delta seconds (ctx.currentTime - startTime).

   that.startTime = null;
   that.playOffset = 0;

   that.domPlayPause = domPlayPause;
   that.domSeek = domSeek;
   that.domDescription = domDescription;
   that.canSeekGui = true;

   const MAX_DEPTH = 2;

   // Load a file into loopplayer.
   that.loadFile = function() {
      // If $url is specified, assume audio to avoid infinite loop.

      // Detect audio or alias by file extension.
      // .loop or .yaml at the moment
      // TODO: translate this whole thing into yield-futures?

      var request = new XMLHttpRequest();

      var urls = that.urls;
      request.open("GET", that.url, true);

      var ext = URI(that.url).suffix().toLowerCase();

      if (inArray(METADATA_EXTS, ext)) {

         // Detect recursive metadata loops.

         if (urls.length >= MAX_DEPTH) {
            console.log('error: recursive metadata.');
            console.log('URL traceback (most recent URL last):');
            for (var i = urls.length - 1; i >= 0; i--) {
               console.log('    ' + urls[i]);
            }
            return;
         }

         // Process metadata files.

         request.onload = function() {
            var response = jsyaml.safeLoad(request.response);
            if (response && response.url) {

               that.url = relativeUrl(that.url, response.url);
               that.urls.push(that.url);
               that.loadFile();

            } else {
               console.log('error: invalid metadata, missing "url"');
            }
         };

         request.onerror = function(request) {
            console.log('error fetching metadata')
         };

      } else {
         // Process audio files.

         request.responseType = "arraybuffer";
         request.onload = function() {
            ctx.decodeAudioData(request.response,
               function(data) {
                  that.data = data;
                  loadedCallback();
               },
               function() {
                  console.log('error decoding audio data');
               }
            );
         };

         request.onerror = function(request) {
            console.log('error fetching audio')
         };

         that.parseLoopPoints();
      }

      request.send();
   };

   // Parses the sampling rate and loop points from URL.
   that.parseLoopPoints = function() {
      var uri = new URI(that.url);

      var filename = uri.filename();
      var filebase = filename.split('.').slice(0, -1).join('.');

      var timeArray = filebase.split(LOOP_SEPARATOR);

      var sampleRateOrig = arrayGetInt(timeArray, -3);
      console.log(sampleRateOrig);
      that.loopStart = arrayGetInt(timeArray, -2) / sampleRateOrig;
      that.loopEnd = arrayGetInt(timeArray, -1) / sampleRateOrig;

      console.log("{0} {1}".format(that.loopStart, that.loopEnd));
   };

   // Start playing from playOffset, and initialize startTime. ()
   that.play = function() {
      if (!that.loaded()) return;

      var source = that.source = ctx.createBufferSource();
      source.buffer = that.data;

      source.connect(ctx.destination);

      source.start(0, that.playOffset);
      that.startTime = ctx.currentTime;

      that.playing = true;

      // Set up looping.

      var loopStart = source.loopStart = that.loopStart;
      var loopEnd = source.loopEnd = that.loopEnd;
      source.loop = true;

      source.playTime = function() {
         var realTime = that.playOffset + (ctx.currentTime - that.startTime);
         var loopTime = realTime - loopStart;
         var loopLength = loopEnd - loopStart;

         return (loopTime > 0) ? (loopStart + loopTime % loopLength) : realTime;
      };

      that.updateGui();
   };

   that.getPlayTime = function() {
      if (that.source !== null) {
         return that.source.playTime();
      } else {
         return that.playOffset;
      }
   };

   // **** GUI FUNCTIONS ****

   that.pause = function() {
      if (!that.loaded()) return;
      that.playOffset = that.source.playTime();
      that.source.stop(0);
      that.source = null;

      that.playing = false;

      that.updateGui();
   };

   that.toggle = function() {
      if (that.playing) {
         that.pause();
      } else {
         that.play();
      }

      that.updateGui();
   };

   that.seek = function(time) {
      if (that.enableSeek()) {
         alert('Seeking when GUI update is disabled!');
      }

      var playing = that.playing;

      if (playing) that.pause();
      that.playOffset = time;
      if (playing) that.play();
   };

   that.seekMaybe = function(time) {
      if (that.enableSeek()) {
         that.seek(time);
      }
   };

   that.stop = function() {
      if (that.playing) that.pause();
      that.playOffset = 0;
      that.updateGui();
   };

   that.disableSeek = function() {
      return that.canSeekGui !== (that.canSeekGui = false);
   };

   that.enableSeek = function() {
      return that.canSeekGui !== (that.canSeekGui = true);
   };

   // **** GUI STATUS FUNCTIONS ****

   that.updateGui = function() {
      that.domPlayPause.value = that.playing ? "Pause" : "Play";
      that.updateSeek();
   };

   that.updateSeek = function() {
      if (that.canSeekGui) {
         that.domSeek.value = that.getPlayTime();
      }
   };

   that.updateGuiLoop = function() {
      that.updateSeek();
      window.setTimeout(that.updateGuiLoop, UPDATE_GUI_INTERVAL);
   };

   // **** END CONSTRUCTOR

   that.loadFile();
}
<|endoftext|>


<commit_before>const electron = require('electron')
const fs = require('fs')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.

var appDataPath = app.getPath('appData') + '/min/'

const browserPage = 'file://' + __dirname + '/index.html'

var mainWindow = null
var isFocusMode = false
var appIsReady = false

var saveWindowBounds = function () {
  if (mainWindow) {
    fs.writeFile(appDataPath + 'windowBounds.json', JSON.stringify(mainWindow.getBounds()))
  }
}

function sendIPCToWindow (window, action, data) {
  // if there are no windows, create a new one
  if (!mainWindow) {
    createWindow(function () {
      mainWindow.webContents.send(action, data || {})
    })
  } else {
    mainWindow.webContents.send(action, data || {})
  }
}

//adjusts the coordinates to account for the window frame on Windows 10
//fixes https://github.com/minbrowser/min/issues/214
//based on https://github.com/electron/electron/issues/4045#issuecomment-170399607
//should be removed once https://github.com/electron/electron/issues/4045 is fixed
function adjustCoordinatesForWindows(coordinates) {
  coordinates.x -= 7
  coordinates.width += 14
  coordinates.height += 7

  return coordinates
}

function createWindow (cb) {
  var savedBounds = fs.readFile(appDataPath + 'windowBounds.json', 'utf-8', function (e, data) {
    if (e || !data) { // there was an error, probably because the file doesn't exist
      var size = electron.screen.getPrimaryDisplay().workAreaSize
      var bounds = {
        x: 0,
        y: 0,
        width: size.width,
        height: size.height
      }
    } else {
      var bounds = JSON.parse(data)
    }

    if(process.platform === 'win32') {

      if(bounds.x === 0 && bounds.y === 0) {
        var screenSize = electron.screen.getPrimaryDisplay().workAreaSize;
        if(screenSize.width === bounds.width && screenSize.height === bounds.height) {
          var shouldMaximize = true;
        }
      }

      bounds = adjustCoordinatesForWindows(bounds)

    }

    createWindowWithBounds(bounds, shouldMaximize)

    if (cb) {
      cb()
    }
  })
}

function createWindowWithBounds (bounds, shouldMaximize) {
  mainWindow = new BrowserWindow({
    width: bounds.width,
    height: bounds.height,
    x: bounds.x,
    y: bounds.y,
    minWidth: 320,
    minHeight: 500,
    titleBarStyle: 'hidden-inset',
    icon: __dirname + '/icons/icon256.png'
  })

  // and load the index.html of the app.
  mainWindow.loadURL(browserPage)

  if(shouldMaximize) {
    mainWindow.maximize()
  }

  // save the window size for the next launch of the app
  mainWindow.on('close', function () {
    saveWindowBounds()
  })

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })

  /* handle pdf downloads - ipc recieved in fileDownloadManager.js */

  mainWindow.webContents.session.on('will-download', function (event, item, webContents) {
    var itemURL = item.getURL()
    if (item.getMimeType() === 'application/pdf' && itemURL.indexOf('blob:') !== 0) { // clicking the download button in the viewer opens a blob url, so we don't want to open those in the viewer (since that would make it impossible to download a PDF)
      event.preventDefault()
      sendIPCToWindow(mainWindow, 'openPDF', {
        url: itemURL,
        event: event,
        item: item, // as of electron 0.35.1, this is an empty object
        webContents: webContents
      })
    }
    return true
  })

  mainWindow.on('enter-full-screen', function () {
    sendIPCToWindow(mainWindow, 'enter-full-screen')
  })

  mainWindow.on('leave-full-screen', function () {
    sendIPCToWindow(mainWindow, 'leave-full-screen')
  })

  mainWindow.on('app-command', function (e, command) {
    if (command === 'browser-backward') {
      sendIPCToWindow(mainWindow, 'goBack')
    } else if (command === 'browser-forward') {
      sendIPCToWindow(mainWindow, 'goForward')
    }
  })

  // prevent remote pages from being loaded using drag-and-drop, since they would have node access
  mainWindow.webContents.on('will-navigate', function (e, url) {
    if (url !== browserPage) {
      e.preventDefault()
    }
  })

  registerFiltering() // register filtering for the default session

  return mainWindow
}

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function () {
  appIsReady = true

  createWindow(function () {
    // if a URL was passed as a command line argument (probably because Min is set as the default browser on Linux), open it.

    if (process.argv && process.argv[1] && process.argv[1].toLowerCase() !== __dirname.toLowerCase() && process.argv[1].indexOf('://') !== -1) {
      mainWindow.webContents.on('did-finish-load', function () {
        sendIPCToWindow(mainWindow, 'addTab', {
          url: process.argv[1]
        })
      })
    }
  })

  // Open the DevTools.
  // mainWindow.openDevTools()

  createAppMenu()
})

app.on('open-url', function (e, url) {
  if (appIsReady) {
    sendIPCToWindow(mainWindow, 'addTab', {
      url: url
    })
  } else {
    app.on('ready', function () {
      setTimeout(function () { // TODO replace this with an event that occurs when the browserWindow finishes loading
        sendIPCToWindow(mainWindow, 'addTab', {
          url: url
        })
      }, 750)
    })
  }
})

/**
 * Emitted when the application is activated, which usually happens when clicks on the applications's dock icon
 * https://github.com/electron/electron/blob/master/docs/api/app.md#event-activate-os-x
 *
 * Opens a new tab when all tabs are closed, and min is still open by clicking on the application dock icon
 */
app.on('activate', function ( /* e, hasVisibleWindows */) {
  if (!mainWindow && appIsReady) { // sometimes, the event will be triggered before the app is ready, and creating new windows will fail
    createWindow()
  }
})

function createAppMenu () {
  // create the menu. based on example from http://electron.atom.io/docs/v0.34.0/api/menu/

  var Menu = electron.Menu
  var MenuItem = electron.MenuItem

  var template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'New Tab',
          accelerator: 'CmdOrCtrl+t',
          click: function (item, window) {
            sendIPCToWindow(window, 'addTab')
          }
        },
        {
          label: 'New Private Tab',
          accelerator: 'shift+CmdOrCtrl+t',
          click: function (item, window) {
            sendIPCToWindow(window, 'addPrivateTab')
          }
        },
        {
          label: 'New Task',
          accelerator: 'shift+CmdOrCtrl+n',
          click: function (item, window) {
            sendIPCToWindow(window, 'addTask')
          }
        },
        {
          type: 'separator'
        },
        {
          label: 'Print',
          accelerator: 'CmdOrCtrl+p',
          click: function (item, window) {
            sendIPCToWindow(window, 'print')
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Undo',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo'
        },
        {
          label: 'Redo',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo'
        },
        {
          type: 'separator'
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        },
        {
          type: 'separator'
        },
        {
          label: 'Find',
          accelerator: 'CmdOrCtrl+F',
          click: function (item, window) {
            sendIPCToWindow(window, 'findInPage')
          }
        }
      ]
    },
    /* these items are added by os x */
    {
      label: 'View',
      submenu: [
        {
          label: 'Zoom in',
          accelerator: 'CmdOrCtrl+=',
          click: function (item, window) {
            sendIPCToWindow(window, 'zoomIn')
          }
        },
        {
          label: 'Zoom out',
          accelerator: 'CmdOrCtrl+-',
          click: function (item, window) {
            sendIPCToWindow(window, 'zoomOut')
          }
        },
        {
          label: 'Actual size',
          accelerator: 'CmdOrCtrl+0',
          click: function (item, window) {
            sendIPCToWindow(window, 'zoomReset')
          }
        },
        {
          type: 'separator'
        },
        {
          label: 'Focus mode',
          accelerator: undefined,
          type: 'checkbox',
          checked: false,
          click: function (item, window) {
            if (isFocusMode) {
              item.checked = false
              isFocusMode = false
              sendIPCToWindow(window, 'exitFocusMode')
            } else {
              item.checked = true
              isFocusMode = true
              sendIPCToWindow(window, 'enterFocusMode')
            }
          }
        },
        {
          label: 'Reading List',
          accelerator: undefined,
          click: function (item, window) {
            sendIPCToWindow(window, 'showReadingList')
          }
        }
      ]
    },
    {
      label: 'Developer',
      submenu: [
        {
          label: 'Reload Browser',
          accelerator: undefined,
          click: function (item, focusedWindow) {
            if (focusedWindow) focusedWindow.reload()
          }
        },
        {
          label: 'Inspect browser',
          click: function (item, focusedWindow) {
            if (focusedWindow) focusedWindow.toggleDevTools()
          }
        },
        {
          type: 'separator'
        },
        {
          label: 'Inspect page',
          accelerator: 'Cmd+Alt+I',
          click: function (item, window) {
            sendIPCToWindow(window, 'inspectPage')
          }
        }
      ]
    },
    {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Close',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Learn More',
          click: function () {
            electron.shell.openExternal('http://github.com/palmerAl/browser')
          }
        }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    var name = app.getName()
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'About ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Preferences',
          accelerator: 'CmdOrCtrl+,',
          click: function (item, window) {
            sendIPCToWindow(window, 'addTab', {
              url: 'file://' + __dirname + '/pages/settings/index.html'
            })
          }
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + name,
          accelerator: 'CmdOrCtrl+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'CmdOrCtrl+Shift+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'CmdOrCtrl+Q',
          click: function () {
            app.quit()
          }
        }
      ]
    })
    // Window menu.
    template[3].submenu.push({
      type: 'separator'
    }, {
      label: 'Bring All to Front',
      role: 'front'
    })
  }

  // preferences item on linux and windows

  if (process.platform !== 'darwin') {
    template[1].submenu.push({
      type: 'separator'
    })

    template[1].submenu.push({
      label: 'Preferences',
      accelerator: 'CmdOrCtrl+,',
      click: function (item, window) {
        sendIPCToWindow(window, 'addTab', {
          url: 'file://' + __dirname + '/pages/settings/index.html'
        })
      }
    })
  }

  var menu = new Menu()

  menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}
;var session = electron.session

var thingsToFilter = {
  trackers: false,
  contentTypes: [] // script, image
}

var filterContentTypes = thingsToFilter.contentTypes.length !== 0

var parser
var parsedFilterData = {}

function initFilterList () {
  parser = require('./ext/abp-filter-parser-modified/abp-filter-parser.js')

  var data = require('fs').readFile(__dirname + '/ext/filterLists/easylist+easyprivacy-noelementhiding.txt', 'utf8', function (err, data) {
    if (err) {
      return
    }

    // data = data.replace(/.*##.+\n/g, '') // remove element hiding rules

    parser.parse(data, parsedFilterData)
  })
}

function handleRequest (details, callback) {
  if (!(details.url.startsWith('http://') || details.url.startsWith('https://')) || details.resourceType === 'mainFrame') {
    callback({
      cancel: false,
      requestHeaders: details.requestHeaders
    })
    return
  }

  // block javascript and images if needed

  if (filterContentTypes) {
    for (var i = 0; i < thingsToFilter.contentTypes.length; i++) {
      if (details.resourceType === thingsToFilter.contentTypes[i]) {
        callback({
          cancel: true,
          requestHeaders: details.requestHeaders
        })
        return
      }
    }
  }

  if (thingsToFilter.trackers) {
    if (parser.matches(parsedFilterData, details.url, {
      domain: '',
      elementType: details.resourceType
    })) {
      callback({
        cancel: true,
        requestHeaders: details.requestHeaders
      })
      return
    }
  }

  callback({
    cancel: false,
    requestHeaders: details.requestHeaders
  })
}

global.setFilteringSettings = function (settings) {
  if (!settings) {
    settings = {}
  }

  if (settings.trackers && !thingsToFilter.trackers) { // we're enabling tracker filtering
    initFilterList()
  }

  thingsToFilter.contentTypes = settings.contentTypes || []
  thingsToFilter.trackers = settings.trackers || false

  filterContentTypes = thingsToFilter.contentTypes.length !== 0
}

global.registerFiltering = function (ses) {
  if (ses) {
    ses = session.fromPartition(ses)
  } else {
    ses = session.defaultSession
  }

  ses.webRequest.onBeforeRequest(handleRequest)
}
<commit_msg>update main.build.js<commit_after>const electron = require('electron')
const fs = require('fs')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.

var appDataPath = app.getPath('appData') + '/min/'

const browserPage = 'file://' + __dirname + '/index.html'

var mainWindow = null
var isFocusMode = false
var appIsReady = false

var saveWindowBounds = function () {
  if (mainWindow) {
    fs.writeFile(appDataPath + 'windowBounds.json', JSON.stringify(mainWindow.getBounds()))
  }
}

function sendIPCToWindow (window, action, data) {
  // if there are no windows, create a new one
  if (!mainWindow) {
    createWindow(function () {
      mainWindow.webContents.send(action, data || {})
    })
  } else {
    mainWindow.webContents.send(action, data || {})
  }
}

function openTabInWindow (url) {
  sendIPCToWindow(mainWindow, 'addTab', {
    url: url
  })
}

// adjusts the coordinates to account for the window frame on Windows 10
// fixes https://github.com/minbrowser/min/issues/214
// based on https://github.com/electron/electron/issues/4045#issuecomment-170399607
// should be removed once https://github.com/electron/electron/issues/4045 is fixed
function adjustCoordinatesForWindows (coordinates) {
  coordinates.x -= 7
  coordinates.width += 14
  coordinates.height += 7

  return coordinates
}

function createWindow (cb) {
  var savedBounds = fs.readFile(appDataPath + 'windowBounds.json', 'utf-8', function (e, data) {
    if (e || !data) { // there was an error, probably because the file doesn't exist
      var size = electron.screen.getPrimaryDisplay().workAreaSize
      var bounds = {
        x: 0,
        y: 0,
        width: size.width,
        height: size.height
      }
    } else {
      var bounds = JSON.parse(data)
    }

    if (process.platform === 'win32') {
      if (bounds.x === 0 && bounds.y === 0) {
        var screenSize = electron.screen.getPrimaryDisplay().workAreaSize
        if (screenSize.width === bounds.width && screenSize.height === bounds.height) {
          var shouldMaximize = true
        }
      }

      bounds = adjustCoordinatesForWindows(bounds)
    }

    createWindowWithBounds(bounds, shouldMaximize)

    if (cb) {
      cb()
    }
  })
}

function createWindowWithBounds (bounds, shouldMaximize) {
  mainWindow = new BrowserWindow({
    width: bounds.width,
    height: bounds.height,
    x: bounds.x,
    y: bounds.y,
    minWidth: 320,
    minHeight: 500,
    titleBarStyle: 'hidden-inset',
    icon: __dirname + '/icons/icon256.png'
  })

  // and load the index.html of the app.
  mainWindow.loadURL(browserPage)

  if (shouldMaximize) {
    mainWindow.maximize()
  }

  // save the window size for the next launch of the app
  mainWindow.on('close', function () {
    saveWindowBounds()
  })

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })

  /* handle pdf downloads - ipc recieved in fileDownloadManager.js */

  mainWindow.webContents.session.on('will-download', function (event, item, webContents) {
    var itemURL = item.getURL()
    if (item.getMimeType() === 'application/pdf' && itemURL.indexOf('blob:') !== 0) { // clicking the download button in the viewer opens a blob url, so we don't want to open those in the viewer (since that would make it impossible to download a PDF)
      event.preventDefault()
      sendIPCToWindow(mainWindow, 'openPDF', {
        url: itemURL,
        event: event,
        item: item, // as of electron 0.35.1, this is an empty object
        webContents: webContents
      })
    }
    return true
  })

  mainWindow.on('enter-full-screen', function () {
    sendIPCToWindow(mainWindow, 'enter-full-screen')
  })

  mainWindow.on('leave-full-screen', function () {
    sendIPCToWindow(mainWindow, 'leave-full-screen')
  })

  mainWindow.on('app-command', function (e, command) {
    if (command === 'browser-backward') {
      sendIPCToWindow(mainWindow, 'goBack')
    } else if (command === 'browser-forward') {
      sendIPCToWindow(mainWindow, 'goForward')
    }
  })

  // prevent remote pages from being loaded using drag-and-drop, since they would have node access
  mainWindow.webContents.on('will-navigate', function (e, url) {
    if (url !== browserPage) {
      e.preventDefault()
    }
  })

  registerFiltering() // register filtering for the default session

  return mainWindow
}

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function () {
  appIsReady = true

  createWindow(function () {
    // if a URL was passed as a command line argument (probably because Min is set as the default browser on Linux), open it.

    if (process.argv && process.argv[1] && process.argv[1].toLowerCase() !== __dirname.toLowerCase() && process.argv[1].indexOf('://') !== -1) {
      mainWindow.webContents.on('did-finish-load', function () {
        sendIPCToWindow(mainWindow, 'addTab', {
          url: process.argv[1]
        })
      })
    }
  })

  // Open the DevTools.
  // mainWindow.openDevTools()

  createAppMenu()
})

app.on('open-url', function (e, url) {
  if (appIsReady) {
    sendIPCToWindow(mainWindow, 'addTab', {
      url: url
    })
  } else {
    app.on('ready', function () {
      setTimeout(function () { // TODO replace this with an event that occurs when the browserWindow finishes loading
        sendIPCToWindow(mainWindow, 'addTab', {
          url: url
        })
      }, 750)
    })
  }
})

/**
 * Emitted when the application is activated, which usually happens when clicks on the applications's dock icon
 * https://github.com/electron/electron/blob/master/docs/api/app.md#event-activate-os-x
 *
 * Opens a new tab when all tabs are closed, and min is still open by clicking on the application dock icon
 */
app.on('activate', function ( /* e, hasVisibleWindows */) {
  if (!mainWindow && appIsReady) { // sometimes, the event will be triggered before the app is ready, and creating new windows will fail
    createWindow()
  }
})

function createAppMenu () {
  // create the menu. based on example from http://electron.atom.io/docs/v0.34.0/api/menu/

  var Menu = electron.Menu
  var MenuItem = electron.MenuItem

  var template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'New Tab',
          accelerator: 'CmdOrCtrl+t',
          click: function (item, window) {
            sendIPCToWindow(window, 'addTab')
          }
        },
        {
          label: 'New Private Tab',
          accelerator: 'shift+CmdOrCtrl+t',
          click: function (item, window) {
            sendIPCToWindow(window, 'addPrivateTab')
          }
        },
        {
          label: 'New Task',
          accelerator: 'shift+CmdOrCtrl+n',
          click: function (item, window) {
            sendIPCToWindow(window, 'addTask')
          }
        },
        {
          type: 'separator'
        },
        {
          label: 'Print',
          accelerator: 'CmdOrCtrl+p',
          click: function (item, window) {
            sendIPCToWindow(window, 'print')
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Undo',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo'
        },
        {
          label: 'Redo',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo'
        },
        {
          type: 'separator'
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        },
        {
          type: 'separator'
        },
        {
          label: 'Find',
          accelerator: 'CmdOrCtrl+F',
          click: function (item, window) {
            sendIPCToWindow(window, 'findInPage')
          }
        }
      ]
    },
    /* these items are added by os x */
    {
      label: 'View',
      submenu: [
        {
          label: 'Zoom in',
          accelerator: 'CmdOrCtrl+=',
          click: function (item, window) {
            sendIPCToWindow(window, 'zoomIn')
          }
        },
        {
          label: 'Zoom out',
          accelerator: 'CmdOrCtrl+-',
          click: function (item, window) {
            sendIPCToWindow(window, 'zoomOut')
          }
        },
        {
          label: 'Actual size',
          accelerator: 'CmdOrCtrl+0',
          click: function (item, window) {
            sendIPCToWindow(window, 'zoomReset')
          }
        },
        {
          type: 'separator'
        },
        {
          label: 'Focus mode',
          accelerator: undefined,
          type: 'checkbox',
          checked: false,
          click: function (item, window) {
            if (isFocusMode) {
              item.checked = false
              isFocusMode = false
              sendIPCToWindow(window, 'exitFocusMode')
            } else {
              item.checked = true
              isFocusMode = true
              sendIPCToWindow(window, 'enterFocusMode')
            }
          }
        },
        {
          label: 'Reading List',
          accelerator: undefined,
          click: function (item, window) {
            sendIPCToWindow(window, 'showReadingList')
          }
        }
      ]
    },
    {
      label: 'Developer',
      submenu: [
        {
          label: 'Reload Browser',
          accelerator: undefined,
          click: function (item, focusedWindow) {
            if (focusedWindow) focusedWindow.reload()
          }
        },
        {
          label: 'Inspect browser',
          click: function (item, focusedWindow) {
            if (focusedWindow) focusedWindow.toggleDevTools()
          }
        },
        {
          type: 'separator'
        },
        {
          label: 'Inspect page',
          accelerator: 'Cmd+Alt+I',
          click: function (item, window) {
            sendIPCToWindow(window, 'inspectPage')
          }
        }
      ]
    },
    {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Close',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Keyboard Shortcuts',
          click: function () {
            openTabInWindow('https://github.com/minbrowser/min/wiki#keyboard-shortcuts')
          }
        },
        {
          label: 'Report a Bug',
          click: function () {
            openTabInWindow('https://github.com/minbrowser/min/issues/new')
          }
        },
        {
          label: 'Take a Tour',
          click: function () {
            openTabInWindow('https://minbrowser.github.io/min/tour/')
          }
        },
        {
          label: 'View on GitHub',
          click: function () {
            openTabInWindow('https://github.com/minbrowser/min')
          }
        }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    var name = app.getName()
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'About ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Preferences',
          accelerator: 'CmdOrCtrl+,',
          click: function (item, window) {
            sendIPCToWindow(window, 'addTab', {
              url: 'file://' + __dirname + '/pages/settings/index.html'
            })
          }
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + name,
          accelerator: 'CmdOrCtrl+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'CmdOrCtrl+Shift+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'CmdOrCtrl+Q',
          click: function () {
            app.quit()
          }
        }
      ]
    })
    // Window menu.
    template[3].submenu.push({
      type: 'separator'
    }, {
      label: 'Bring All to Front',
      role: 'front'
    })
  }

  // preferences item on linux and windows

  if (process.platform !== 'darwin') {
    template[1].submenu.push({
      type: 'separator'
    })

    template[1].submenu.push({
      label: 'Preferences',
      accelerator: 'CmdOrCtrl+,',
      click: function (item, window) {
        sendIPCToWindow(window, 'addTab', {
          url: 'file://' + __dirname + '/pages/settings/index.html'
        })
      }
    })
  }

  var menu = new Menu()

  menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}
;var session = electron.session

var thingsToFilter = {
  trackers: false,
  contentTypes: [] // script, image
}

var filterContentTypes = thingsToFilter.contentTypes.length !== 0

var parser
var parsedFilterData = {}

function initFilterList () {
  parser = require('./ext/abp-filter-parser-modified/abp-filter-parser.js')

  var data = require('fs').readFile(__dirname + '/ext/filterLists/easylist+easyprivacy-noelementhiding.txt', 'utf8', function (err, data) {
    if (err) {
      return
    }

    // data = data.replace(/.*##.+\n/g, '') // remove element hiding rules

    parser.parse(data, parsedFilterData)
  })
}

function handleRequest (details, callback) {
  if (!(details.url.startsWith('http://') || details.url.startsWith('https://')) || details.resourceType === 'mainFrame') {
    callback({
      cancel: false,
      requestHeaders: details.requestHeaders
    })
    return
  }

  // block javascript and images if needed

  if (filterContentTypes) {
    for (var i = 0; i < thingsToFilter.contentTypes.length; i++) {
      if (details.resourceType === thingsToFilter.contentTypes[i]) {
        callback({
          cancel: true,
          requestHeaders: details.requestHeaders
        })
        return
      }
    }
  }

  if (thingsToFilter.trackers) {
    if (parser.matches(parsedFilterData, details.url, {
      domain: '',
      elementType: details.resourceType
    })) {
      callback({
        cancel: true,
        requestHeaders: details.requestHeaders
      })
      return
    }
  }

  callback({
    cancel: false,
    requestHeaders: details.requestHeaders
  })
}

global.setFilteringSettings = function (settings) {
  if (!settings) {
    settings = {}
  }

  if (settings.trackers && !thingsToFilter.trackers) { // we're enabling tracker filtering
    initFilterList()
  }

  thingsToFilter.contentTypes = settings.contentTypes || []
  thingsToFilter.trackers = settings.trackers || false

  filterContentTypes = thingsToFilter.contentTypes.length !== 0
}

global.registerFiltering = function (ses) {
  if (ses) {
    ses = session.fromPartition(ses)
  } else {
    ses = session.defaultSession
  }

  ses.webRequest.onBeforeRequest(handleRequest)
}
<|endoftext|>