<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

function FacilityController($scope, facilityReferenceData, $routeParams, facility, Facility, $location, FacilityProgramProducts, FacilityImages, facilityImages, $q, $dialog, messageService) {
  $scope.$parent.facilityId = null;
  $scope.message = "";
  initialize();

  function initialize() {
    $scope.facilityTypes = facilityReferenceData.facilityTypes;
    $scope.geographicZones = facilityReferenceData.geographicZones;
    $scope.facilityOperators = facilityReferenceData.facilityOperators;
    $scope.images = facilityImages.images;
    $scope.programs = facilityReferenceData.programs;
    if ($routeParams.facilityId) {
      $scope.facility = getFacilityWithDateObjects(facility);
      $scope.originalFacilityCode = facility.code;
      $scope.originalFacilityName = facility.name;
      $scope.isEdit = true;
      updateProgramsToDisplay();
    } else {
      $scope.facility = {};
      updateProgramsToDisplay();
      $scope.facility.enabled = true;
    }
    $scope.facilityProgramProductsList = [];
  }

  function convertStringToCorrectDateFormat(stringDate) {
    if (stringDate) {
      return stringDate.split("-").reverse().join("-");
    }
    return null;
  }

  function getFacilityWithDateObjects(facility) {
    angular.forEach(facility.supportedPrograms, function (supportedProgram) {
      if (supportedProgram.startDate) {
        supportedProgram.startDate = supportedProgram.stringStartDate;
      }
    });

    facility.goLiveDate = convertStringToCorrectDateFormat(facility.stringGoLiveDate);
    facility.goDownDate = convertStringToCorrectDateFormat(facility.stringGoDownDate);

    return facility;
  }

  $scope.showISAEditModal = function (supportedProgram) {
    $scope.currentProgram = supportedProgram.program;
    $scope.$broadcast('showISAEditModal');
  };

  $scope.cancelUserSave = function () {
    $location.path('#/search');
  };

  function saveAllocationProgramProducts() {
    var promises = [];

    var keys = _.keys($scope.facilityProgramProductsList);

    $(keys).each(function (index, key) {
      var deferred = $q.defer();
      promises.push(deferred.promise);

      var program = $scope.facilityProgramProductsList[key][0].program;

      FacilityProgramProducts.update({facilityId: $scope.facility.id, programId: program.id}, $scope.facilityProgramProductsList[key], function (data) {
        deferred.resolve();
      }, function () {
        deferred.reject({error: "error.facility.allocation.product.save", program: program.name});
      });
    });

    return promises;
  }

  $scope.saveFacility = function () {
    if ($scope.facilityForm.$error.pattern || $scope.facilityForm.$error.required) {
      $scope.showError = "true";
      $scope.error = 'form.error';
      $scope.message = "";
      return;
    }

    var facilitySaveCallback = function (data) {
      $scope.facility = data.facility;
      var promises = saveAllocationProgramProducts();

      $q.all(promises).then(function () {
        $scope.showError = "true";
        $scope.error = "";
        $scope.errorProgram = "";
        $scope.$parent.message = data.success;
        $scope.facility = getFacilityWithDateObjects(data.facility);
        $scope.$parent.facilityId = $scope.facility.id;
        $location.path('');
      }, function (error) {
        $scope.showError = "true";
        $scope.message = "";
        $scope.error = error.error;
        $scope.errorProgram = error.program;
      });
    };

    if (!$scope.isEdit) {
      Facility.save({}, $scope.facility, facilitySaveCallback, errorFunc);
    } else {
      Facility.update({id: $scope.facility.id}, $scope.facility, facilitySaveCallback, errorFunc);
    }
  };

  $scope.blurDateFields = function () {
    angular.element("input[ui-date]").blur();
  };

  $scope.addSupportedProgram = function (supportedProgram) {
    if (supportedProgram.active && !supportedProgram.editedStartDate) {
      $scope.showDateNotEnteredError = true;
      return;
    }
    supportedProgram.program = getProgramById(supportedProgram.program.id);
    $scope.facility.supportedPrograms.push(supportedProgram);
    $scope.showDateNotEnteredError = false;
    $scope.supportedProgram = undefined;
    updateProgramsToDisplay();
  };

  $scope.showConfirmDateChangeWindow = function (program) {
    window.program = program;
    if (getProgramById(program.program.id).push) {
      $scope.dateChangeCallback(true);
      return;
    }
    var dialogOpts = {
      id: "dateChangeConfirmModal",
      header: 'message.setProgramStartDate',
      body: 'message.dateChangeConfirmMessage'
    };
    OpenLmisDialog.newDialog(dialogOpts, $scope.dateChangeCallback, $dialog);
  };

  $scope.dateChangeCallback = function (result) {
    if (result) {
      window.program.startDate = window.program.editedStartDate;
    } else {
      window.program.editedStartDate = window.program.startDate;
    }
  };

  $scope.showRemoveProgramConfirmDialog = function (supportedProgram) {
    $scope.selectedSupportedProgram = supportedProgram;
    var options = {
      id: "removeProgramConfirmDialog",
      header: 'delete.facility.program.header',
      body: messageService.get('delete.facility.program.confirm', $scope.selectedSupportedProgram.program.name)
    };
    OpenLmisDialog.newDialog(options, $scope.removeSupportedProgramConfirm, $dialog);
  };

  $scope.removeSupportedProgramConfirm = function (result) {
    if (result) {
      $scope.removeSupportedProgram();
    }
    $scope.selectedSupportedProgram = undefined;
  };

  $scope.removeSupportedProgram = function () {
    $scope.facility.supportedPrograms = _.without($scope.facility.supportedPrograms, $scope.selectedSupportedProgram);
    updateProgramsToDisplay();
  };

  function getProgramById(id) {
    return (_.findWhere($scope.programs, {'id': id}));
  }

  var successFunc = function (data) {
    $scope.showError = "true";
    $scope.error = "";
    $scope.message = data.success;
    $scope.facility = getFacilityWithDateObjects(data.facility);
    $scope.originalFacilityCode = data.facility.code;
    $scope.originalFacilityName = data.facility.name;
  };

  var errorFunc = function (data) {
    $scope.showError = "true";
    $scope.message = "";
    $scope.error = data.data.error;
  };

  $scope.disableFacilityCallBack = function (result) {
    if (!result) return;
    Facility.remove({id: $scope.facility.id}, {}, successFunc, errorFunc);
  };

  $scope.showConfirmFacilityDisableWindow = function () {
    var dialogOpts = {
      id: "disableFacilityDialog",
      header: 'disable.facility.header',
      body: messageService.get('disable.facility.confirm', $scope.originalFacilityName, $scope.originalFacilityCode)
    };
    OpenLmisDialog.newDialog(dialogOpts, $scope.disableFacilityCallBack, $dialog);
  };

  $scope.showConfirmFacilityEnable = function () {
    var dialogOpts = {
      id: "enableConfirmModal",
      header: "create.facility.enableFacility",
      body: "'{0}' / '{1}' will be enabled in the system.".format($scope.originalFacilityName, $scope.originalFacilityCode)
    };
    OpenLmisDialog.newDialog(dialogOpts, $scope.enableFacilityCallBack, $dialog);
  };

  $scope.enableFacilityCallBack = function (result) {
    if (!result) return;
    Facility.restore({id: $scope.facility.id}, successFunc, errorFunc);
  };

  function updateProgramsToDisplay() {
    $scope.facility.supportedPrograms = $scope.facility.supportedPrograms || [];
    var supportedProgramIds = _.pluck(_.pluck($scope.facility.supportedPrograms, 'program'), "id");
    $scope.programsToDisplay = _.reject($scope.programs, function (supportedProgram) {
      return _.contains(supportedProgramIds, supportedProgram.id);
    });
    $scope.programSupportedMessage = ($scope.programsToDisplay.length) ? 'label.select.program.supported' : 'label.no.programs.left';
  }
}

FacilityController.resolve = {
  facilityReferenceData: function ($q, $timeout, FacilityReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      FacilityReferenceData.get({}, function (data) {
        deferred.resolve(data);
      }, {});
    }, 100);
    return deferred.promise;
  },
  facilityImages: function ($q,$route, $timeout, FacilityImages){
    var deferred = $q.defer();
    var facilityId = $route.current.params.facilityId;
    $timeout(function(){

       FacilityImages.get({facilityId: facilityId }, function (data){
           deferred.resolve(data);
       });
    }, 100);
    return deferred.promise;
  },

  facility: function ($q, $timeout, Facility, $route) {
    if ($route.current.params.facilityId === undefined) return undefined;

    var deferred = $q.defer();
    var facilityId = $route.current.params.facilityId;

    $timeout(function () {
      Facility.get({id: facilityId}, function (data) {
        deferred.resolve(data.facility);
      }, {});
    }, 100);
    return deferred.promise;
  }
};

<commit_msg>ELMIS-1219: Fix add facility button<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

function FacilityController($scope, facilityReferenceData, $routeParams, facility, Facility, $location, FacilityProgramProducts, FacilityImages, facilityImages, $q, $dialog, messageService) {
  $scope.$parent.facilityId = null;
  $scope.message = "";
  initialize();

  function initialize() {
    $scope.facilityTypes = facilityReferenceData.facilityTypes;
    $scope.geographicZones = facilityReferenceData.geographicZones;
    $scope.facilityOperators = facilityReferenceData.facilityOperators;
    $scope.images = facilityImages.images;
    $scope.programs = facilityReferenceData.programs;
    if ($routeParams.facilityId) {
      $scope.facility = getFacilityWithDateObjects(facility);
      $scope.originalFacilityCode = facility.code;
      $scope.originalFacilityName = facility.name;
      $scope.isEdit = true;
      updateProgramsToDisplay();
    } else {
      $scope.facility = {};
      updateProgramsToDisplay();
      $scope.facility.enabled = true;
    }
    $scope.facilityProgramProductsList = [];
  }

  function convertStringToCorrectDateFormat(stringDate) {
    if (stringDate) {
      return stringDate.split("-").reverse().join("-");
    }
    return null;
  }

  function getFacilityWithDateObjects(facility) {
    angular.forEach(facility.supportedPrograms, function (supportedProgram) {
      if (supportedProgram.startDate) {
        supportedProgram.startDate = supportedProgram.stringStartDate;
      }
    });

    facility.goLiveDate = convertStringToCorrectDateFormat(facility.stringGoLiveDate);
    facility.goDownDate = convertStringToCorrectDateFormat(facility.stringGoDownDate);

    return facility;
  }

  $scope.showISAEditModal = function (supportedProgram) {
    $scope.currentProgram = supportedProgram.program;
    $scope.$broadcast('showISAEditModal');
  };

  $scope.cancelUserSave = function () {
    $location.path('#/search');
  };

  function saveAllocationProgramProducts() {
    var promises = [];

    var keys = _.keys($scope.facilityProgramProductsList);

    $(keys).each(function (index, key) {
      var deferred = $q.defer();
      promises.push(deferred.promise);

      var program = $scope.facilityProgramProductsList[key][0].program;

      FacilityProgramProducts.update({facilityId: $scope.facility.id, programId: program.id}, $scope.facilityProgramProductsList[key], function (data) {
        deferred.resolve();
      }, function () {
        deferred.reject({error: "error.facility.allocation.product.save", program: program.name});
      });
    });

    return promises;
  }

  $scope.saveFacility = function () {
    if ($scope.facilityForm.$error.pattern || $scope.facilityForm.$error.required) {
      $scope.showError = "true";
      $scope.error = 'form.error';
      $scope.message = "";
      return;
    }

    var facilitySaveCallback = function (data) {
      $scope.facility = data.facility;
      var promises = saveAllocationProgramProducts();

      $q.all(promises).then(function () {
        $scope.showError = "true";
        $scope.error = "";
        $scope.errorProgram = "";
        $scope.$parent.message = data.success;
        $scope.facility = getFacilityWithDateObjects(data.facility);
        $scope.$parent.facilityId = $scope.facility.id;
        $location.path('');
      }, function (error) {
        $scope.showError = "true";
        $scope.message = "";
        $scope.error = error.error;
        $scope.errorProgram = error.program;
      });
    };

    if (!$scope.isEdit) {
      Facility.save({}, $scope.facility, facilitySaveCallback, errorFunc);
    } else {
      Facility.update({id: $scope.facility.id}, $scope.facility, facilitySaveCallback, errorFunc);
    }
  };

  $scope.blurDateFields = function () {
    angular.element("input[ui-date]").blur();
  };

  $scope.addSupportedProgram = function (supportedProgram) {
    if (supportedProgram.active && !supportedProgram.editedStartDate) {
      $scope.showDateNotEnteredError = true;
      return;
    }
    supportedProgram.program = getProgramById(supportedProgram.program.id);
    $scope.facility.supportedPrograms.push(supportedProgram);
    $scope.showDateNotEnteredError = false;
    $scope.supportedProgram = undefined;
    updateProgramsToDisplay();
  };

  $scope.showConfirmDateChangeWindow = function (program) {
    window.program = program;
    if (getProgramById(program.program.id).push) {
      $scope.dateChangeCallback(true);
      return;
    }
    var dialogOpts = {
      id: "dateChangeConfirmModal",
      header: 'message.setProgramStartDate',
      body: 'message.dateChangeConfirmMessage'
    };
    OpenLmisDialog.newDialog(dialogOpts, $scope.dateChangeCallback, $dialog);
  };

  $scope.dateChangeCallback = function (result) {
    if (result) {
      window.program.startDate = window.program.editedStartDate;
    } else {
      window.program.editedStartDate = window.program.startDate;
    }
  };

  $scope.showRemoveProgramConfirmDialog = function (supportedProgram) {
    $scope.selectedSupportedProgram = supportedProgram;
    var options = {
      id: "removeProgramConfirmDialog",
      header: 'delete.facility.program.header',
      body: messageService.get('delete.facility.program.confirm', $scope.selectedSupportedProgram.program.name)
    };
    OpenLmisDialog.newDialog(options, $scope.removeSupportedProgramConfirm, $dialog);
  };

  $scope.removeSupportedProgramConfirm = function (result) {
    if (result) {
      $scope.removeSupportedProgram();
    }
    $scope.selectedSupportedProgram = undefined;
  };

  $scope.removeSupportedProgram = function () {
    $scope.facility.supportedPrograms = _.without($scope.facility.supportedPrograms, $scope.selectedSupportedProgram);
    updateProgramsToDisplay();
  };

  function getProgramById(id) {
    return (_.findWhere($scope.programs, {'id': id}));
  }

  var successFunc = function (data) {
    $scope.showError = "true";
    $scope.error = "";
    $scope.message = data.success;
    $scope.facility = getFacilityWithDateObjects(data.facility);
    $scope.originalFacilityCode = data.facility.code;
    $scope.originalFacilityName = data.facility.name;
  };

  var errorFunc = function (data) {
    $scope.showError = "true";
    $scope.message = "";
    $scope.error = data.data.error;
  };

  $scope.disableFacilityCallBack = function (result) {
    if (!result) return;
    Facility.remove({id: $scope.facility.id}, {}, successFunc, errorFunc);
  };

  $scope.showConfirmFacilityDisableWindow = function () {
    var dialogOpts = {
      id: "disableFacilityDialog",
      header: 'disable.facility.header',
      body: messageService.get('disable.facility.confirm', $scope.originalFacilityName, $scope.originalFacilityCode)
    };
    OpenLmisDialog.newDialog(dialogOpts, $scope.disableFacilityCallBack, $dialog);
  };

  $scope.showConfirmFacilityEnable = function () {
    var dialogOpts = {
      id: "enableConfirmModal",
      header: "create.facility.enableFacility",
      body: "'{0}' / '{1}' will be enabled in the system.".format($scope.originalFacilityName, $scope.originalFacilityCode)
    };
    OpenLmisDialog.newDialog(dialogOpts, $scope.enableFacilityCallBack, $dialog);
  };

  $scope.enableFacilityCallBack = function (result) {
    if (!result) return;
    Facility.restore({id: $scope.facility.id}, successFunc, errorFunc);
  };

  function updateProgramsToDisplay() {
    $scope.facility.supportedPrograms = $scope.facility.supportedPrograms || [];
    var supportedProgramIds = _.pluck(_.pluck($scope.facility.supportedPrograms, 'program'), "id");
    $scope.programsToDisplay = _.reject($scope.programs, function (supportedProgram) {
      return _.contains(supportedProgramIds, supportedProgram.id);
    });
    $scope.programSupportedMessage = ($scope.programsToDisplay.length) ? 'label.select.program.supported' : 'label.no.programs.left';
  }
}

FacilityController.resolve = {
  facilityReferenceData: function ($q, $timeout, FacilityReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      FacilityReferenceData.get({}, function (data) {
        deferred.resolve(data);
      }, {});
    }, 100);
    return deferred.promise;
  },
  facilityImages: function ($q,$route, $timeout, FacilityImages){
    var deferred = $q.defer();
    var facilityId = $route.current.params.facilityId;
    $timeout(function(){
        if(!isUndefined(facilityId)){
            FacilityImages.get({facilityId: facilityId }, function (data){
                deferred.resolve(data);
            });
        }else{
            deferred.resolve([]);
        }
    }, 100);
    return deferred.promise;
  },

  facility: function ($q, $timeout, Facility, $route) {
    if ($route.current.params.facilityId === undefined) return undefined;

    var deferred = $q.defer();
    var facilityId = $route.current.params.facilityId;

    $timeout(function () {
      Facility.get({id: facilityId}, function (data) {
        deferred.resolve(data.facility);
      }, {});
    }, 100);
    return deferred.promise;
  }
};

<|endoftext|>


<commit_before>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;

function PlayerMenu(world) {
    this.__init__(world);
}

function MenuIcon(icon_type, world, row) {
    this.__init__(icon_type, world, row);
}

MenuIcon.prototype = {
    __init__: function(icon_type, world, row) {
        this.world = world;
        this.row = row;
        this.object3D = new THREE.Object3D();

        for (var i = 0; i < MANAGER_WORLD.icon_textures.length; i++) {
            if (MANAGER_WORLD.icon_textures[i][1].includes(icon_type)) {
                this.geometry = new THREE.CircleGeometry(10, 32);
                // TODO : Eventually just do FrontSide
                // TODO : Eventually add some transparency.
                this.material = new THREE.MeshBasicMaterial({map: MANAGER_WORLD.icon_textures[i][0], side: THREE.DoubleSide, transparent: true, opacity: .75});
                //var cursor_material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: CURSOR_DEFAULT_OPACITY});
                this.icon = new THREE.Mesh(this.geometry, this.material);

                this.object3D.add(this.icon);

                this.world.add_to_scene(this.object3D);
            }
        }
    },

    set_position_and_normal: function(position, nx, nz) {
        this.y_position = position.y - (this.row - 1) * SPACE_BETWEEN_MENU_ICONS;
        this.object3D.position.set(position.x, this.y_position, position.z);
        this.object3D.lookAt(new THREE.Vector3(position.x + nx * 5, position.y - (this.row - 1) * SPACE_BETWEEN_MENU_ICONS, position.z + nz * 5));
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
    }
};

PlayerMenu.prototype = {

    world: null,

    __init__: function(world) {
        this.world = world;

        this.visible = false;
        this.total_delta = 0;

        this.time_needed_for_each_row = ONE_SECOND / 5;
        this.total_distance = 5 * SPACE_BETWEEN_MENU_ICONS;
    },

    set_to_invisible: function() {
        this.visible = false;
    },

    set_to_visible: function() {
        this.visible = true;
        this.total_delta = 0;

        var pp = CURRENT_PLAYER.get_position();
        var pd = CURRENT_PLAYER.get_direction();

        var start_position = new THREE.Vector3(pp.x + pd.x * 100, pp.y + pd.y * 100, pp.z + pd.z * 100);

        this.icon_create_entity_group.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_save.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_settings.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_home.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_multiplayer.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_log_out.set_position_and_normal(start_position, -pd.x, -pd.z);
    },

    is_visible: function() {
        return this.visible;
    },

    update: function(delta) {
        this.total_delta += delta;
        if (this.total_delta >= 1.0) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / 1.0;
        }

        for (var i = 0; i < this.icons.length; i++) {
            if (this.icons[i].row !== 0) {
                var this_icons_max_delta = this.time_needed_for_each_row * this.icons[i].row;
                if (this.percentage < this_icons_max_delta) {
                    this.icons[i].update_y_position(this.percentage * this.total_distance);
                }
            }
        }
    },

    // This function gets called once per player menu object.
    load_icon_textures: function() {
        this.icon_create_entity_group = new MenuIcon(ICON_ENTITY_GROUP, this.world, 0);
        this.icon_save = new MenuIcon(ICON_SAVE, this.world, 1);
        this.icon_settings = new MenuIcon(ICON_SETTINGS, this.world, 2);
        this.icon_home = new MenuIcon(ICON_HOME, this.world, 3);
        this.icon_multiplayer = new MenuIcon(ICON_MULTIPLAYER, this.world, 4);
        this.icon_log_out = new MenuIcon(ICON_EXIT, this.world, 5);

        this.icons = [this.icon_create_entity_group, this.icon_save, this.icon_settings, this.icon_home, this.icon_multiplayer, this.icon_log_out];
    }

};
<commit_msg>general updating 76<commit_after>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;

function PlayerMenu(world) {
    this.__init__(world);
}

function MenuIcon(icon_type, world, row) {
    this.__init__(icon_type, world, row);
}

MenuIcon.prototype = {
    __init__: function(icon_type, world, row) {
        this.world = world;
        this.row = row;
        this.object3D = new THREE.Object3D();

        for (var i = 0; i < MANAGER_WORLD.icon_textures.length; i++) {
            if (MANAGER_WORLD.icon_textures[i][1].includes(icon_type)) {
                this.geometry = new THREE.CircleGeometry(10, 32);
                // TODO : Eventually just do FrontSide
                // TODO : Eventually add some transparency.
                this.material = new THREE.MeshBasicMaterial({map: MANAGER_WORLD.icon_textures[i][0], side: THREE.DoubleSide, transparent: true, opacity: .75});
                //var cursor_material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: CURSOR_DEFAULT_OPACITY});
                this.icon = new THREE.Mesh(this.geometry, this.material);

                this.object3D.add(this.icon);

                this.world.add_to_scene(this.object3D);
            }
        }
    },

    set_position_and_normal: function(position, nx, nz) {
        this.y_position = position.y + SPACE_BETWEEN_MENU_ICONS * 2;
        this.object3D.position.set(position.x, this.y_position, position.z);
        this.object3D.lookAt(new THREE.Vector3(position.x + nx * 5, position.y - (this.row - 1) * SPACE_BETWEEN_MENU_ICONS, position.z + nz * 5));
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
    }
};

PlayerMenu.prototype = {

    world: null,

    __init__: function(world) {
        this.world = world;

        this.visible = false;
        this.total_delta = 0;

        this.time_needed_for_each_row = ONE_SECOND / 5;
        this.total_distance = 5 * SPACE_BETWEEN_MENU_ICONS;
    },

    set_to_invisible: function() {
        this.visible = false;
    },

    set_to_visible: function() {
        this.visible = true;
        this.total_delta = 0;

        var pp = CURRENT_PLAYER.get_position();
        var pd = CURRENT_PLAYER.get_direction();

        var start_position = new THREE.Vector3(pp.x + pd.x * 100, pp.y + pd.y * 100, pp.z + pd.z * 100);

        this.icon_create_entity_group.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_save.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_settings.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_home.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_multiplayer.set_position_and_normal(start_position, -pd.x, -pd.z);
        this.icon_log_out.set_position_and_normal(start_position, -pd.x, -pd.z);
    },

    is_visible: function() {
        return this.visible;
    },

    update: function(delta) {
        this.total_delta += delta;
        if (this.total_delta >= 1.0) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / 1.0;
        }

        for (var i = 0; i < this.icons.length; i++) {
            if (this.icons[i].row !== 0) {
                var this_icons_max_delta = this.time_needed_for_each_row * this.icons[i].row;
                if (this.percentage < this_icons_max_delta) {
                    this.icons[i].update_y_position(this.percentage * this.total_distance);
                }
            }
        }
    },

    // This function gets called once per player menu object.
    load_icon_textures: function() {
        this.icon_create_entity_group = new MenuIcon(ICON_ENTITY_GROUP, this.world, 0);
        this.icon_save = new MenuIcon(ICON_SAVE, this.world, 1);
        this.icon_settings = new MenuIcon(ICON_SETTINGS, this.world, 2);
        this.icon_home = new MenuIcon(ICON_HOME, this.world, 3);
        this.icon_multiplayer = new MenuIcon(ICON_MULTIPLAYER, this.world, 4);
        this.icon_log_out = new MenuIcon(ICON_EXIT, this.world, 5);

        this.icons = [this.icon_create_entity_group, this.icon_save, this.icon_settings, this.icon_home, this.icon_multiplayer, this.icon_log_out];
    }

};
<|endoftext|>


<commit_before>import React, {Component} from '../base-react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import remote from 'remote'
import {ipcRenderer} from 'electron'

const currentWindow = remote.getCurrentWindow()

window.console.log = (...args) => ipcRenderer.send('console.log', args)

window.console.warn = (...args) => ipcRenderer.send('console.warn', args)

window.console.error = (...args) => ipcRenderer.send('console.error', args)

class RemoteStore {
  constructor (props) {
    ipcRenderer.on('stateChange', (event, arg) => {
      this.internalState = props.substore ? {[props.substore]: arg} : arg
      this._publishChange()
    })

    ipcRenderer.send('subscribeStore', props.substore)

    this.listeners = []
    this.internalState = {}
  }

  getState () {
    return this.internalState
  }

  dispatch (action) {
    // TODO use our middlewares
    if (action.constructor === Function) {
      action(a => this.dispatch(a), () => this.getState())
    } else {
      ipcRenderer.send('dispatchAction', action)
    }
  }

  subscribe (listener) {
    this.listeners.push(listener)
    return listener => {
      this.listeners = this.listeners.filter(l => l !== listener)
    }
  }

  _publishChange () {
    this.listeners.forEach(l => {
      setImmediate(l)
    })
  }
}

class RemoteComponentLoader extends Component {
  constructor (props) {
    super(props)
    this.state = {loaded: false, unmounted: false}

    const payload = window.location.hash.substring(1).split(':')
    const substore = payload && payload.length > 1 && payload[1]
    this.store = new RemoteStore({substore})
    this.store.dispatch = this.store.dispatch.bind(this.store)

    const componentToLoad = payload && payload.length && payload[0]

    if (!componentToLoad) {
      throw new TypeError('Remote Component not passed through hash')
    }

    const component = require('../' + componentToLoad)
    this.Component = component.default || component
  }

  componentWillMount () {
    currentWindow.on('hasProps', props => {
      // Maybe we need to wait for the state to arrive at the beginning
      if (props.waitForState &&
          // Make sure we only do this if we haven't loaded the state yet
          !this.state.loaded &&
          // Only do this if the store hasn't been filled yet.
          Object.keys(this.store.getState()).length === 0) {
        const unsub = this.store.subscribe(() => {
          currentWindow.show()
          this.setState({props: props, loaded: true})
          unsub()
        })
      } else {
        // If we've received props, and the loaded state was false
        // That means we should show the window
        if (this.state.loaded === false) {
          currentWindow.show()
        }
        setImmediate(() => this.setState({props: props, loaded: true}))
      }
    })

    ipcRenderer.on('remoteUnmount', () => {
      setImmediate(() => this.setState({unmounted: true}))
      // Hide the window since we've effective told it to close
      currentWindow.hide()
    })
    ipcRenderer.send('registerRemoteUnmount', currentWindow.id)

    currentWindow.emit('needProps')
  }

  componentDidUpdate (prevProps, prevState) {
    if (!prevState.unmounted && this.state.unmounted) {
      // Close the window now that the remote-components unmount lifecycle method has finished
      currentWindow.close()
    }
  }

  componentWillUnmount () {
    ipcRenderer.removeAllListeners('hasProps')
  }

  render () {
    const Component = this.Component
    if (!this.state.loaded) {
      return
loading

    }
    if (this.state.unmounted) {
      return

    }
    return (
      <Provider store={this.store}>
        <Component {...this.state.props}/>
      </Provider>
    )
  }
}

ReactDOM.render(<RemoteComponentLoader/>, document.getElementById('remoteComponent'))
<commit_msg>comment typos<commit_after>import React, {Component} from '../base-react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import remote from 'remote'
import {ipcRenderer} from 'electron'

const currentWindow = remote.getCurrentWindow()

window.console.log = (...args) => ipcRenderer.send('console.log', args)

window.console.warn = (...args) => ipcRenderer.send('console.warn', args)

window.console.error = (...args) => ipcRenderer.send('console.error', args)

class RemoteStore {
  constructor (props) {
    ipcRenderer.on('stateChange', (event, arg) => {
      this.internalState = props.substore ? {[props.substore]: arg} : arg
      this._publishChange()
    })

    ipcRenderer.send('subscribeStore', props.substore)

    this.listeners = []
    this.internalState = {}
  }

  getState () {
    return this.internalState
  }

  dispatch (action) {
    // TODO use our middlewares
    if (action.constructor === Function) {
      action(a => this.dispatch(a), () => this.getState())
    } else {
      ipcRenderer.send('dispatchAction', action)
    }
  }

  subscribe (listener) {
    this.listeners.push(listener)
    return listener => {
      this.listeners = this.listeners.filter(l => l !== listener)
    }
  }

  _publishChange () {
    this.listeners.forEach(l => {
      setImmediate(l)
    })
  }
}

class RemoteComponentLoader extends Component {
  constructor (props) {
    super(props)
    this.state = {loaded: false, unmounted: false}

    const payload = window.location.hash.substring(1).split(':')
    const substore = payload && payload.length > 1 && payload[1]
    this.store = new RemoteStore({substore})
    this.store.dispatch = this.store.dispatch.bind(this.store)

    const componentToLoad = payload && payload.length && payload[0]

    if (!componentToLoad) {
      throw new TypeError('Remote Component not passed through hash')
    }

    const component = require('../' + componentToLoad)
    this.Component = component.default || component
  }

  componentWillMount () {
    currentWindow.on('hasProps', props => {
      // Maybe we need to wait for the state to arrive at the beginning
      if (props.waitForState &&
          // Make sure we only do this if we haven't loaded the state yet
          !this.state.loaded &&
          // Only do this if the store hasn't been filled yet
          Object.keys(this.store.getState()).length === 0) {
        const unsub = this.store.subscribe(() => {
          currentWindow.show()
          this.setState({props: props, loaded: true})
          unsub()
        })
      } else {
        // If we've received props, and the loaded state was false, that
        // means we should show the window
        if (this.state.loaded === false) {
          currentWindow.show()
        }
        setImmediate(() => this.setState({props: props, loaded: true}))
      }
    })

    ipcRenderer.on('remoteUnmount', () => {
      setImmediate(() => this.setState({unmounted: true}))
      // Hide the window since we've effectively told it to close
      currentWindow.hide()
    })
    ipcRenderer.send('registerRemoteUnmount', currentWindow.id)

    currentWindow.emit('needProps')
  }

  componentDidUpdate (prevProps, prevState) {
    if (!prevState.unmounted && this.state.unmounted) {
      // Close the window now that the remote-component's unmount
      // lifecycle method has finished
      currentWindow.close()
    }
  }

  componentWillUnmount () {
    ipcRenderer.removeAllListeners('hasProps')
  }

  render () {
    const Component = this.Component
    if (!this.state.loaded) {
      return
loading

    }
    if (this.state.unmounted) {
      return

    }
    return (
      <Provider store={this.store}>
        <Component {...this.state.props}/>
      </Provider>
    )
  }
}

ReactDOM.render(<RemoteComponentLoader/>, document.getElementById('remoteComponent'))
<|endoftext|>


<commit_before>(function (angular) {
    'use strict';

    angular
        .module('mllApp.upload')
        .controller('MusicSummaryFormController', MusicSummaryFormController);

    MusicSummaryFormController.$inject = ['$state', 'authenticationService'];

    function MusicSummaryFormController($state, authenticationService) {
        this.authService = authenticationService;

        this.quit = () => {
            $state.go(this.authService.details.data.type, { id: this.authService.details.data.id });
        };
    }
})(window.angular);<commit_msg>MUS-109: added reload = true for this transition<commit_after>(function (angular) {
    'use strict';

    angular
        .module('mllApp.upload')
        .controller('MusicSummaryFormController', MusicSummaryFormController);

    MusicSummaryFormController.$inject = ['$state', 'authenticationService'];

    function MusicSummaryFormController($state, authenticationService) {
        this.authService = authenticationService;

        this.quit = () => {
            $state.go(this.authService.details.data.type, { id: this.authService.details.data.id }, {reload: true});
        };
    }
})(window.angular);<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function() {
  /* global React */
  class CalendarAlarmWidget extends React.Component {
    componentDidMount() {
      this.addAttributes(this.props.isSelected);
    }

    componentWillReceiveProps(nextProps) {
      // need to call removeAttributes first so that previous render attributes are removed
      this.removeAttributes();
      this.addAttributes(nextProps.isSelected);
    }

    addAttributes(isWidgetSelected) {
      if (isWidgetSelected) {
        this.widget.setAttribute("selected", "true");
      }
    }

    removeAttributes() {
      this.widget.removeAttribute("selected");
    }

    render() {
      const { time, name, snoozeAlarm, dismissAlarm } = this.props;
      // replace this function while integrating
      const showDetails = () => {};

      return (

 (this.widget = node)}
          onClick={this.props.onClick}
        >

{name}

{time}

Details...

{time}

            <SnoozeButton onClick={snoozeAlarm} type="single" />
            <button className="alarm-dismiss-button" onClick={dismissAlarm}>Dismiss</button>

      );
    }
  }

  CalendarAlarmWidget.propTypes = {
    isSelected: PropTypes.bool.isRequired,
    onClick: PropTypes.func.isRequired,
    name: PropTypes.string.isRequired,
    time: PropTypes.string.isRequired,
    snoozeAlarm: PropTypes.func.isRequired,
    dismissAlarm: PropTypes.func.isRequired
  };

  window.CalendarAlarmWidget = CalendarAlarmWidget;
})();
<commit_msg>ready to integrate<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function () {
  /* global React, Redux, ReactRedux */
  const { connect } = ReactRedux;
  const { bindActionCreators } = Redux;

  class CalendarAlarmWidget extends React.Component {
    componentDidMount() {
      this.addAttributes(this.props.isSelected);
    }

    componentWillReceiveProps(nextProps) {
      // need to call removeAttributes first so that previous render attributes are removed
      this.removeAttributes();
      this.addAttributes(nextProps.isSelected);
    }

    addAttributes(isWidgetSelected) {
      if (isWidgetSelected) {
        this.widget.setAttribute("selected", "true");
      }
    }

    removeAttributes() {
      this.widget.removeAttribute("selected");
    }

    render() {
      const { time, name, snoozeAlarm, dismissAlarm } = this.props;
      // replace this function while integrating
      const showDetails = () => { };

      return (

 (this.widget = node)}
          onClick={this.props.onClick}
        >

{name}

{time}

Details...

{time}

            <SnoozeButton onClick={snoozeAlarm} type="single" />
            <button className="alarm-dismiss-button" onClick={dismissAlarm}>Dismiss</button>

      );
    }
  }

  CalendarAlarmWidget.propTypes = {
    isSelected: PropTypes.bool.isRequired,
    onClick: PropTypes.func.isRequired,
    name: PropTypes.string.isRequired,
    time: PropTypes.string.isRequired,
    snoozeAlarm: PropTypes.func.isRequired,
    dismissAlarm: PropTypes.func.isRequired,
    actions: PropTypes.func.isRequired
  };

  const mapDispatchToProps = dispatch => ({
    actions: bindActionCreators(window.__single_alarm_actions__, dispatch)
  });

  window.CalendarAlarmWidget = connect(undefined, mapDispatchToProps)(CalendarAlarmWidget);
})();
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

const {Set, Hash} = require('./../Utils');

/**
 * A tree structure used to record the semantic context in which
 * an ATN configuration is valid.  It's either a single predicate,
 * a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
 *
 *
I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of
 * {@link SemanticContext} within the scope of this outer class.

 */
class SemanticContext {
	hashCode() {
		const hash = new Hash();
		this.updateHashCode(hash);
		return hash.finish();
	}

	/**
	 * For context independent predicates, we evaluate them without a local
	 * context (i.e., null context). That way, we can evaluate them without
	 * having to create proper rule-specific context during prediction (as
	 * opposed to the parser, which creates them naturally). In a practical
	 * sense, this avoids a cast exception from RuleContext to myruleContext.
	 *
	 *
For context dependent predicates, we must pass in a local context so that
	 * references such as $arg evaluate properly as _localctx.arg. We only
	 * capture context dependent predicates in the context in which we begin
	 * prediction, so we passed in the outer context here in case of context
	 * dependent predicate evaluation.

	 */
	evaluate(parser, outerContext) {}

	/**
	 * Evaluate the precedence predicates for the context and reduce the result.
	 *
	 * @param parser The parser instance.
	 * @param outerContext The current parser context object.
	 * @return The simplified semantic context after precedence predicates are
	 * evaluated, which will be one of the following values.
	 *

	 *
{@link //NONE}: if the predicate simplifies to {@code true} after
	 * precedence predicates are evaluated.

	 *
{@code null}: if the predicate simplifies to {@code false} after
	 * precedence predicates are evaluated.

	 *
{@code this}: if the semantic context is not changed as a result of
	 * precedence predicate evaluation.

	 *
A non-{@code null} {@link SemanticContext}: the new simplified
	 * semantic context after precedence predicates are evaluated.

	 *

	 */
	evalPrecedence(parser, outerContext) {
		return this;
	}

	static andContext(a, b) {
		if (a === null || a === SemanticContext.NONE) {
			return b;
		}
		if (b === null || b === SemanticContext.NONE) {
			return a;
		}
		const result = new AND(a, b);
		if (result.opnds.length === 1) {
			return result.opnds[0];
		} else {
			return result;
		}
	}

	static orContext(a, b) {
		if (a === null) {
			return b;
		}
		if (b === null) {
			return a;
		}
		if (a === SemanticContext.NONE || b === SemanticContext.NONE) {
			return SemanticContext.NONE;
		}
		const result = new OR(a, b);
		if (result.opnds.length === 1) {
			return result.opnds[0];
		} else {
			return result;
		}
	}
}

class Predicate extends SemanticContext {
	constructor(ruleIndex, predIndex, isCtxDependent) {
		super();
		this.ruleIndex = ruleIndex === undefined ? -1 : ruleIndex;
		this.predIndex = predIndex === undefined ? -1 : predIndex;
		this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred
		return this;
	}

	evaluate(parser, outerContext) {
		const localctx = this.isCtxDependent ? outerContext : null;
		return parser.sempred(localctx, this.ruleIndex, this.predIndex);
	}

	updateHashCode(hash) {
		hash.update(this.ruleIndex, this.predIndex, this.isCtxDependent);
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof Predicate)) {
			return false;
		} else {
			return this.ruleIndex === other.ruleIndex &&
					this.predIndex === other.predIndex &&
					this.isCtxDependent === other.isCtxDependent;
		}
	}

	toString() {
		return "{" + this.ruleIndex + ":" + this.predIndex + "}?";
	}
}

/**
 * The default {@link SemanticContext}, which is semantically equivalent to
 * a predicate of the form {@code {true}?}
 */
SemanticContext.NONE = new Predicate();

class PrecedencePredicate extends SemanticContext {
	constructor(precedence) {
		super();
		this.precedence = precedence === undefined ? 0 : precedence;
	}

	evaluate(parser, outerContext) {
		return parser.precpred(outerContext, this.precedence);
	}

	evalPrecedence(parser, outerContext) {
		if (parser.precpred(outerContext, this.precedence)) {
			return SemanticContext.NONE;
		} else {
			return null;
		}
	}

	compareTo(other) {
		return this.precedence - other.precedence;
	}

	updateHashCode(hash) {
		hash.update(31);
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof PrecedencePredicate)) {
			return false;
		} else {
			return this.precedence === other.precedence;
		}
	}

	toString() {
		return "{"+this.precedence+">=prec}?";
	}

	static filterPrecedencePredicates(set) {
		const result = [];
		set.values().map( function(context) {
			if (context instanceof PrecedencePredicate) {
				result.push(context);
			}
		});
		return result;
	}
}

class AND extends SemanticContext {
	/**
	 * A semantic context which is true whenever none of the contained contexts
	 * is false
	 */
	constructor(a, b) {
		super();
		const operands = new Set();
		if (a instanceof AND) {
			a.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(a);
		}
		if (b instanceof AND) {
			b.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(b);
		}
		const precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
		if (precedencePredicates.length > 0) {
			// interested in the transition with the lowest precedence
			let reduced = null;
			precedencePredicates.map( function(p) {
				if(reduced===null || p.precedence<reduced.precedence) {
					reduced = p;
				}
			});
			operands.add(reduced);
		}
		this.opnds = operands.values();
		return this;
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof AND)) {
			return false;
		} else {
			return this.opnds === other.opnds;
		}
	}

	updateHashCode(hash) {
		hash.update(this.opnds, "AND");
	}

	/**
	 * {@inheritDoc}
	 *
	 *

	 * The evaluation of predicates by this context is short-circuiting, but
	 * unordered.

	 */
	evaluate(parser, outerContext) {
		for (let i = 0; i < this.opnds.length; i++) {
			if (!this.opnds[i].evaluate(parser, outerContext)) {
				return false;
			}
		}
		return true;
	}

	evalPrecedence(parser, outerContext) {
		let differs = false;
		const operands = [];
		for (let i = 0; i < this.opnds.length; i++) {
			const context = this.opnds[i];
			const evaluated = context.evalPrecedence(parser, outerContext);
			differs |= (evaluated !== context);
			if (evaluated === null) {
				// The AND context is false if any element is false
				return null;
			} else if (evaluated !== SemanticContext.NONE) {
				// Reduce the result by skipping true elements
				operands.push(evaluated);
			}
		}
		if (!differs) {
			return this;
		}
		if (operands.length === 0) {
			// all elements were true, so the AND context is true
			return SemanticContext.NONE;
		}
		let result = null;
		operands.map(function(o) {
			result = result === null ? o : SemanticContext.andContext(result, o);
		});
		return result;
	}

	toString() {
		let s = "";
		this.opnds.map(function(o) {
			s += "&& " + o.toString();
		});
		return s.length > 3 ? s.slice(3) : s;
	}
}

class OR extends SemanticContext {
	/**
	 * A semantic context which is true whenever at least one of the contained
	 * contexts is true
	 */
	constructor(a, b) {
		super();
		const operands = new Set();
		if (a instanceof OR) {
			a.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(a);
		}
		if (b instanceof OR) {
			b.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(b);
		}

		const precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
		if (precedencePredicates.length > 0) {
			// interested in the transition with the highest precedence
			const s = precedencePredicates.sort(function(a, b) {
				return a.compareTo(b);
			});
			const reduced = s[s.length-1];
			operands.add(reduced);
		}
		this.opnds = operands.values();
		return this;
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof OR)) {
			return false;
		} else {
			return this.opnds === other.opnds;
		}
	}

	updateHashCode(hash) {
		hash.update(this.opnds, "OR");
	}

	/**
	 *

	 * The evaluation of predicates by this context is short-circuiting, but
	 * unordered.

	 */
	evaluate(parser, outerContext) {
		for (let i = 0; i < this.opnds.length; i++) {
			if (this.opnds[i].evaluate(parser, outerContext)) {
				return true;
			}
		}
		return false;
	}

	evalPrecedence(parser, outerContext) {
		let differs = false;
		const operands = [];
		for (let i = 0; i < this.opnds.length; i++) {
			const context = this.opnds[i];
			const evaluated = context.evalPrecedence(parser, outerContext);
			differs |= (evaluated !== context);
			if (evaluated === SemanticContext.NONE) {
				// The OR context is true if any element is true
				return SemanticContext.NONE;
			} else if (evaluated !== null) {
				// Reduce the result by skipping false elements
				operands.push(evaluated);
			}
		}
		if (!differs) {
			return this;
		}
		if (operands.length === 0) {
			// all elements were false, so the OR context is false
			return null;
		}
		const result = null;
		operands.map(function(o) {
			return result === null ? o : SemanticContext.orContext(result, o);
		});
		return result;
	}

	toString() {
		let s = "";
		this.opnds.map(function(o) {
			s += "|| " + o.toString();
		});
		return s.length > 3 ? s.slice(3) : s;
	}
}

module.exports = {
	SemanticContext,
	PrecedencePredicate,
	Predicate
}
<commit_msg>fix: no need for return on constructor<commit_after>/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

const {Set, Hash} = require('./../Utils');

/**
 * A tree structure used to record the semantic context in which
 * an ATN configuration is valid.  It's either a single predicate,
 * a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
 *
 *
I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of
 * {@link SemanticContext} within the scope of this outer class.

 */
class SemanticContext {
	hashCode() {
		const hash = new Hash();
		this.updateHashCode(hash);
		return hash.finish();
	}

	/**
	 * For context independent predicates, we evaluate them without a local
	 * context (i.e., null context). That way, we can evaluate them without
	 * having to create proper rule-specific context during prediction (as
	 * opposed to the parser, which creates them naturally). In a practical
	 * sense, this avoids a cast exception from RuleContext to myruleContext.
	 *
	 *
For context dependent predicates, we must pass in a local context so that
	 * references such as $arg evaluate properly as _localctx.arg. We only
	 * capture context dependent predicates in the context in which we begin
	 * prediction, so we passed in the outer context here in case of context
	 * dependent predicate evaluation.

	 */
	evaluate(parser, outerContext) {}

	/**
	 * Evaluate the precedence predicates for the context and reduce the result.
	 *
	 * @param parser The parser instance.
	 * @param outerContext The current parser context object.
	 * @return The simplified semantic context after precedence predicates are
	 * evaluated, which will be one of the following values.
	 *

	 *
{@link //NONE}: if the predicate simplifies to {@code true} after
	 * precedence predicates are evaluated.

	 *
{@code null}: if the predicate simplifies to {@code false} after
	 * precedence predicates are evaluated.

	 *
{@code this}: if the semantic context is not changed as a result of
	 * precedence predicate evaluation.

	 *
A non-{@code null} {@link SemanticContext}: the new simplified
	 * semantic context after precedence predicates are evaluated.

	 *

	 */
	evalPrecedence(parser, outerContext) {
		return this;
	}

	static andContext(a, b) {
		if (a === null || a === SemanticContext.NONE) {
			return b;
		}
		if (b === null || b === SemanticContext.NONE) {
			return a;
		}
		const result = new AND(a, b);
		if (result.opnds.length === 1) {
			return result.opnds[0];
		} else {
			return result;
		}
	}

	static orContext(a, b) {
		if (a === null) {
			return b;
		}
		if (b === null) {
			return a;
		}
		if (a === SemanticContext.NONE || b === SemanticContext.NONE) {
			return SemanticContext.NONE;
		}
		const result = new OR(a, b);
		if (result.opnds.length === 1) {
			return result.opnds[0];
		} else {
			return result;
		}
	}
}

class Predicate extends SemanticContext {
	constructor(ruleIndex, predIndex, isCtxDependent) {
		super();
		this.ruleIndex = ruleIndex === undefined ? -1 : ruleIndex;
		this.predIndex = predIndex === undefined ? -1 : predIndex;
		this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred
	}

	evaluate(parser, outerContext) {
		const localctx = this.isCtxDependent ? outerContext : null;
		return parser.sempred(localctx, this.ruleIndex, this.predIndex);
	}

	updateHashCode(hash) {
		hash.update(this.ruleIndex, this.predIndex, this.isCtxDependent);
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof Predicate)) {
			return false;
		} else {
			return this.ruleIndex === other.ruleIndex &&
					this.predIndex === other.predIndex &&
					this.isCtxDependent === other.isCtxDependent;
		}
	}

	toString() {
		return "{" + this.ruleIndex + ":" + this.predIndex + "}?";
	}
}

/**
 * The default {@link SemanticContext}, which is semantically equivalent to
 * a predicate of the form {@code {true}?}
 */
SemanticContext.NONE = new Predicate();

class PrecedencePredicate extends SemanticContext {
	constructor(precedence) {
		super();
		this.precedence = precedence === undefined ? 0 : precedence;
	}

	evaluate(parser, outerContext) {
		return parser.precpred(outerContext, this.precedence);
	}

	evalPrecedence(parser, outerContext) {
		if (parser.precpred(outerContext, this.precedence)) {
			return SemanticContext.NONE;
		} else {
			return null;
		}
	}

	compareTo(other) {
		return this.precedence - other.precedence;
	}

	updateHashCode(hash) {
		hash.update(31);
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof PrecedencePredicate)) {
			return false;
		} else {
			return this.precedence === other.precedence;
		}
	}

	toString() {
		return "{"+this.precedence+">=prec}?";
	}

	static filterPrecedencePredicates(set) {
		const result = [];
		set.values().map( function(context) {
			if (context instanceof PrecedencePredicate) {
				result.push(context);
			}
		});
		return result;
	}
}

class AND extends SemanticContext {
	/**
	 * A semantic context which is true whenever none of the contained contexts
	 * is false
	 */
	constructor(a, b) {
		super();
		const operands = new Set();
		if (a instanceof AND) {
			a.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(a);
		}
		if (b instanceof AND) {
			b.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(b);
		}
		const precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
		if (precedencePredicates.length > 0) {
			// interested in the transition with the lowest precedence
			let reduced = null;
			precedencePredicates.map( function(p) {
				if(reduced===null || p.precedence<reduced.precedence) {
					reduced = p;
				}
			});
			operands.add(reduced);
		}
		this.opnds = operands.values();
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof AND)) {
			return false;
		} else {
			return this.opnds === other.opnds;
		}
	}

	updateHashCode(hash) {
		hash.update(this.opnds, "AND");
	}

	/**
	 * {@inheritDoc}
	 *
	 *

	 * The evaluation of predicates by this context is short-circuiting, but
	 * unordered.

	 */
	evaluate(parser, outerContext) {
		for (let i = 0; i < this.opnds.length; i++) {
			if (!this.opnds[i].evaluate(parser, outerContext)) {
				return false;
			}
		}
		return true;
	}

	evalPrecedence(parser, outerContext) {
		let differs = false;
		const operands = [];
		for (let i = 0; i < this.opnds.length; i++) {
			const context = this.opnds[i];
			const evaluated = context.evalPrecedence(parser, outerContext);
			differs |= (evaluated !== context);
			if (evaluated === null) {
				// The AND context is false if any element is false
				return null;
			} else if (evaluated !== SemanticContext.NONE) {
				// Reduce the result by skipping true elements
				operands.push(evaluated);
			}
		}
		if (!differs) {
			return this;
		}
		if (operands.length === 0) {
			// all elements were true, so the AND context is true
			return SemanticContext.NONE;
		}
		let result = null;
		operands.map(function(o) {
			result = result === null ? o : SemanticContext.andContext(result, o);
		});
		return result;
	}

	toString() {
		let s = "";
		this.opnds.map(function(o) {
			s += "&& " + o.toString();
		});
		return s.length > 3 ? s.slice(3) : s;
	}
}

class OR extends SemanticContext {
	/**
	 * A semantic context which is true whenever at least one of the contained
	 * contexts is true
	 */
	constructor(a, b) {
		super();
		const operands = new Set();
		if (a instanceof OR) {
			a.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(a);
		}
		if (b instanceof OR) {
			b.opnds.map(function(o) {
				operands.add(o);
			});
		} else {
			operands.add(b);
		}

		const precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
		if (precedencePredicates.length > 0) {
			// interested in the transition with the highest precedence
			const s = precedencePredicates.sort(function(a, b) {
				return a.compareTo(b);
			});
			const reduced = s[s.length-1];
			operands.add(reduced);
		}
		this.opnds = operands.values();
	}

	equals(other) {
		if (this === other) {
			return true;
		} else if (!(other instanceof OR)) {
			return false;
		} else {
			return this.opnds === other.opnds;
		}
	}

	updateHashCode(hash) {
		hash.update(this.opnds, "OR");
	}

	/**
	 *

	 * The evaluation of predicates by this context is short-circuiting, but
	 * unordered.

	 */
	evaluate(parser, outerContext) {
		for (let i = 0; i < this.opnds.length; i++) {
			if (this.opnds[i].evaluate(parser, outerContext)) {
				return true;
			}
		}
		return false;
	}

	evalPrecedence(parser, outerContext) {
		let differs = false;
		const operands = [];
		for (let i = 0; i < this.opnds.length; i++) {
			const context = this.opnds[i];
			const evaluated = context.evalPrecedence(parser, outerContext);
			differs |= (evaluated !== context);
			if (evaluated === SemanticContext.NONE) {
				// The OR context is true if any element is true
				return SemanticContext.NONE;
			} else if (evaluated !== null) {
				// Reduce the result by skipping false elements
				operands.push(evaluated);
			}
		}
		if (!differs) {
			return this;
		}
		if (operands.length === 0) {
			// all elements were false, so the OR context is false
			return null;
		}
		const result = null;
		operands.map(function(o) {
			return result === null ? o : SemanticContext.orContext(result, o);
		});
		return result;
	}

	toString() {
		let s = "";
		this.opnds.map(function(o) {
			s += "|| " + o.toString();
		});
		return s.length > 3 ? s.slice(3) : s;
	}
}

module.exports = {
	SemanticContext,
	PrecedencePredicate,
	Predicate
}
<|endoftext|>


<commit_before>"use strict";

//Load dependencies
var applicationStorage = process.require("core/applicationStorage.js");

/**
 * Get the projection for guild
 * @param query
 */
module.exports.get = function (query) {
    var projection = {region: 1, realm: 1, name: 1};
    if (query.view === "detailed") {
        projection["bnet.side"] = 1;
        projection["ad.language"] = 1;
        projection["ad.recruitment"] = 1;
        projection["ad.raids_per_week"] = 1;
        projection["ad.updated"] = 1;
        projection["progress.normalCount"] = 1;
        projection["progress.heroicCount"] = 1;
        projection["progress.mythicCount"] = 1;
        projection.rank = 1;
        projection["id"] = 1;
    }
    if (query.view === "minimal") {
        projection["bnet.side"] = 1;
        projection["ad.updated"] = 1;
        projection["id"] = 1;
    }
    return projection;
};
<commit_msg>Fix client progression issue<commit_after>"use strict";

//Load dependencies
var applicationStorage = process.require("core/applicationStorage.js");

/**
 * Get the projection for guild
 * @param query
 */
module.exports.get = function (query) {
    var projection = {region: 1, realm: 1, name: 1};
    if (query.view === "detailed") {
        projection["bnet.side"] = 1;
        projection["ad.language"] = 1;
        projection["ad.recruitment"] = 1;
        projection["ad.raids_per_week"] = 1;
        projection["ad.updated"] = 1;
        projection["progress.tier_18.normalCount"] = 1;
        projection["progress.tier_18.heroicCount"] = 1;
        projection["progress.tier_18.mythicCount"] = 1;
        projection.rank = 1;
        projection["id"] = 1;
    }
    if (query.view === "minimal") {
        projection["bnet.side"] = 1;
        projection["ad.updated"] = 1;
        projection["id"] = 1;
    }
    return projection;
};
<|endoftext|>


<commit_before>// @flow
import * as Selectors from '../selectors'
import * as Creators from '../../../../actions/chat/creators'
import {FilterSmallTeam} from '.'
import {pausableConnect, type TypedState} from '../../../../util/container'

const mapStateToProps = (state: TypedState, {conversationIDKey, channelname, teamname, isActiveRoute}) => {
  const p = Selectors.snippetRowSelector(state, conversationIDKey)

  return {
    backgroundColor: p.backgroundColor,
    channelname,
    hasBadge: p.hasBadge,
    hasUnread: p.hasUnread,
    isActiveRoute,
    isMuted: p.isMuted,
    isSelected: p.isSelected,
    participantNeedToRekey: p.participantNeedToRekey,
    participants: p.participants,
    showBold: p.showBold,
    teamname,
    usernameColor: p.usernameColor,
    youNeedToRekey: p.youNeedToRekey,
  }
}

const mapDispatchToProps = (dispatch: Dispatch, {conversationIDKey}) => ({
  onSelectConversation: () => {
    dispatch(Creators.setInboxFilter(''))
    dispatch(Creators.selectConversation(conversationIDKey, true))
  },
})

const mergeProps = (stateProps, dispatchProps, ownProps) => ({
  backgroundColor: stateProps.backgroundColor,
  hasBadge: stateProps.hasBadge,
  hasUnread: stateProps.hasUnread,
  isActiveRoute: ownProps.isActiveRoute,
  isMuted: stateProps.isMuted,
  isSelected: stateProps.isSelected,
  onSelectConversation: dispatchProps.onSelectConversation,
  participantNeedToRekey: stateProps.participantNeedToRekey,
  participants: stateProps.participants,
  showBold: stateProps.showBold,
  teamname: stateProps.teamname || '',
  usernameColor: stateProps.usernameColor,
  youNeedToRekey: stateProps.youNeedToRekey,
})

export default pausableConnect(mapStateToProps, mapDispatchToProps, mergeProps)(FilterSmallTeam)
<commit_msg>plumb teamname (#9223)<commit_after>// @flow
import * as Selectors from '../selectors'
import * as Creators from '../../../../actions/chat/creators'
import {FilterSmallTeam} from '.'
import {pausableConnect, type TypedState} from '../../../../util/container'

const mapStateToProps = (state: TypedState, {conversationIDKey, channelname, teamname, isActiveRoute}) => {
  const p = Selectors.snippetRowSelector(state, conversationIDKey)

  return {
    backgroundColor: p.backgroundColor,
    channelname,
    hasBadge: p.hasBadge,
    hasUnread: p.hasUnread,
    isActiveRoute,
    isMuted: p.isMuted,
    isSelected: p.isSelected,
    participantNeedToRekey: p.participantNeedToRekey,
    participants: p.participants,
    showBold: p.showBold,
    teamname: p.teamname,
    usernameColor: p.usernameColor,
    youNeedToRekey: p.youNeedToRekey,
  }
}

const mapDispatchToProps = (dispatch: Dispatch, {conversationIDKey}) => ({
  onSelectConversation: () => {
    dispatch(Creators.setInboxFilter(''))
    dispatch(Creators.selectConversation(conversationIDKey, true))
  },
})

const mergeProps = (stateProps, dispatchProps, ownProps) => ({
  backgroundColor: stateProps.backgroundColor,
  hasBadge: stateProps.hasBadge,
  hasUnread: stateProps.hasUnread,
  isActiveRoute: ownProps.isActiveRoute,
  isMuted: stateProps.isMuted,
  isSelected: stateProps.isSelected,
  onSelectConversation: dispatchProps.onSelectConversation,
  participantNeedToRekey: stateProps.participantNeedToRekey,
  participants: stateProps.participants,
  showBold: stateProps.showBold,
  teamname: stateProps.teamname || '',
  usernameColor: stateProps.usernameColor,
  youNeedToRekey: stateProps.youNeedToRekey,
})

export default pausableConnect(mapStateToProps, mapDispatchToProps, mergeProps)(FilterSmallTeam)
<|endoftext|>


<commit_before>/**
 * Note: This version requires Angular UI Bootstrap >= v0.6.0
 */

//== Controllers =============================================================//

angular.module('dialogs.controllers',['ui.bootstrap.modal'])

	/**
	 * Error Dialog Controller
	 */
	.controller('errorDialogCtrl',['$scope','$modalInstance','header','msg',function($scope,$modalInstance,header,msg){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Error';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'An unknown error has occurred.';

		//-- Methods -----//

		$scope.close = function(){
			$modalInstance.close();
		}; // end close
	}]) // end ErrorDialogCtrl

	/**
	 * Wait Dialog Controller
	 */
	.controller('waitDialogCtrl',['$scope','$modalInstance','$timeout','header','msg','progress',function($scope,$modalInstance,$timeout,header,msg,progress){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Please Wait...';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'Waiting on operation to complete.';
		$scope.progress = (angular.isDefined(progress)) ? progress : 100;

		//-- Listeners -----//

		// Note: used $timeout instead of $scope.$apply() because I was getting a $$nextSibling error

		// close wait dialog
		$scope.$on('dialogs.wait.complete',function(){
			$timeout(function(){ $modalInstance.close(); });
		}); // end on(dialogs.wait.complete)

		// update the dialog's message
		$scope.$on('dialogs.wait.message',function(evt,args){
			$scope.msg = (angular.isDefined(args.msg)) ? args.msg : $scope.msg;
		}); // end on(dialogs.wait.message)

		// update the dialog's progress (bar) and/or message
		$scope.$on('dialogs.wait.progress',function(evt,args){
			$scope.msg = (angular.isDefined(args.msg)) ? args.msg : $scope.msg;
			$scope.progress = (angular.isDefined(args.progress)) ? args.progress : $scope.progress;
		}); // end on(dialogs.wait.progress)

		//-- Methods -----//

		$scope.getProgress = function(){
			return {'width': $scope.progress + '%'};
		}; // end getProgress
	}]) // end WaitDialogCtrl

	/**
	 * Notify Dialog Controller
	 */
	.controller('notifyDialogCtrl',['$scope','$modalInstance','header','msg',function($scope,$modalInstance,header,msg){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Notification';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'Unknown application notification.';

		//-- Methods -----//

		$scope.close = function(){
			$modalInstance.close();
		}; // end close
	}]) // end WaitDialogCtrl

	/**
	 * Confirm Dialog Controller
	 */
	.controller('confirmDialogCtrl',['$scope','$modalInstance','header','msg','primaryButtonText','secondaryButtonText',function($scope,$modalInstance,header,msg,primaryButtonText,secondaryButtonText){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Confirmation';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'Confirmation required.';
		$scope.primaryButtonText = (angular.isDefined(primaryButtonText)) ? primaryButtonText : 'Yes';
		$scope.secondaryButtonText = (angular.isDefined(secondaryButtonText)) ? secondaryButtonText : 'No';

		//-- Methods -----//

		$scope.no = function(){
			$modalInstance.dismiss('no');
		}; // end close

		$scope.yes = function(){
			$modalInstance.close('yes');
		}; // end yes
	}]); // end ConfirmDialogCtrl / dialogs.controllers

//== Services ================================================================//

angular.module('dialogs.services',['ui.bootstrap.modal','dialogs.controllers'])

	/**
	 * Dialogs Service
	 */
	.factory('dialogs',['$modal',function($modal){
		return {
			error : function(header,msg){
				return $modal.open({
					templateUrl : '/dialogs/error.html',
					controller : 'errorDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); }
					}
				}); // end modal.open
			}, // end error

			wait : function(header,msg,progress){
				return $modal.open({
					templateUrl : '/dialogs/wait.html',
					controller : 'waitDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); },
						progress : function() { return angular.copy(progress); }
					}
				}); // end modal.open
			}, // end wait

			notify : function(header,msg){
				return $modal.open({
					templateUrl : '/dialogs/notify.html',
					controller : 'notifyDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); }
					}
				}); // end modal.open
			}, // end notify

			confirm : function(header,msg,primaryButtonText,secondaryButtonText){
				return $modal.open({
					templateUrl : '/dialogs/confirm.html',
					controller : 'confirmDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); },
						primaryButtonText : function() { return angular.copy(primaryButtonText); },
						secondaryButtonText : function() { return angular.copy(secondaryButtonText); }
					}
				}); // end modal.open
			}, // end confirm

			create : function(url,ctrlr,data,opts){
				var k = (angular.isDefined(opts.keyboard)) ? opts.keyboard : true; // values: true,false
				var b = (angular.isDefined(opts.backdrop)) ? opts.backdrop : true; // values: 'static',true,false
				var w = (angular.isDefined(opts.windowClass)) ? opts.windowClass : 'dialogs-default'; // additional CSS class(es) to be added to a modal window
				return $modal.open({
					templateUrl : url,
					controller : ctrlr,
					keyboard : k,
					backdrop : b,
					windowClass: w,
					resolve : {
						data : function() { return angular.copy(data); }
					}
				}); // end modal.open
			} // end confirm
		};
	}]); // end $dialogs / dialogs.services

//== Module ==================================================================//

angular.module('dialogs',['dialogs.services','ngSanitize']) // requires angular-sanitize.min.js (ngSanitize) //code.angularjs.org/1.2.1/angular-sanitize.min.js

	// Add default templates via $templateCache
	.run(['$templateCache',function($templateCache){
		$templateCache.put('/dialogs/error.html','
<button type="button" class="close" ng-click="close()">×</button>

<button type="button" class="btn btn-default" ng-click="close()">Close</button>
');
		$templateCache.put('/dialogs/wait.html','

 Please Wait

{{progress}}% Complete

');
		$templateCache.put('/dialogs/notify.html','
<button type="button" class="close" ng-click="close()" class="pull-right">×</button>
 {{header}}

<button type="button" class="btn btn-primary" ng-click="close()">OK</button>
');
		$templateCache.put('/dialogs/confirm.html','
<button type="button" class="close" ng-click="no()">×</button>
 {{header}}

<button type="button" class="btn btn-default" ng-click="yes()">{{primaryButtonText}}</button><button type="button" class="btn btn-primary" ng-click="no()">{{secondaryButtonText}}</button>
');
	}]); // end run / dialogs

<commit_msg>Made first button primary instead of second button<commit_after>/**
 * Note: This version requires Angular UI Bootstrap >= v0.6.0
 */

//== Controllers =============================================================//

angular.module('dialogs.controllers',['ui.bootstrap.modal'])

	/**
	 * Error Dialog Controller
	 */
	.controller('errorDialogCtrl',['$scope','$modalInstance','header','msg',function($scope,$modalInstance,header,msg){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Error';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'An unknown error has occurred.';

		//-- Methods -----//

		$scope.close = function(){
			$modalInstance.close();
		}; // end close
	}]) // end ErrorDialogCtrl

	/**
	 * Wait Dialog Controller
	 */
	.controller('waitDialogCtrl',['$scope','$modalInstance','$timeout','header','msg','progress',function($scope,$modalInstance,$timeout,header,msg,progress){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Please Wait...';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'Waiting on operation to complete.';
		$scope.progress = (angular.isDefined(progress)) ? progress : 100;

		//-- Listeners -----//

		// Note: used $timeout instead of $scope.$apply() because I was getting a $$nextSibling error

		// close wait dialog
		$scope.$on('dialogs.wait.complete',function(){
			$timeout(function(){ $modalInstance.close(); });
		}); // end on(dialogs.wait.complete)

		// update the dialog's message
		$scope.$on('dialogs.wait.message',function(evt,args){
			$scope.msg = (angular.isDefined(args.msg)) ? args.msg : $scope.msg;
		}); // end on(dialogs.wait.message)

		// update the dialog's progress (bar) and/or message
		$scope.$on('dialogs.wait.progress',function(evt,args){
			$scope.msg = (angular.isDefined(args.msg)) ? args.msg : $scope.msg;
			$scope.progress = (angular.isDefined(args.progress)) ? args.progress : $scope.progress;
		}); // end on(dialogs.wait.progress)

		//-- Methods -----//

		$scope.getProgress = function(){
			return {'width': $scope.progress + '%'};
		}; // end getProgress
	}]) // end WaitDialogCtrl

	/**
	 * Notify Dialog Controller
	 */
	.controller('notifyDialogCtrl',['$scope','$modalInstance','header','msg',function($scope,$modalInstance,header,msg){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Notification';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'Unknown application notification.';

		//-- Methods -----//

		$scope.close = function(){
			$modalInstance.close();
		}; // end close
	}]) // end WaitDialogCtrl

	/**
	 * Confirm Dialog Controller
	 */
	.controller('confirmDialogCtrl',['$scope','$modalInstance','header','msg','primaryButtonText','secondaryButtonText',function($scope,$modalInstance,header,msg,primaryButtonText,secondaryButtonText){
		//-- Variables -----//

		$scope.header = (angular.isDefined(header)) ? header : 'Confirmation';
		$scope.msg = (angular.isDefined(msg)) ? msg : 'Confirmation required.';
		$scope.primaryButtonText = (angular.isDefined(primaryButtonText)) ? primaryButtonText : 'Yes';
		$scope.secondaryButtonText = (angular.isDefined(secondaryButtonText)) ? secondaryButtonText : 'No';

		//-- Methods -----//

		$scope.no = function(){
			$modalInstance.dismiss('no');
		}; // end close

		$scope.yes = function(){
			$modalInstance.close('yes');
		}; // end yes
	}]); // end ConfirmDialogCtrl / dialogs.controllers

//== Services ================================================================//

angular.module('dialogs.services',['ui.bootstrap.modal','dialogs.controllers'])

	/**
	 * Dialogs Service
	 */
	.factory('dialogs',['$modal',function($modal){
		return {
			error : function(header,msg){
				return $modal.open({
					templateUrl : '/dialogs/error.html',
					controller : 'errorDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); }
					}
				}); // end modal.open
			}, // end error

			wait : function(header,msg,progress){
				return $modal.open({
					templateUrl : '/dialogs/wait.html',
					controller : 'waitDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); },
						progress : function() { return angular.copy(progress); }
					}
				}); // end modal.open
			}, // end wait

			notify : function(header,msg){
				return $modal.open({
					templateUrl : '/dialogs/notify.html',
					controller : 'notifyDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); }
					}
				}); // end modal.open
			}, // end notify

			confirm : function(header,msg,primaryButtonText,secondaryButtonText){
				return $modal.open({
					templateUrl : '/dialogs/confirm.html',
					controller : 'confirmDialogCtrl',
					resolve : {
						header : function() { return angular.copy(header); },
						msg : function() { return angular.copy(msg); },
						primaryButtonText : function() { return angular.copy(primaryButtonText); },
						secondaryButtonText : function() { return angular.copy(secondaryButtonText); }
					}
				}); // end modal.open
			}, // end confirm

			create : function(url,ctrlr,data,opts){
				var k = (angular.isDefined(opts.keyboard)) ? opts.keyboard : true; // values: true,false
				var b = (angular.isDefined(opts.backdrop)) ? opts.backdrop : true; // values: 'static',true,false
				var w = (angular.isDefined(opts.windowClass)) ? opts.windowClass : 'dialogs-default'; // additional CSS class(es) to be added to a modal window
				return $modal.open({
					templateUrl : url,
					controller : ctrlr,
					keyboard : k,
					backdrop : b,
					windowClass: w,
					resolve : {
						data : function() { return angular.copy(data); }
					}
				}); // end modal.open
			} // end confirm
		};
	}]); // end $dialogs / dialogs.services

//== Module ==================================================================//

angular.module('dialogs',['dialogs.services','ngSanitize']) // requires angular-sanitize.min.js (ngSanitize) //code.angularjs.org/1.2.1/angular-sanitize.min.js

	// Add default templates via $templateCache
	.run(['$templateCache',function($templateCache){
		$templateCache.put('/dialogs/error.html','
<button type="button" class="close" ng-click="close()">×</button>

<button type="button" class="btn btn-default" ng-click="close()">Close</button>
');
		$templateCache.put('/dialogs/wait.html','

 Please Wait

{{progress}}% Complete

');
		$templateCache.put('/dialogs/notify.html','
<button type="button" class="close" ng-click="close()" class="pull-right">×</button>
 {{header}}

<button type="button" class="btn btn-primary" ng-click="close()">OK</button>
');
		$templateCache.put('/dialogs/confirm.html','
<button type="button" class="close" ng-click="no()">×</button>
 {{header}}

<button type="button" class="btn btn-default btn-primary" ng-click="yes()">{{primaryButtonText}}</button><button type="button" class="btn btn-default" ng-click="no()">{{secondaryButtonText}}</button>
');
	}]); // end run / dialogs

<|endoftext|>


<commit_before>// @flow
import PDFDocument from 'pdfkit';
import qr from 'qr-image';
import { defineMessages } from 'react-intl';
import fs from 'fs';
import paperWalletFontPath from '../assets/pdf/paper-wallet-certificate-font.ttf';
import paperWalletPage1Path from '../assets/pdf/paper-wallet-certificate-page-1.png';
import paperWalletPage1PathTestnet from '../assets/pdf/paper-wallet-certificate-page-1-testnet.png';
import paperWalletPage2Path from '../assets/pdf/paper-wallet-certificate-page-2.png';
import paperWalletPage2PathTestnet from '../assets/pdf/paper-wallet-certificate-page-2-testnet.png';
import paperWalletCertificateBgPath from '../assets/pdf/paper-wallet-certificate-background.png';
import environment from '../../../common/environment';
import { loadAssetChannel } from '../ipc/loadAsset';

const messages = defineMessages({
  walletAddressLabel: {
    id: 'paper.wallet.pdf.walletAddress.label',
    defaultMessage: '!!!Wallet address',
    description: 'Paper wallet pdf "Wallet address" label.'
  },
  recoveryPhraseLabel: {
    id: 'paper.wallet.pdf.recoveryPhrase.label',
    defaultMessage: '!!!Paper wallet recovery phrase',
    description: 'Paper wallet pdf "Paper wallet recovery phrase" label.'
  },
  passwordLabel: {
    id: 'paper.wallet.pdf.password.label',
    defaultMessage: '!!!Password',
    description: 'Paper wallet pdf "Password" label.'
  },
  infoTitle: {
    id: 'paper.wallet.pdf.info.title',
    defaultMessage: '!!!Daedalus paper wallet certificate',
    description: 'PDF title',
  },
  infoAuthor: {
    id: 'paper.wallet.pdf.info.author',
    defaultMessage: '!!!Daedalus wallet',
    description: 'PDF author',
  },
});

type DownloadPaperWalletCertificateParams = {
  address: string,
  filePath: string,
  mnemonics: Array<string>,
  intl: Object,
};

export const downloadPaperWalletCertificate = async (
  { address, mnemonics, intl, filePath }: DownloadPaperWalletCertificateParams
) => {
  const { getBuildLabel, isMainnet } = environment;
  const qrCodeImage = qr.imageSync(address, { type: 'png', size: 10, ec_level: 'L', margin: 0 });
  const textColor = '#3b5c9b';

  const printMnemonic = (index) => `${index + 1}. ${mnemonics[index]}`;

  const loadAssetFromPath = async (path) => await loadAssetChannel.send({ fileName: path });

  const loadFontBufferFromPath = async (path) => {
    const asset = await loadAssetFromPath(path);
    return Buffer.from(asset, 'base64');
  };

  const loadImageUriFromPath = async (path) => {
    const asset = await loadAssetFromPath(path);
    return `data:image/png;base64,${asset}`;
  };

  const width = 595.28;
  const height = 841.98;
  const doc = new PDFDocument({
    size: [width, height],
    margins: {
      bottom: 0,
      left: 0,
      right: 0,
      top: 0,
    },
    info: {
      Title: intl.formatMessage(messages.infoTitle),
      Author: intl.formatMessage(messages.infoAuthor),
    }
  });

  /* eslint-disable max-len */
  // font family
  const fontBuffer = await loadFontBufferFromPath(paperWalletFontPath);
  doc.font(fontBuffer);

  // background images
  const backgroundUri = await loadImageUriFromPath(paperWalletCertificateBgPath);
  doc.image(backgroundUri, 0, 0, { fit: [width, height] });

  // first page
  const page1Uri = await loadImageUriFromPath(
    isMainnet() ? paperWalletPage1Path : paperWalletPage1PathTestnet
  );
  doc.image(page1Uri, 0, 0, { fit: [width, height] });
  doc.rotate(180, { origin: [width / 2, height / 2] });
  doc.fillColor(textColor);
  doc.fontSize(10).text(intl.formatMessage(messages.walletAddressLabel), 0, 160, { width: 595, align: 'center' });
  doc.image(qrCodeImage, (width / 2) - 80 / 2, 180, { fit: [80, 80] });
  doc.fontSize(8).text(address, (width - 250) / 2, 274, { width: 250, align: 'center', lineGap: 2 });

  // revert document rotation
  doc.rotate(-180, { origin: [width / 2, height / 2] });

  // second page
  doc.addPage();
  const page2Uri = await loadImageUriFromPath(
    isMainnet() ? paperWalletPage2Path : paperWalletPage2PathTestnet
  );
  doc.image(page2Uri, 0, 0, { fit: [width, height] });
  doc.rotate(180, { origin: [width / 2, height / 2] });
  doc.fillColor(textColor);
  doc.fontSize(10).text(intl.formatMessage(messages.recoveryPhraseLabel), 0, 535, { width: 595, align: 'center' });

  // mnemonics
  doc.fontSize(7);
  doc.text(printMnemonic(0), 168, 560);
  doc.text(printMnemonic(1), 212, 560);
  doc.text(printMnemonic(2), 256, 560);
  doc.text(printMnemonic(3), 300, 560);
  doc.text(printMnemonic(4), 344, 560);
  doc.text(printMnemonic(5), 388, 560);

  doc.text(printMnemonic(6), 168, 581);
  doc.text(printMnemonic(7), 212, 581);
  doc.text(printMnemonic(8), 256, 581);
  doc.text(printMnemonic(9), 300, 581);
  doc.text(printMnemonic(10), 344, 581);
  doc.text(printMnemonic(11), 388, 581);

  doc.text(printMnemonic(12), 168, 602);
  doc.text(printMnemonic(13), 212, 602);
  doc.text(printMnemonic(14), 256, 602);
  doc.text(printMnemonic(15), 300, 602);
  doc.text(printMnemonic(16), 344, 602);
  doc.text(printMnemonic(17), 388, 602);

  doc.fontSize(7).text(getBuildLabel(), (width - 270) / 2, 705, { width: 270, align: 'left' });
  doc.rotate(-180, { origin: [width / 2, height / 2] });
  /* eslint-enable max-len */

  doc.pipe(fs.createWriteStream(filePath));
  doc.end();
};
<commit_msg>[DDW-262] Changes isMainnet to constant from function<commit_after>// @flow
import PDFDocument from 'pdfkit';
import qr from 'qr-image';
import { defineMessages } from 'react-intl';
import fs from 'fs';
import paperWalletFontPath from '../assets/pdf/paper-wallet-certificate-font.ttf';
import paperWalletPage1Path from '../assets/pdf/paper-wallet-certificate-page-1.png';
import paperWalletPage1PathTestnet from '../assets/pdf/paper-wallet-certificate-page-1-testnet.png';
import paperWalletPage2Path from '../assets/pdf/paper-wallet-certificate-page-2.png';
import paperWalletPage2PathTestnet from '../assets/pdf/paper-wallet-certificate-page-2-testnet.png';
import paperWalletCertificateBgPath from '../assets/pdf/paper-wallet-certificate-background.png';
import { loadAssetChannel } from '../ipc/loadAsset';

const messages = defineMessages({
  walletAddressLabel: {
    id: 'paper.wallet.pdf.walletAddress.label',
    defaultMessage: '!!!Wallet address',
    description: 'Paper wallet pdf "Wallet address" label.'
  },
  recoveryPhraseLabel: {
    id: 'paper.wallet.pdf.recoveryPhrase.label',
    defaultMessage: '!!!Paper wallet recovery phrase',
    description: 'Paper wallet pdf "Paper wallet recovery phrase" label.'
  },
  passwordLabel: {
    id: 'paper.wallet.pdf.password.label',
    defaultMessage: '!!!Password',
    description: 'Paper wallet pdf "Password" label.'
  },
  infoTitle: {
    id: 'paper.wallet.pdf.info.title',
    defaultMessage: '!!!Daedalus paper wallet certificate',
    description: 'PDF title',
  },
  infoAuthor: {
    id: 'paper.wallet.pdf.info.author',
    defaultMessage: '!!!Daedalus wallet',
    description: 'PDF author',
  },
});

type DownloadPaperWalletCertificateParams = {
  address: string,
  filePath: string,
  mnemonics: Array<string>,
  intl: Object,
  isMainnet: boolean,
  buildLabel: string
};

export const downloadPaperWalletCertificate = async (
  { address, mnemonics, intl, filePath, isMainnet, buildLabel }:
  DownloadPaperWalletCertificateParams
) => {
  const qrCodeImage = qr.imageSync(address, { type: 'png', size: 10, ec_level: 'L', margin: 0 });
  const textColor = '#3b5c9b';

  const printMnemonic = (index) => `${index + 1}. ${mnemonics[index]}`;

  const loadAssetFromPath = async (path) => await loadAssetChannel.send({ fileName: path });

  const loadFontBufferFromPath = async (path) => {
    const asset = await loadAssetFromPath(path);
    return Buffer.from(asset, 'base64');
  };

  const loadImageUriFromPath = async (path) => {
    const asset = await loadAssetFromPath(path);
    return `data:image/png;base64,${asset}`;
  };

  const width = 595.28;
  const height = 841.98;
  const doc = new PDFDocument({
    size: [width, height],
    margins: {
      bottom: 0,
      left: 0,
      right: 0,
      top: 0,
    },
    info: {
      Title: intl.formatMessage(messages.infoTitle),
      Author: intl.formatMessage(messages.infoAuthor),
    }
  });

  /* eslint-disable max-len */
  // font family
  const fontBuffer = await loadFontBufferFromPath(paperWalletFontPath);
  doc.font(fontBuffer);

  // background images
  const backgroundUri = await loadImageUriFromPath(paperWalletCertificateBgPath);
  doc.image(backgroundUri, 0, 0, { fit: [width, height] });

  // first page
  const page1Uri = await loadImageUriFromPath(
    isMainnet ? paperWalletPage1Path : paperWalletPage1PathTestnet
  );
  doc.image(page1Uri, 0, 0, { fit: [width, height] });
  doc.rotate(180, { origin: [width / 2, height / 2] });
  doc.fillColor(textColor);
  doc.fontSize(10).text(intl.formatMessage(messages.walletAddressLabel), 0, 160, { width: 595, align: 'center' });
  doc.image(qrCodeImage, (width / 2) - 80 / 2, 180, { fit: [80, 80] });
  doc.fontSize(8).text(address, (width - 250) / 2, 274, { width: 250, align: 'center', lineGap: 2 });

  // revert document rotation
  doc.rotate(-180, { origin: [width / 2, height / 2] });

  // second page
  doc.addPage();
  const page2Uri = await loadImageUriFromPath(
    isMainnet ? paperWalletPage2Path : paperWalletPage2PathTestnet
  );
  doc.image(page2Uri, 0, 0, { fit: [width, height] });
  doc.rotate(180, { origin: [width / 2, height / 2] });
  doc.fillColor(textColor);
  doc.fontSize(10).text(intl.formatMessage(messages.recoveryPhraseLabel), 0, 535, { width: 595, align: 'center' });

  // mnemonics
  doc.fontSize(7);
  doc.text(printMnemonic(0), 168, 560);
  doc.text(printMnemonic(1), 212, 560);
  doc.text(printMnemonic(2), 256, 560);
  doc.text(printMnemonic(3), 300, 560);
  doc.text(printMnemonic(4), 344, 560);
  doc.text(printMnemonic(5), 388, 560);

  doc.text(printMnemonic(6), 168, 581);
  doc.text(printMnemonic(7), 212, 581);
  doc.text(printMnemonic(8), 256, 581);
  doc.text(printMnemonic(9), 300, 581);
  doc.text(printMnemonic(10), 344, 581);
  doc.text(printMnemonic(11), 388, 581);

  doc.text(printMnemonic(12), 168, 602);
  doc.text(printMnemonic(13), 212, 602);
  doc.text(printMnemonic(14), 256, 602);
  doc.text(printMnemonic(15), 300, 602);
  doc.text(printMnemonic(16), 344, 602);
  doc.text(printMnemonic(17), 388, 602);

  doc.fontSize(7).text(buildLabel, (width - 270) / 2, 705, { width: 270, align: 'left' });
  doc.rotate(-180, { origin: [width / 2, height / 2] });
  /* eslint-enable max-len */

  doc.pipe(fs.createWriteStream(filePath));
  doc.end();
};
<|endoftext|>