<commit_before>/**
 * Created by gbecan on 17/12/14.
 */

/**
 * Sort two elements by their names (accessed with x.name)
 * @param a
 * @param b
 * @returns {number}
 */
function sortByName(a, b) {
    if (a.name < b.name) {
        return -1;
    } else if (a.name > b.name) {
        return 1;
    } else {
        return 0;
    }
}

pcmApp.controller("PCMEditorController", function($scope, $http) {

    // Load PCM
    var pcmMM = Kotlin.modules['pcm'].pcm;
    var factory = new pcmMM.factory.DefaultPcmFactory();
    var loader = factory.createJSONLoader();
    var serializer = factory.createJSONSerializer();

    // Init
    var features = [];
    var featureHeaders = [];
    var productHeaders = [];
    var products = [];

    if (typeof id === 'undefined') {
        // Create example PCM
        $scope.pcm = factory.createPCM();

        var exampleFeature = factory.createFeature();
        exampleFeature.name = "Feature";
        $scope.pcm.addFeatures(exampleFeature);

        var exampleFeature1 = factory.createFeature();
        exampleFeature1.name = "Feature1";
        $scope.pcm.addFeatures(exampleFeature1);

        var exampleProduct = factory.createProduct();
        exampleProduct.name = "Product";
        $scope.pcm.addProducts(exampleProduct);

        var exampleCell = factory.createCell();
        exampleCell.feature = exampleFeature;
        exampleCell.content = "Yes";
        exampleProduct.addValues(exampleCell);

        var exampleCell1 = factory.createCell();
        exampleCell1.feature = exampleFeature1;
        exampleCell1.content = "No";
        exampleProduct.addValues(exampleCell1);

        initializeHOT();

    } else {

        $http.get("/api/get/" + id).success(function (data) {
            $scope.pcm = loader.loadModelFromString(JSON.stringify(data)).get(0);
            initializeHOT();
        });

    }

    function initializeHOT() {
        // Transform features to handonstable data structures
        var kFeatures = getConcreteFeatures($scope.pcm).sort(sortByName); // $scope.pcm.features.array
        for (var i = 0; i < kFeatures.length; i++) {
            features.push({
                data: property(kFeatures[i].generated_KMF_ID),
		ID : kFeatures[i].generated_KMF_ID
            });
            featureHeaders.push(kFeatures[i].name);
        }

        // Transform products to handonstable data structures
        var kProducts = $scope.pcm.products.array.sort(sortByName);
        for (var i = 0; i < kProducts.length; i++) {
            var product = kProducts[i];

            productHeaders.push(product.name);
            products.push(model(product));

        }

        var container = document.getElementById('hot');
        var hot = new Handsontable(container,
            {
                data: products,
                //dataSchema: schema,
                rowHeaders: productHeaders,
                colHeaders: featureHeaders,
                columns: features,
                //contextMenu: true,
                contextMenu: contextMenu(),
                //stretchH: 'all', // Scroll bars ?!
                manualColumnMove: true,
                manualRowMove: true
            });

	  function contextMenu () {
		  return {
		  /*add_col : {
			  name : 'add a column (DON\'T SAVE !!!)',
			  callback: function (key, selection) {
			      var header = prompt("Please enter your column name", "");
			      if (header != null) {
				  featureHeaders.push(header);
				  var feature = factory.createFeature();
				  features.push({
				      data: feature,
				      ID : feature.generated_KMF_ID
				  });
				  for (var i = 0 ; i < $scope.pcm.products.array.length ; i++) {
				      var cell = factory.createCell();
				      cell.content = "";
				      cell.feature = feature;
				      $scope.pcm.products.array[i].addValues(cell);
				  }
				  hot.render();
			      }
			  },
			  disabled: function () {
			      return false;
			  }
		  },*/
		  remove_column : {
			  name : 'remove colomn(s)',
			  callback: function (key, selection) {
			      var start = selection.start.col;
			      var end = selection.end.col;
			      for (var i = 0 ; i < $scope.pcm.products.array.length ; i++) {
				  var product = $scope.pcm.products.array[i];
				  var array = product.values.array;
				  for (var j = 0 ; j < array.length ; j++) {
				      var cell = array[j];
				      for (var k = start ; k <= end ; k++) {
					  if (cell.feature.generated_KMF_ID == features[k].ID) {
					      alert(array.length);
					      product.removeValues(cell);
					      alert(array.length);
					      break;
					  }
				      }
				  }
			      }
			      features.splice(start, end-start+1);
			      featureHeaders.splice(start, end-start+1);

			      hot.render();
			  },
			  disabled: function () {
			      return false;
			  }
		  },
		  set_column_name : {
			  name : 'set column name',
			  callback: function (key, selection) {
				  var header = prompt("Please enter your column name", "");
				  if (header != null) {
				      featureHeaders.splice(selection.start.col, 1, header);
				      features[selection.start.col].data.name = header;
				      //$scope.pcm.findFeaturesById(features[selection.start.col].ID).name = header;

				      var feature;
				      for (var i = 0 ; i < $scope.pcm.features.array.length ; i++) {
					  feature = $scope.pcm.features.array[i];
					  if (feature.generated_KMF_ID == features[selection.start.col].ID) break;
				      }
				      feature.name = header;

				      hot.render();
				  }
			  },
			  disabled: function () {
			      // if multiple columns selected : disable
			      return hot.getSelected()[1] != hot.getSelected()[3];
			  }
		  },
		  "hsep": "---------",
		  add_row : {
			  name : 'add a row',
			  callback: function (key, selection) {
			      var header = prompt("Please enter your row name", "");
			      if (header != null) {
				  productHeaders.push(header);
				  var product = factory.createProduct();
				  product.name = header;
				  for (var i = 0; i < $scope.pcm.features.array.length; i++) {
				      var cell = factory.createCell();
				      cell.feature = $scope.pcm.features.array[i];
				      cell.content = "";
				      product.addValues(cell);
				  }
				  $scope.pcm.addProducts(product);
				  products.push(model(product));

				  hot.render();
			      }
			  },
			  disabled: function () {
			      return false;
			  }
		  },
		  remove_row : {
			  name : 'remove row(s)',
			  callback: function (key, selection) {
			      var start = selection.start.row;
			      var end = selection.end.row;

			      var array = $scope.pcm.products.array;
			      for (var i = 0 ; i < array.length ; i++) {
				  var product = array[i];
				  for (var j = start ; j <= end ; j++) {
				      if (product.generated_KMF_ID == products[j]) {
					  $scope.pcm.removeProducts(product);
					  break;
				      }
				  }
			      }

			      products.splice(start, end-start+1);
			      productHeaders.splice(start, end-start+1);

			      hot.render();
			  },
			  disabled: function () {
			      return false;
			  }
		  },
		  /*set_row_name : {
			  name : 'set row name',
			  callback: function (key, selection) {
				  var header = prompt("Please enter your row name", "");
				  if (header != null) {
				      productHeaders.splice(selection.start.row, 1, header);
				      //products[selection.start.row].data.name = header;
				      //$scope.pcm.findproductsById(products[selection.start.col].ID).name = header;

				      var product;
				      for (var i = 0 ; i < $scope.pcm.products.array.length ; i++) {
					  product = $scope.pcm.products.array[i];
					  if (product.generated_KMF_ID == products[selection.start.row].ID) break;
				      }
				      product.name = header;

				      hot.render();
				  }
			  },
			  disabled: function () {
			      // if multiple columns selected : disable
			      return hot.getSelected()[0] != hot.getSelected()[2];
			  }
		  },*/
		  };
	  }
    }

    function getConcreteFeatures(pcm) {

        var aFeatures = pcm.features.array;

        var features = [];
        for (var i = 0; i < aFeatures.length; i++) {
            var aFeature = aFeatures[i];
            features = features.concat(getConcreteFeaturesRec(aFeature))
        }

        return features;
    }

    function getConcreteFeaturesRec(aFeature) {

        var features = [];

        if (typeof aFeature.subFeatures !== 'undefined') {
            var subFeatures = aFeature.subFeatures.array;
            for (var i = 0; i < subFeatures.length; i++) {
                var subFeature = subFeatures[i];
                features = features.concat(getConcreteFeaturesRec(subFeature));
            }
        } else {
            features.push(aFeature);
        }

        return features;
    }

    /**
     * Synchronization function between handsontable and a PCM model of a product
     * @param product : KMF model of a product
     * @returns synchronization object
     */
    function model(product) {
        var idKMF = product.generated_KMF_ID;
        return idKMF;
    }

    function schema() {
        var newProduct = factory.createProduct();
        $scope.pcm.addProducts(newProduct);

        for (var i = 0; i < $scope.pcm.features.array.length; i++) {
            var cell = factory.createCell();
            cell.feature = $scope.pcm.features.array[i];
            cell.content = "";
            newProduct.addValues(cell);
        }

        return model(newProduct);
    }

    /**
     * Bind handsontable cells to PCM cells
     * @param attr
     * @returns synchronization function
     */
    function property(attr) {
        return function (row, value) {
            var product = $scope.pcm.findProductsByID(row);
            //var cell = product.select("values[feature/id == " + attr + "]").get(0); // FIXME : does not work ! We need to find the cell that correponds to the feature id
            var cells = product.values.array
            for (var i = 0; i < cells.length; i++) {
                var cell = cells[i];
                if (cell.feature.generated_KMF_ID === attr) {
                    break;
                }
            }

            if (typeof value === 'undefined') {
                return cell.content;
            } else {
                cell.content = value;
                return row;
            }
        }
    }

    /**
     * Save PCM on the server
     */
    $scope.save = function() {
        var jsonModel = serializer.serialize($scope.pcm);

        if (typeof id === 'undefined') {
            $http.post("/api/create", JSON.parse(jsonModel)).success(function(data) {
                id = data;
                console.log("model created with id=" + id);
            });
        } else {
            $http.post("/api/save/" + id, JSON.parse(jsonModel)).success(function(data) {
                console.log("model saved");
            });
        }
    };

    $scope.remove = function() {
        if (typeof id !== 'undefined') {
            $http.get("/api/remove/" + id).success(function(data) {
                window.location.href = "/";
                console.log("model removed");
            });
        }
    };

});

<commit_msg>can rename rows<commit_after>/**
 * Created by gbecan on 17/12/14.
 */

/**
 * Sort two elements by their names (accessed with x.name)
 * @param a
 * @param b
 * @returns {number}
 */
function sortByName(a, b) {
    if (a.name < b.name) {
        return -1;
    } else if (a.name > b.name) {
        return 1;
    } else {
        return 0;
    }
}

pcmApp.controller("PCMEditorController", function($scope, $http) {

    // Load PCM
    var pcmMM = Kotlin.modules['pcm'].pcm;
    var factory = new pcmMM.factory.DefaultPcmFactory();
    var loader = factory.createJSONLoader();
    var serializer = factory.createJSONSerializer();

    // Init
    var features = [];
    var featureHeaders = [];
    var productHeaders = [];
    var products = [];

    if (typeof id === 'undefined') {
        // Create example PCM
        $scope.pcm = factory.createPCM();

        var exampleFeature = factory.createFeature();
        exampleFeature.name = "Feature";
        $scope.pcm.addFeatures(exampleFeature);

        var exampleFeature1 = factory.createFeature();
        exampleFeature1.name = "Feature1";
        $scope.pcm.addFeatures(exampleFeature1);

        var exampleProduct = factory.createProduct();
        exampleProduct.name = "Product";
        $scope.pcm.addProducts(exampleProduct);

        var exampleCell = factory.createCell();
        exampleCell.feature = exampleFeature;
        exampleCell.content = "Yes";
        exampleProduct.addValues(exampleCell);

        var exampleCell1 = factory.createCell();
        exampleCell1.feature = exampleFeature1;
        exampleCell1.content = "No";
        exampleProduct.addValues(exampleCell1);

        initializeHOT();

    } else {

        $http.get("/api/get/" + id).success(function (data) {
            $scope.pcm = loader.loadModelFromString(JSON.stringify(data)).get(0);
            initializeHOT();
        });

    }

    function initializeHOT() {
        // Transform features to handonstable data structures
        var kFeatures = getConcreteFeatures($scope.pcm).sort(sortByName); // $scope.pcm.features.array
        for (var i = 0; i < kFeatures.length; i++) {
            features.push({
                data: property(kFeatures[i].generated_KMF_ID),
		ID : kFeatures[i].generated_KMF_ID
            });
            featureHeaders.push(kFeatures[i].name);
        }

        // Transform products to handonstable data structures
        var kProducts = $scope.pcm.products.array.sort(sortByName);
        for (var i = 0; i < kProducts.length; i++) {
            var product = kProducts[i];

            productHeaders.push(product.name);
            products.push(model(product));

        }

        var container = document.getElementById('hot');
        var hot = new Handsontable(container,
            {
                data: products,
                //dataSchema: schema,
                rowHeaders: productHeaders,
                colHeaders: featureHeaders,
                columns: features,
                //contextMenu: true,
                contextMenu: contextMenu(),
                //stretchH: 'all', // Scroll bars ?!
                manualColumnMove: true,
                manualRowMove: true
            });

	  function contextMenu () {
		  return {
		  /*add_col : {
			  name : 'add a column (DON\'T SAVE !!!)',
			  callback: function (key, selection) {
			      var header = prompt("Please enter your column name", "");
			      if (header != null) {
				  featureHeaders.push(header);
				  var feature = factory.createFeature();
				  features.push({
				      data: feature,
				      ID : feature.generated_KMF_ID
				  });
				  for (var i = 0 ; i < $scope.pcm.products.array.length ; i++) {
				      var cell = factory.createCell();
				      cell.content = "";
				      cell.feature = feature;
				      $scope.pcm.products.array[i].addValues(cell);
				  }
				  hot.render();
			      }
			  },
			  disabled: function () {
			      return false;
			  }
		  },*/
		  remove_column : {
			  name : 'remove colomn(s)',
			  callback: function (key, selection) {
			      var start = selection.start.col;
			      var end = selection.end.col;
			      for (var i = 0 ; i < $scope.pcm.products.array.length ; i++) {
				  var product = $scope.pcm.products.array[i];
				  var array = product.values.array;
				  for (var j = 0 ; j < array.length ; j++) {
				      var cell = array[j];
				      for (var k = start ; k <= end ; k++) {
					  if (cell.feature.generated_KMF_ID == features[k].ID) {
					      alert(array.length);
					      product.removeValues(cell);
					      alert(array.length);
					      break;
					  }
				      }
				  }
			      }
			      features.splice(start, end-start+1);
			      featureHeaders.splice(start, end-start+1);

			      hot.render();
			  },
			  disabled: function () {
			      return false;
			  }
		  },
		  set_column_name : {
			  name : 'set column name',
			  callback: function (key, selection) {
				  var header = prompt("Please enter your column name", "");
				  if (header != null) {
				      featureHeaders.splice(selection.start.col, 1, header);
				      features[selection.start.col].data.name = header;
				      //$scope.pcm.findFeaturesById(features[selection.start.col].ID).name = header;

				      var feature;
				      for (var i = 0 ; i < $scope.pcm.features.array.length ; i++) {
					  feature = $scope.pcm.features.array[i];
					  if (feature.generated_KMF_ID == features[selection.start.col].ID) break;
				      }
				      feature.name = header;

				      hot.render();
				  }
			  },
			  disabled: function () {
			      // if multiple columns selected : disable
			      return hot.getSelected()[1] != hot.getSelected()[3];
			  }
		  },
		  "hsep": "---------",
		  add_row : {
			  name : 'add a row',
			  callback: function (key, selection) {
			      var header = prompt("Please enter your row name", "");
			      if (header != null) {
				  productHeaders.push(header);
				  var product = factory.createProduct();
				  product.name = header;
				  for (var i = 0; i < $scope.pcm.features.array.length; i++) {
				      var cell = factory.createCell();
				      cell.feature = $scope.pcm.features.array[i];
				      cell.content = "";
				      product.addValues(cell);
				  }
				  $scope.pcm.addProducts(product);
				  products.push(model(product));

				  hot.render();
			      }
			  },
			  disabled: function () {
			      return false;
			  }
		  },
		  remove_row : {
			  name : 'remove row(s)',
			  callback: function (key, selection) {
			      var start = selection.start.row;
			      var end = selection.end.row;

			      var array = $scope.pcm.products.array;
			      for (var i = 0 ; i < array.length ; i++) {
				  var product = array[i];
				  for (var j = start ; j <= end ; j++) {
				      if (product.generated_KMF_ID == products[j]) {
					  $scope.pcm.removeProducts(product);
					  break;
				      }
				  }
			      }

			      products.splice(start, end-start+1);
			      productHeaders.splice(start, end-start+1);

			      hot.render();
			  },
			  disabled: function () {
			      return false;
			  }
		  },
		  set_row_name : {
			  name : 'set row name',
			  callback: function (key, selection) {
				  var header = prompt("Please enter your row name", "");
				  if (header != null) {
				      productHeaders.splice(selection.start.row, 1, header);
				      $scope.pcm.findProductsByID(products[selection.start.row]).name = header;

				      hot.render();
				  }
			  },
			  disabled: function () {
			      // if multiple columns selected : disable
			      return hot.getSelected()[0] != hot.getSelected()[2];
			  }
		  },
		  };
	  }
    }

    function getConcreteFeatures(pcm) {

        var aFeatures = pcm.features.array;

        var features = [];
        for (var i = 0; i < aFeatures.length; i++) {
            var aFeature = aFeatures[i];
            features = features.concat(getConcreteFeaturesRec(aFeature))
        }

        return features;
    }

    function getConcreteFeaturesRec(aFeature) {

        var features = [];

        if (typeof aFeature.subFeatures !== 'undefined') {
            var subFeatures = aFeature.subFeatures.array;
            for (var i = 0; i < subFeatures.length; i++) {
                var subFeature = subFeatures[i];
                features = features.concat(getConcreteFeaturesRec(subFeature));
            }
        } else {
            features.push(aFeature);
        }

        return features;
    }

    /**
     * Synchronization function between handsontable and a PCM model of a product
     * @param product : KMF model of a product
     * @returns synchronization object
     */
    function model(product) {
        var idKMF = product.generated_KMF_ID;
        return idKMF;
    }

    function schema() {
        var newProduct = factory.createProduct();
        $scope.pcm.addProducts(newProduct);

        for (var i = 0; i < $scope.pcm.features.array.length; i++) {
            var cell = factory.createCell();
            cell.feature = $scope.pcm.features.array[i];
            cell.content = "";
            newProduct.addValues(cell);
        }

        return model(newProduct);
    }

    /**
     * Bind handsontable cells to PCM cells
     * @param attr
     * @returns synchronization function
     */
    function property(attr) {
        return function (row, value) {
            var product = $scope.pcm.findProductsByID(row);
            //var cell = product.select("values[feature/id == " + attr + "]").get(0); // FIXME : does not work ! We need to find the cell that correponds to the feature id
            var cells = product.values.array
            for (var i = 0; i < cells.length; i++) {
                var cell = cells[i];
                if (cell.feature.generated_KMF_ID === attr) {
                    break;
                }
            }

            if (typeof value === 'undefined') {
                return cell.content;
            } else {
                cell.content = value;
                return row;
            }
        }
    }

    /**
     * Save PCM on the server
     */
    $scope.save = function() {
        var jsonModel = serializer.serialize($scope.pcm);

        if (typeof id === 'undefined') {
            $http.post("/api/create", JSON.parse(jsonModel)).success(function(data) {
                id = data;
                console.log("model created with id=" + id);
            });
        } else {
            $http.post("/api/save/" + id, JSON.parse(jsonModel)).success(function(data) {
                console.log("model saved");
            });
        }
    };

    $scope.remove = function() {
        if (typeof id !== 'undefined') {
            $http.get("/api/remove/" + id).success(function(data) {
                window.location.href = "/";
                console.log("model removed");
            });
        }
    };

});

<|endoftext|>


<commit_before>'use strict';

angular.module('<%=angularAppName%>')<% if (authenticationType == 'oauth2' || authenticationType == 'xauth') { %>
    .factory('authInterceptor', function ($rootScope, $q, $location, localStorageService) {
        return {
            // Add authorization token to headers
            request: function (config) {
                config.headers = config.headers || {};
                var token = localStorageService.get('token');
                <% if (authenticationType == 'oauth2') { %>
                if (token && token.expires_at && token.expires_at > new Date().getTime()) {
                    config.headers.Authorization = 'Bearer ' + token.access_token;
                }
                <% } %><% if (authenticationType == 'xauth') { %>
                if (token && token.expires && token.expires > new Date().getTime()) {
                  config.headers['x-auth-token'] = token.token;
                }
                <% } %>
                return config;
            }
        };
    })<% } %><% if (authenticationType == 'oauth2' || authenticationType == 'xauth') { %>
    .factory('authExpiredInterceptor', function ($rootScope, $q, $injector, localStorageService) {
        return {
            responseError: function (response) {
                // token has expired
                if (response.status === 401 && (response.data.error == 'invalid_token' || response.data.error == 'Unauthorized')) {
                    localStorageService.remove('token');
                    var Principal = $injector.get('Principal');
                    if (Principal.isAuthenticated()) {
                        var Auth = $injector.get('Auth');
                        Auth.authorize(true);
                    }
                }
                return $q.reject(response);
            }
        };
    })<% } %><% if (authenticationType == 'session') { %>
    .factory('authExpiredInterceptor', function ($rootScope, $q, $injector, localStorageService) {
        return {
            responseError: function(response) {
                // If we have an unauthorized request we redirect to the login page
                // Don't do this check on the account API to avoid infinite loop
                if (response.status == 401 && response.data.path !== undefined && response.data.path.indexOf("/api/account") == -1){
                    var Auth = $injector.get('Auth');
                    var $state = $injector.get('$state');
                    var to = $rootScope.toState;
                    var params = $rootScope.toStateParams;
                    Auth.logout();
                    $rootScope.previousStateName = to;
                    $rootScope.previousStateNameParams = params;
                    $state.go('login');
                } else if (response.status == 403 && response.config.method != 'GET' && getCSRF() == ''){
            		// If the CSRF token expired, then try to get a new CSRF token and retry the old request
                	return $injector.get('Account').get().$promise
                    .then(function() { return afterCSRFRenewed(response); })
                    .catch(function() { return afterCSRFRenewed(response); });
                }
                return $q.reject(response);
            }
        };

        function afterCSRFRenewed(oldResponse) {
        	if (getCSRF() !== '') {
        		// retry the old request after the new CSRF-TOKEN is obtained
        		var $http = $injector.get('$http');
        		return $http(oldResponse.config);
        	} else {
        		// unlikely get here but reject with the old response any way and avoid infinite loop
        		return $q.reject(oldResponse);
        	}
        }

    	function getCSRF() {
    		var name = 'CSRF-TOKEN=';
    		var ca = document.cookie.split(';');
    		for(var i=0; i<ca.length; i++) {
    			var c = ca[i];
    			while (c.charAt(0)==' ') c = c.substring(1);
    			if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    		}
    		return '';
    	}
    })<% } %>;
<commit_msg>call afterCSRFRenewed in promise's finally instead of then and catch respectively<commit_after>'use strict';

angular.module('<%=angularAppName%>')<% if (authenticationType == 'oauth2' || authenticationType == 'xauth') { %>
    .factory('authInterceptor', function ($rootScope, $q, $location, localStorageService) {
        return {
            // Add authorization token to headers
            request: function (config) {
                config.headers = config.headers || {};
                var token = localStorageService.get('token');
                <% if (authenticationType == 'oauth2') { %>
                if (token && token.expires_at && token.expires_at > new Date().getTime()) {
                    config.headers.Authorization = 'Bearer ' + token.access_token;
                }
                <% } %><% if (authenticationType == 'xauth') { %>
                if (token && token.expires && token.expires > new Date().getTime()) {
                  config.headers['x-auth-token'] = token.token;
                }
                <% } %>
                return config;
            }
        };
    })<% } %><% if (authenticationType == 'oauth2' || authenticationType == 'xauth') { %>
    .factory('authExpiredInterceptor', function ($rootScope, $q, $injector, localStorageService) {
        return {
            responseError: function (response) {
                // token has expired
                if (response.status === 401 && (response.data.error == 'invalid_token' || response.data.error == 'Unauthorized')) {
                    localStorageService.remove('token');
                    var Principal = $injector.get('Principal');
                    if (Principal.isAuthenticated()) {
                        var Auth = $injector.get('Auth');
                        Auth.authorize(true);
                    }
                }
                return $q.reject(response);
            }
        };
    })<% } %><% if (authenticationType == 'session') { %>
    .factory('authExpiredInterceptor', function ($rootScope, $q, $injector, localStorageService) {
        return {
            responseError: function(response) {
                // If we have an unauthorized request we redirect to the login page
                // Don't do this check on the account API to avoid infinite loop
                if (response.status == 401 && response.data.path !== undefined && response.data.path.indexOf("/api/account") == -1){
                    var Auth = $injector.get('Auth');
                    var $state = $injector.get('$state');
                    var to = $rootScope.toState;
                    var params = $rootScope.toStateParams;
                    Auth.logout();
                    $rootScope.previousStateName = to;
                    $rootScope.previousStateNameParams = params;
                    $state.go('login');
                } else if (response.status == 403 && response.config.method != 'GET' && getCSRF() == '') {
            		// If the CSRF token expired, then try to get a new CSRF token and retry the old request
                	var $http = $injector.get('$http');
                	return $http.get('/').finally(function() { return afterCSRFRenewed(response); });
                }
                return $q.reject(response);
            }
        };

        function afterCSRFRenewed(oldResponse) {
        	if (getCSRF() !== '') {
        		// retry the old request after the new CSRF-TOKEN is obtained
        		var $http = $injector.get('$http');
        		return $http(oldResponse.config);
        	} else {
        		// unlikely get here but reject with the old response any way and avoid infinite loop
        		return $q.reject(oldResponse);
        	}
        }

    	function getCSRF() {
    		var name = 'CSRF-TOKEN=';
    		var ca = document.cookie.split(';');
    		for(var i=0; i<ca.length; i++) {
    			var c = ca[i];
    			while (c.charAt(0)==' ') c = c.substring(1);
    			if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    		}
    		return '';
    	}
    })<% } %>;
<|endoftext|>


<commit_before>/**
 * 点选，光线射线投射，需要在Show.js里添加objects[],存放场景中的所有mesh
 * @author XueFeng
 */

var raycasting = function(show) {
	this.raycaster = null;											// 射线
	this.mouse = null;													// 鼠标坐标
	this.intersected = null;										// 与射线相交的物体
	this.renderer = show.renderer;
	show.raycasting = this;

	//this.objects = [];													// 将场景中的objects中的group拆分，存入该数组
	this.meshes = [];
	this.addRayCaster = false;									// 是否开始点选
	this.needUpdate = true;										// 是否需要更新，应对objects数组
};

raycasting.prototype = {

	init : function() {
		//alert("init");
		//初始化raycaster
		this.raycaster = new THREE.Raycaster();
		this.mouse = new THREE.Vector2();
		this.renderer.domElement.addEventListener('click',
				this.onDocumentMouseClick, false);

		this.addRayCaster = true;
	},

	onDocumentMouseClick : function(event) {
		//初始化鼠标信息，初始化raycaster
		//alert("click");
		if (myRayCaster.addRayCaster) {
			event.preventDefault();
			show.raycasting.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
			show.raycasting.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
			show.raycasting.raycaster.setFromCamera(show.raycasting.mouse,
					show.camera);

			var intersections;//与射线相交的所有物体,intersections[0]就是与射线相交的最前面的物体
			//alert("objects.length:" + show.objects.length);
			intersections = show.raycasting.raycaster
					.intersectObjects(myRayCaster.meshes);
			//alert("intersections:"+ intersections.length);

			if (intersections.length > 0) {																	// 存在与射线相交的物体
				if (show.raycasting.raycaster.intersected != intersections[0].object) {
					// alert("color");
					 show.raycasting.intersected = intersections[0].object;

					 if(intersections[0].object.parent instanceof THREE.Group)
						 {
						 		show.selected = intersections[0].object.parent;

								show.signals.objectSelected.dispatch(show.selected);				// 发布选中物体信号
						 }
					 else
						 show.selected = intersections[0].object;								// 选中物体

					 show.selectNeedUpdate = true;
				}

			}
			else
			{
					console.log("没有选中目标物");
			}
		}

	},				// onDocumentMouseClick : function(event)

	setRayCaster : function() {																								// 调用该函数，开启点选功能
		addRayCaster = true;
	},

	update : function() {
		if (this.needUpdate) {
			this.meshes = [];
			this.needUpdate = false;
			for (var i = 0; i < show.objects.length; i++) {// 遍历show.objects中的对象，判断是否为group类型
				if (show.objects[i] instanceof THREE.Group) {// 是group类型，遍历其孩子对象
					//alert("group");
					for(var j = 0; j < show.objects[i].children.length; j ++){
						this.meshes.push(show.objects[i].children[j]);
					}
				} else {
					//alert("not group");
					this.meshes.push(show.objects[i]);
				}
			}
			//alert("meshes0:" + this.meshes.length);
		}
	}

//	 update : function(ray)																										// ray为此类在全局中的名字
//	 {
//	 	if(ray.addRayCaster)											// 如果开启射线功能才去执行其他的更新操作
//	 	{
//
//	 		if(ray.needUpdate)																											// 如果需要更新
//	 		{
//	 			ray.needUpdate = false;
//	 			ray.objects = [];																											// 先将待检测数组置为空数组
//	 			for(var i = 0; i < show.objects.length; i++)
//	 			{
//	 				if(show.objects[i] instanceof THREE.Group)													// 如果遇到group,将Group拆分，不是group直接装入
//	 				{
//	 					var temp = show.objects[i];
//	 					for(var j = 0; j < temp.children.length; j++)
//	 					{
//	 						ray.objects.push(temp.children[j]);															// 将group的每个孩子都加入到数组中
//	 					}
//	 				}		// if(show.objects[i] instanceof THREE.Group)
//	 				else
//	 				{
//	 						ray.objects.push(show.objects[i]);															// 不是group 直接装入数组
//	 				}
//	 			}		// 	for(var i = 0; i < show.objects.length; i++)
//	 		}		// if(ray.needUpdate)
//
//	 	}		// if(ray.addRayCaster)
//
//	 }					// update : fucntion(ray)
};
<commit_msg>射线出问题了<commit_after>/**
 * 点选，光线射线投射，需要在Show.js里添加objects[],存放场景中的所有mesh
 * @author XueFeng
 */

var raycasting = function(show) {
	this.raycaster = null;											// 射线
	this.mouse = null;													// 鼠标坐标
	this.intersected = null;										// 与射线相交的物体
	this.renderer = show.renderer;
	show.raycasting = this;

	//this.objects = [];													// 将场景中的objects中的group拆分，存入该数组
	this.meshes = [];
	this.addRayCaster = false;									// 是否开始点选
	this.needUpdate = true;										// 是否需要更新，应对objects数组
};

raycasting.prototype = {

	init : function() {
		//alert("init");
		//初始化raycaster
		this.raycaster = new THREE.Raycaster();
		this.mouse = new THREE.Vector2();
		this.renderer.domElement.addEventListener('click',
				this.onDocumentMouseClick, false);

		this.addRayCaster = true;
	},

	onDocumentMouseClick : function(event) {
		//初始化鼠标信息，初始化raycaster
		//alert("click");
		if (myRayCaster.addRayCaster) {
			event.preventDefault();
			show.raycasting.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
			show.raycasting.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
			show.raycasting.raycaster.setFromCamera(show.raycasting.mouse,
					show.camera);

			var intersections;//与射线相交的所有物体,intersections[0]就是与射线相交的最前面的物体
			//alert("objects.length:" + show.objects.length);
			intersections = show.raycasting.raycaster
					.intersectObjects(myRayCaster.meshes);
			//alert("intersections:"+ intersections.length);

			if (intersections.length > 0) {																	// 存在与射线相交的物体
				if (show.raycasting.raycaster.intersected != intersections[0].object) {
					// alert("color");
					 show.raycasting.intersected = intersections[0].object;

					 if(intersections[0].object.parent instanceof THREE.Group)
						 {
						 		show.selected = intersections[0].object.parent;

								show.signals.objectSelected.dispatch(show.selected);				// 发布选中物体信号
						 }
					 else
						 show.selected = intersections[0].object;								// 选中物体

					 show.selectNeedUpdate = true;
				}

			}
			else
			{

					console.log("没有选中目标物");
					console.log(show.raycasting.meshes);
					//console.log(show);
			}
		}

	},				// onDocumentMouseClick : function(event)

	setRayCaster : function() {																								// 调用该函数，开启点选功能
		addRayCaster = true;
	},

	update : function() {
		if (this.needUpdate) {
			this.meshes = [];
			this.needUpdate = false;
			for (var i = 0; i < show.objects.length; i++) {// 遍历show.objects中的对象，判断是否为group类型
				if (show.objects[i] instanceof THREE.Group) {// 是group类型，遍历其孩子对象
					//alert("group");
					for(var j = 0; j < show.objects[i].children.length; j ++){
						this.meshes.push(show.objects[i].children[j]);
					}
				} else {
					//alert("not group");
					this.meshes.push(show.objects[i]);
				}
			}
			//alert("meshes0:" + this.meshes.length);
		}
	}

//	 update : function(ray)																										// ray为此类在全局中的名字
//	 {
//	 	if(ray.addRayCaster)											// 如果开启射线功能才去执行其他的更新操作
//	 	{
//
//	 		if(ray.needUpdate)																											// 如果需要更新
//	 		{
//	 			ray.needUpdate = false;
//	 			ray.objects = [];																											// 先将待检测数组置为空数组
//	 			for(var i = 0; i < show.objects.length; i++)
//	 			{
//	 				if(show.objects[i] instanceof THREE.Group)													// 如果遇到group,将Group拆分，不是group直接装入
//	 				{
//	 					var temp = show.objects[i];
//	 					for(var j = 0; j < temp.children.length; j++)
//	 					{
//	 						ray.objects.push(temp.children[j]);															// 将group的每个孩子都加入到数组中
//	 					}
//	 				}		// if(show.objects[i] instanceof THREE.Group)
//	 				else
//	 				{
//	 						ray.objects.push(show.objects[i]);															// 不是group 直接装入数组
//	 				}
//	 			}		// 	for(var i = 0; i < show.objects.length; i++)
//	 		}		// if(ray.needUpdate)
//
//	 	}		// if(ray.addRayCaster)
//
//	 }					// update : fucntion(ray)
};
<|endoftext|>


<commit_before>var getPath = function() {
	return "/";
}
var recentFiles;
var files;
var filesInLocalPath;
var today = new Date();

var profile;

/*$.ajax({method: "GET",
    headers: {'Content-Type': 'application/json'},
    url: "/conf/storage/recent"
    }).done(function(data) {  recentFiles = data; console.log(data);});*/

function onSignIn(googleUser) {
	console.log("Success");

	profile = googleUser.getBasicProfile();
	google = googleUser;
	var user = {
		"email" : profile.getEmail(),
		"firstName" : profile.getGivenName(),
		"lastName" : profile.getFamilyName(),
		"socialId" : profile.getId(),
		"tokenId" : googleUser.getAuthResponse().id_token
	};

	console.log(user);

	$.ajax({
		type : 'POST',
		url : "/conf/user",
		data : JSON.stringify(user),
		error : function(e) {
			console.log(e);
		},
		dataType : "json",
		contentType : "application/json"
	});

}

$(document).ready(function() {

	$.ajax({
		method : "GET",
		headers : {
			'Content-Type' : 'application/json'
		},
		url : "/conf/storage"
	}).done(function(data) {
		files = data;
		console.log(data);
	});

	$("#newTextFile").click(function() {
		console.log("New File");

		var date = {
			"Year" : today.getFullYear(),
			"Month" : today.getMonth() + 1,
			"Date" : today.getDate(),
			"Hour" : today.getHours() + 1,
			"Minute" : today.getMinutes()
		}

		var file = {
			"userPath" : getPath(),
			"storagePath" : null,
			"name" : "untitled document",
			"owner" : profile.getEmail(),
			"type" : "rtf",
			"lastModified" : null,
			"dateCreated" : null,
			"sharedWith" : null
		}

		$.ajax({
			type : 'POST',
			url : "/conf/storage/insert",
			data : JSON.stringify(file),
			error : function(e) {
				console.log(e);
			},
			dataType : "json",
			contentType : "application/json"
		});
	});
});
<commit_msg>Prince is no longer null. Async : false<commit_after>var getPath = function() {
	return "/";
}
var recentFiles;
var files;
var filesInLocalPath;
var today = new Date();

var profile;

/*$.ajax({method: "GET",
    headers: {'Content-Type': 'application/json'},
    url: "/conf/storage/recent"
    }).done(function(data) {  recentFiles = data; console.log(data);});*/

function onSignIn(googleUser) {
	console.log("Success");

	profile = googleUser.getBasicProfile();
	google = googleUser;
	var user = {
		"email" : profile.getEmail(),
		"firstName" : profile.getGivenName(),
		"lastName" : profile.getFamilyName(),
		"socialId" : profile.getId(),
		"tokenId" : googleUser.getAuthResponse().id_token
	};

	console.log(user);

	$.ajax({
		type : 'POST',
		url : "/conf/user",
		data : JSON.stringify(user),
		async : false,
		error : function(e) {
			console.log(e);
		},
		dataType : "json",
		contentType : "application/json"
	});

	$.ajax({
		method : "GET",
		headers : {
			'Content-Type' : 'application/json'
		},
		url : "/conf/storage"
	}).done(function(data) {
		files = data;
		console.log(data);
	});

}

$(document).ready(function() {

	$("#newTextFile").click(function() {
		console.log("New File");

		var date = {
			"Year" : today.getFullYear(),
			"Month" : today.getMonth() + 1,
			"Date" : today.getDate(),
			"Hour" : today.getHours() + 1,
			"Minute" : today.getMinutes()
		}

		var file = {
			"userPath" : getPath(),
			"storagePath" : null,
			"name" : "untitled document",
			"owner" : profile.getEmail(),
			"type" : "rtf",
			"lastModified" : null,
			"dateCreated" : null,
			"sharedWith" : null
		}

		$.ajax({
			type : 'POST',
			url : "/conf/storage/insert",
			data : JSON.stringify(file),
			error : function(e) {
				console.log(e);
			},
			dataType : "json",
			contentType : "application/json"
		});
	});
});
<|endoftext|>


<commit_before>/*
 * #%L
 * wcm.io
 * %%
 * Copyright (C) 2014 - 2015 wcm.io
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
;/**
 * (Id: debug.js 676 2014-06-19 15:47:33Z sseifert )
 */
/**
 * Logs messages to the firebug console or creates an HTML div as alternative console.
 * The plugin is based on the "jQuery plugin for debugging".
 *
 * @copyright       (c) 2007 Ralf S. Engelschall <rse@engelschall.com>
 * @license      GPL <http://www.gnu.org/licenses/gpl.txt>
 * @see        http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/
 */

/*global
  jQuery
*/

/*
 * Wrapper function to use "$" instead of "jQuery"
 * For Aptana/Eclipse: Remove this function to get a Code Assitent and
 * see the outline or generate a documentation
 */
(function($) {
  /*
   * jQuery class extension methods
   */
    $.extend({
        /**
         * boolean status whether debugging is enabled
         */
        _debug$: null,

    /**
     * boolean instance of the console created or not
     */
    _instance$: false,

    /**
     * method for getting and setting debug status
     * @param boolean onoff
     */
        debug: function (onoff) {
            var old_value = ($._debug$ === true ? true : false);
            $._debug$ = (onoff ? true : false);
            return old_value;
        },

    /**
     * method for logging an object or message
     * @param string message
     */
        log: function () {
            if ($._debug$ === true) {
        //create alternative html console
        if($._instance$ === false) {
             $.createConsole();
          $._instance$ = true;
        }
        if(navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
          var str = "";
          for(var i=0; i<arguments.length; i++) {
            str += arguments[i] + " ";
          }
          console.log(str);
        } else {
          console.log.apply(console, arguments);
        }
      }
        },

    /**
     * creates the alternative html console and javascript interface
     */
    createConsole: function() {
      if (typeof window.console === "undefined") {
      /* minimum conversion of arbitrary object to text representation */
      function object2text (obj) {
        var text = null;
        if (typeof obj === "undefined") {
          text = "[undefined]";

        } else if (typeof obj === "boolean") {
          text = (obj ? "true" : "false");

        } else if (typeof obj === "number") {
          text = "" + obj;

        } else if (typeof obj === "string") {
          text = obj;

        } else if (typeof obj === "function") {
          text = obj;

        } else if (typeof obj === "object") {
          if (typeof obj.nodeType !== "undefined") {
            /* W3C DOM element node */
            if (obj.nodeType == 1) {
              text = '<';
              text += obj.nodeName.toLowerCase();
              for (var i = 0; i < obj.attributes.length; i++) {
                text += ' ' + obj.attributes[i].nodeName.toLowerCase() +
                '="' +
                obj.attributes[i].nodeValue +
                '"';
              }
              text += '>';

            /* W3C DOM attribute node */
                        } else if (obj.nodeType == 2) {
              text = obj.nodeName + '="' + obj.nodeValue;

            /* W3C DOM text node */
            } else if (obj.nodeType == 3) {
                text = obj.nodeValue;
            }

                    } else if (typeof obj.toJSONString !== "undefined") {
            text = obj.toJSONString();

          } else if (typeof obj.toString !== "undefined"){
            text = obj.toString();
          }
                }
                if (text === null) {
          text = "[unknown]";
        }
                return text;
            }

            /* create the logging
 node */
            $("body").append('

jQuery debug console

');

            /* attach a function to each of the Firebug methods */
            var names = [
                "log", "debug", "info", "warn", "error", "assert",
                "dir", "dirxml", "group", "groupEnd", "time", "timeEnd",
                "count", "trace", "profile", "profileEnd"
            ];
      window.console = {};
      for (var i = 0; i < names.length; i++) {
        window.console[names[i]] = function() {
          $('#jQueryDebug')
            .css("display", $._debug$ === true ? "block" : "none");

          if(arguments.length == 1) {
            $('#jQueryDebug ol.debugList')
              .append('
' + object2text(arguments[0]) + '
');
          } else {
            var element = '

';
            for(var k = 0; k < arguments.length; k++) {
              element += '
' + object2text(arguments[k]) + '
';
            }
            element += '

';
            $('#jQueryDebug ol.debugList').append(element);
          }

        };
      }

      /* indicate that we are the one who is proving the Firebug interface */
      window.console.jQueryDebug = true;
    }

    }
  });

  /*
   * jQuery object extension methods
   */
  $.fn.extend({
    /**
     * method for logging all jQuery items
     * @param string message
     */
    log: function () {
      if ($._debug$ === true) {
        //create alternative html console
        if($._instance$ === false) {
             $.createConsole();
          $._instance$ = true;
        }

        //cache arguments in extra array
        var args = [];
        for(var i = 0; i < arguments.length; i++) {
          args.push(arguments[i]);
        }

        return this.each(function () {
          //if arguments exits, use them and add element
          if (args.length > 0) {
            //make an independent copy
            var args_temp = args.slice();
            args_temp.push([this]);
            $.log.apply($, args_temp);

          //else only use element
          } else {
            $.log(this);
          }
        });
      }
        }
    });

})(jQuery);

<commit_msg>remove obsolete lines<commit_after>/*
 * #%L
 * wcm.io
 * %%
 * Copyright (C) 2014 - 2015 wcm.io
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
;/**
 * Logs messages to the firebug console or creates an HTML div as alternative console.
 * The plugin is based on the "jQuery plugin for debugging".
 *
 * @copyright       (c) 2007 Ralf S. Engelschall <rse@engelschall.com>
 * @license      GPL <http://www.gnu.org/licenses/gpl.txt>
 * @see        http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/
 */

/*global
  jQuery
*/

/*
 * Wrapper function to use "$" instead of "jQuery"
 * For Aptana/Eclipse: Remove this function to get a Code Assitent and
 * see the outline or generate a documentation
 */
(function($) {
  /*
   * jQuery class extension methods
   */
    $.extend({
        /**
         * boolean status whether debugging is enabled
         */
        _debug$: null,

    /**
     * boolean instance of the console created or not
     */
    _instance$: false,

    /**
     * method for getting and setting debug status
     * @param boolean onoff
     */
        debug: function (onoff) {
            var old_value = ($._debug$ === true ? true : false);
            $._debug$ = (onoff ? true : false);
            return old_value;
        },

    /**
     * method for logging an object or message
     * @param string message
     */
        log: function () {
            if ($._debug$ === true) {
        //create alternative html console
        if($._instance$ === false) {
             $.createConsole();
          $._instance$ = true;
        }
        if(navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
          var str = "";
          for(var i=0; i<arguments.length; i++) {
            str += arguments[i] + " ";
          }
          console.log(str);
        } else {
          console.log.apply(console, arguments);
        }
      }
        },

    /**
     * creates the alternative html console and javascript interface
     */
    createConsole: function() {
      if (typeof window.console === "undefined") {
      /* minimum conversion of arbitrary object to text representation */
      function object2text (obj) {
        var text = null;
        if (typeof obj === "undefined") {
          text = "[undefined]";

        } else if (typeof obj === "boolean") {
          text = (obj ? "true" : "false");

        } else if (typeof obj === "number") {
          text = "" + obj;

        } else if (typeof obj === "string") {
          text = obj;

        } else if (typeof obj === "function") {
          text = obj;

        } else if (typeof obj === "object") {
          if (typeof obj.nodeType !== "undefined") {
            /* W3C DOM element node */
            if (obj.nodeType == 1) {
              text = '<';
              text += obj.nodeName.toLowerCase();
              for (var i = 0; i < obj.attributes.length; i++) {
                text += ' ' + obj.attributes[i].nodeName.toLowerCase() +
                '="' +
                obj.attributes[i].nodeValue +
                '"';
              }
              text += '>';

            /* W3C DOM attribute node */
                        } else if (obj.nodeType == 2) {
              text = obj.nodeName + '="' + obj.nodeValue;

            /* W3C DOM text node */
            } else if (obj.nodeType == 3) {
                text = obj.nodeValue;
            }

                    } else if (typeof obj.toJSONString !== "undefined") {
            text = obj.toJSONString();

          } else if (typeof obj.toString !== "undefined"){
            text = obj.toString();
          }
                }
                if (text === null) {
          text = "[unknown]";
        }
                return text;
            }

            /* create the logging
 node */
            $("body").append('

jQuery debug console

');

            /* attach a function to each of the Firebug methods */
            var names = [
                "log", "debug", "info", "warn", "error", "assert",
                "dir", "dirxml", "group", "groupEnd", "time", "timeEnd",
                "count", "trace", "profile", "profileEnd"
            ];
      window.console = {};
      for (var i = 0; i < names.length; i++) {
        window.console[names[i]] = function() {
          $('#jQueryDebug')
            .css("display", $._debug$ === true ? "block" : "none");

          if(arguments.length == 1) {
            $('#jQueryDebug ol.debugList')
              .append('
' + object2text(arguments[0]) + '
');
          } else {
            var element = '

';
            for(var k = 0; k < arguments.length; k++) {
              element += '
' + object2text(arguments[k]) + '
';
            }
            element += '

';
            $('#jQueryDebug ol.debugList').append(element);
          }

        };
      }

      /* indicate that we are the one who is proving the Firebug interface */
      window.console.jQueryDebug = true;
    }

    }
  });

  /*
   * jQuery object extension methods
   */
  $.fn.extend({
    /**
     * method for logging all jQuery items
     * @param string message
     */
    log: function () {
      if ($._debug$ === true) {
        //create alternative html console
        if($._instance$ === false) {
             $.createConsole();
          $._instance$ = true;
        }

        //cache arguments in extra array
        var args = [];
        for(var i = 0; i < arguments.length; i++) {
          args.push(arguments[i]);
        }

        return this.each(function () {
          //if arguments exits, use them and add element
          if (args.length > 0) {
            //make an independent copy
            var args_temp = args.slice();
            args_temp.push([this]);
            $.log.apply($, args_temp);

          //else only use element
          } else {
            $.log(this);
          }
        });
      }
        }
    });

})(jQuery);

<|endoftext|>


<commit_before>/**
 * React Native for Web Starter App
 * https://github.com/grabcode/react-native-web-starter
 * Follow me https://twitter.com/grabthecode
 */

import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Navigator,
    TouchableHighlight
} from 'react-native';

import {Container} from './navegacao/Container';
import {HomeScene} from '../scenes/Home';
import {SobreScene} from '../scenes/Sobre';

export class App extends Component {
    render() {

        const routes = [
            {title: 'Home', index: 0, name: 'HOME'},
            {title: 'Sobre', index: 1, name: 'SOBRE'}
        ];

        return (
            <Container>

                <Navigator
                    style={styles.navigator}
                    initialRoute={routes[0]}
                    initialRouteStack={routes}
                    renderScene={(route, navigator) =>
                        <TouchableHighlight onPress={() => {
                            if (route.index === 0) {
                                navigator.push(routes[1]);
                            } else {
                                navigator.pop();
                            }
                        }}>
                            <Text>Hello {route.title}!</Text>
                        </TouchableHighlight>

                    }

                />
                <HomeScene />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    navigator: {
        flex: 1
    }
});
<commit_msg>Navigator falhou no Browser<commit_after>/**
 * React Native for Web Starter App
 * https://github.com/grabcode/react-native-web-starter
 * Follow me https://twitter.com/grabthecode
 */

import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Navigator,
    TouchableHighlight
} from 'react-native';

import {Container} from './navegacao/Container';
import {HomeScene} from '../scenes/Home';
import {SobreScene} from '../scenes/Sobre';

export class App extends Component {
    render() {

        const routes = [
            {title: 'Home', index: 0, name: 'HOME'},
            {title: 'Sobre', index: 1, name: 'SOBRE'}
        ];

        return (
            <Container>
                <HomeScene />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    navigator: {
        flex: 1
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.common.gadgets.Curve',
    dependencies: ['og.common.gadgets.manager'],
    obj: function () {
        var prefix = 'og_curve_gadget_', counter = 1, module = this;
        return function (config) {
            var gadget = this, $curve, alive = prefix + counter++;
            gadget.dataman = new og.analytics.Cell({source: config.source, row: config.row, col: config.col})
                .on('data', function (data) {
                    if (!$.isArray(data))
                        return $curve.html('loading...'), og.dev.warn(module.name + ': data should be an Array');
                    gadget.data = [{curve: data}];
                    $curve.update ? $curve.update(gadget.data) : gadget.resize();
                });
            gadget.alive = function () {
                var live = !!$('.' + alive).length;
                if (!live) gadget.dataman.kill();
                return live;
            };
            gadget.resize = function () {
                if (!$(config.selector).length) return;
                $curve = $(config.selector)
                    .css({position: 'absolute', top: 0, left: 0, right: 0, bottom: 0})
                    .ogcurve(gadget.data);
            };
            $curve = $(config.selector).addClass(alive);
            if (!config.child) og.common.gadgets.manager.register(gadget);
        };
    }
});<commit_msg>move curve gadget loading notification to initialization instead of to data event handler<commit_after>/**
 * Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.common.gadgets.Curve',
    dependencies: ['og.common.gadgets.manager'],
    obj: function () {
        var prefix = 'og_curve_gadget_', counter = 1, module = this;
        return function (config) {
            var gadget = this, $curve, alive = prefix + counter++;
            gadget.dataman = new og.analytics.Cell({source: config.source, row: config.row, col: config.col})
                .on('data', function (data) {
                    if (!$.isArray(data)) return og.dev.warn(module.name + ': data should be an Array', data);
                    gadget.data = [{curve: data}];
                    $curve.update ? $curve.update(gadget.data) : gadget.resize();
                });
            gadget.alive = function () {
                var live = !!$('.' + alive).length;
                if (!live) gadget.dataman.kill();
                return live;
            };
            gadget.resize = function () {
                if (!$(config.selector).length) return;
                $curve = $(config.selector)
                    .css({position: 'absolute', top: 0, left: 0, right: 0, bottom: 0})
                    .ogcurve(gadget.data);
            };
            $curve = $(config.selector).addClass(alive).html('loading...');
            if (!config.child) og.common.gadgets.manager.register(gadget);
        };
    }
});<|endoftext|>


<commit_before>'use strict';

const EDITOR_MODE_CREATE = 1;
const EDITOR_MODE_EDIT   = 2;

const ADD_NEW_FIELD_BUTTON_ROW = 'add_new_field_button';

const DELETABLE_ROW = 'deletable_row';

function EntityEditor(entity_wall) {
    this.__init__(entity_wall);
}

EntityEditor.prototype = {

    __init__: function(entity_wall_manager) {
        this.entity_wall_manager = entity_wall_manager;
        this.base_wall = this.entity_wall_manager.base_wall;
        this.world = this.base_wall.world;
        this.entity_wall = this.entity_wall_manager.entity_wall;

        this.current_mode = null;
    },

    create_or_save_changes_button_pressed: function() {
        if (this.current_mode === EDITOR_MODE_CREATE) {
            this._entity_created();
        } else {
            this._modify_entity();
        }
    },

    cancel_or_delete_button_pressed: function() {
        if (this.current_mode === EDITOR_MODE_CREATE) {
            this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
        } else {
            this.entity_wall_manager.delete_entity(this.entity_being_edited);
        }
    },

    delete_entity_field: function(field_name) {
        delete this.entity_field_rows[field_name];
        this.wall_entity_editor.delete_row_by_name(field_name);

        if (this.current_mode === EDITOR_MODE_EDIT) {
            this.entity_being_edited.delete_property(field_name);
        }

        this.base_wall.refresh_position_and_look_at();
    },

    create: function(edit_mode) {
        if (!is_defined(this.wall_entity_editor)) {
            this.wall_entity_editor = new FloatingWall(600, 400, null, null, this.base_wall.world, false, COLOR_FLOATING_WALL_SUCCESS);
            this.wall_entity_editor.manual_visibility = true;
            this.wall_entity_editor.set_attachment_depth_offset(10);
            this.wall_entity_editor.add_close_button();

            this.wall_title = this.wall_entity_editor.add_row(-1).add_3D_element('HODL IOTA', TYPE_TITLE);

            this.entity_field_rows = {};

            // Default field : entity type selector.
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE] = new FieldRowEntityType(this);
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].create(null);

            // Default field : entity name.
            this.entity_field_rows[ENTITY_PROPERTY_NAME] = new FieldRowName(this);
            this.entity_field_rows[ENTITY_PROPERTY_NAME].create(null);

            // Both creating a new entity and editing an existing entity will contain an add a new field button.
            this.add_new_field_button = this.wall_entity_editor.add_row(null, ADD_NEW_FIELD_BUTTON_ROW).add_2D_button([0, 1], 'add new field', COLOR_BLUE, null);

            // Both creating a new entity and editing an existing entity will contain an create/save-changes button.
            this.create_or_save_changes_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_GREEN, this.create_or_save_changes_button_pressed.bind(this));

            // Both creating a new entity and editing an existing entity will contain an delete/cancel button.
            this.cancel_or_delete_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_RED, this.cancel_or_delete_button_pressed.bind(this));

            // Create the entity field creator.
            this.wall_entity_field_creater = new EntityFieldCreator(this);
            this.wall_entity_field_creater.set_display_button(this.add_new_field_button);
        } else {
            this.wall_entity_editor.detach_from_parent();
        }

        // Delete all previously made non-default entity field rows.
        var field_rows_to_delete = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key !== ENTITY_DEFAULT_PROPERTY_TYPE && key !== ENTITY_PROPERTY_NAME) {
                    field_rows_to_delete.push(key);
                }
            }
        }
        for (var r = 0; r < field_rows_to_delete.length; r++) {
            this.wall_entity_editor.delete_row_by_name(field_rows_to_delete[r]);
            delete this.entity_field_rows[field_rows_to_delete[r]];
        }

        if (edit_mode === EDITOR_MODE_CREATE) {
            this.current_mode = EDITOR_MODE_CREATE;

            this.wall_entity_editor.attach_to(this.create_new_entity_button);
            this.wall_entity_editor.set_auto_adjust_height(true);
            this.wall_title.update_text('Create New Entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_to_default();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_to_default();

            this.create_or_save_changes_button.update_text('create entity');
            this.cancel_or_delete_button.update_text('cancel');
        } else {
            this.current_mode = EDITOR_MODE_EDIT;

            this.wall_entity_editor.attach_to(this.entity_being_edited_button);
            this.wall_entity_editor.set_auto_adjust_height(true);
            this.wall_title.update_text('Editing : ' + this.entity_being_edited.get_value(ENTITY_PROPERTY_NAME));

            this.create_or_save_changes_button.update_text('save changes');
            this.cancel_or_delete_button.update_text('delete entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_from_entity();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_from_entity();

            // TODO : Populate all the required entity field rows.
            var all_non_default_editable_fields = this.entity_being_edited.get_all_non_default_editable_fields();
            // Sort the fields alphabetically.
            all_non_default_editable_fields = all_non_default_editable_fields.sort(function(a, b) {
                return a[0] > b[0];
            });

            for (var f = 0; f < all_non_default_editable_fields.length; f++) {
                this.add_entity_field(all_non_default_editable_fields[f][0], all_non_default_editable_fields[f][1]);
            }
        }

        this.wall_entity_editor.force_display_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    _add_entity_field: function(field_name) {
        if (field_name === ENTITY_PROPERTY_START_DATE_TIME || field_name === ENTITY_PROPERTY_END_DATE_TIME) {
            this.entity_field_rows[field_name] = new FieldRowDateTime(this, field_name);
        } else if (field_name === ENTITY_PROPERTY_COMPLETED) {
            this.entity_field_rows[field_name] = new FieldRowCompleted(this);
        } else {
            this.entity_field_rows[field_name] = new FieldRowRegular(this, field_name);
        }
        return this.entity_field_rows[field_name];
    },

    add_entity_field: function(field_name, field_value) {
        // Check if the field was already added.
        if (!this.wall_entity_editor.has_row_with_name(field_name)) {

            // Get the row index of the 'add new field' button.
            var insert_index_for_row = this.wall_entity_editor.get_row_with_name(ADD_NEW_FIELD_BUTTON_ROW).row_number;

            var new_entity_field = this._add_entity_field(field_name);
            new_entity_field.create(insert_index_for_row, field_value);

            this.base_wall.refresh_position_and_look_at();
        }
    },

    _opened_for_first_time: function() {
        this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].hide_extra_elements();
    },

    _hide_self_and_update: function() {
        this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    /*___      ___   ___         ___  __    ___         __
     |__  |\ |  |  |  |  \ /    |__  |  \ |  |  | |\ | / _`
     |___ | \|  |  |  |   |     |___ |__/ |  |  | | \| \__> */
    edit_entity: function(entity, entity_row_button) {
        this.entity_being_edited_button = entity_row_button;
        this.entity_being_edited = entity;
        this.create(EDITOR_MODE_EDIT);
        this._opened_for_first_time();
    },

    _modify_entity: function() {
        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            this.entity_being_edited.set_property(all_entities_fields_and_values[f][0], all_entities_fields_and_values[f][1]);
            this.entity_being_edited_button.update_text(this.entity_being_edited.get_value(ENTITY_PROPERTY_NAME));
        }
        this._hide_self_and_update();
    },

    /*___      ___   ___         __   __   ___      ___    __
     |__  |\ |  |  |  |  \ /    /  ` |__) |__   /\   |  | /  \ |\ |
     |___ | \|  |  |  |   |     \__, |  \ |___ /~~\  |  | \__/ | \| */
    _entity_created: function() {
        var entity_to_create = new Entity();
        entity_to_create.add_parent(this.entity_wall_manager.entity_wall_entity);

        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            entity_to_create.set_property(all_entities_fields_and_values[f][0], all_entities_fields_and_values[f][1]);
        }
        this.entity_wall_manager.add_entity(entity_to_create);
        this._hide_self_and_update();
    },

    set_create_entity_display_button: function(button) {
        this.create_new_entity_button = button;
        this.create_new_entity_button.set_engage_function(this._create_new_entity_button_pressed.bind(this));
    },

    _create_new_entity_button_pressed: function() {
        this.create(EDITOR_MODE_CREATE);
        this._opened_for_first_time();
    },

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    in_creation_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_CREATE;
        }
        return false;
    },

    in_editing_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_EDIT;
        }
        return false;
    },

    _get_all_entity_fields_and_values: function() {
        var entity_fields_and_values = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key.startsWith(ENTITY_PROPERTY_START_TOKEN)) {
                    entity_fields_and_values.push([key, this.entity_field_rows[key].get_value()]);
                }
            }
        }
        return entity_fields_and_values;
    },

    has_field: function(field_name) {
        return this.wall_entity_editor.has_row_with_name(field_name);
    }

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

const EDITOR_MODE_CREATE = 1;
const EDITOR_MODE_EDIT   = 2;

const ADD_NEW_FIELD_BUTTON_ROW = 'add_new_field_button';

const DELETABLE_ROW = 'deletable_row';

function EntityEditor(entity_wall) {
    this.__init__(entity_wall);
}

EntityEditor.prototype = {

    __init__: function(entity_wall_manager) {
        this.entity_wall_manager = entity_wall_manager;
        this.base_wall = this.entity_wall_manager.base_wall;
        this.world = this.base_wall.world;
        this.entity_wall = this.entity_wall_manager.entity_wall;

        this.current_mode = null;
    },

    create_or_save_changes_button_pressed: function() {
        if (this.current_mode === EDITOR_MODE_CREATE) {
            this._entity_created();
        } else {
            this._modify_entity();
        }
    },

    cancel_or_delete_button_pressed: function() {
        if (this.current_mode === EDITOR_MODE_CREATE) {
            this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
        } else {
            this.entity_wall_manager.delete_entity(this.entity_being_edited);
        }
    },

    delete_entity_field: function(field_name) {
        delete this.entity_field_rows[field_name];
        this.wall_entity_editor.delete_row_by_name(field_name);

        if (this.current_mode === EDITOR_MODE_EDIT) {
            this.entity_being_edited.delete_property(field_name);
        }

        this.base_wall.refresh_position_and_look_at();
    },

    create: function(edit_mode) {
        if (!is_defined(this.wall_entity_editor)) {
            this.wall_entity_editor = new FloatingWall(600, 400, null, null, this.base_wall.world, false, COLOR_FLOATING_WALL_SUCCESS);
            this.wall_entity_editor.manual_visibility = true;
            this.wall_entity_editor.set_attachment_depth_offset(10);
            this.wall_entity_editor.add_close_button();

            this.wall_title = this.wall_entity_editor.add_row(-1).add_3D_element('HODL IOTA', TYPE_TITLE);

            this.entity_field_rows = {};

            // Default field : entity type selector.
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE] = new FieldRowEntityType(this);
            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].create(null);

            // Default field : entity name.
            this.entity_field_rows[ENTITY_PROPERTY_NAME] = new FieldRowName(this);
            this.entity_field_rows[ENTITY_PROPERTY_NAME].create(null);

            // Both creating a new entity and editing an existing entity will contain an add a new field button.
            this.add_new_field_button = this.wall_entity_editor.add_row(null, ADD_NEW_FIELD_BUTTON_ROW).add_2D_button([0, 1], 'add new field', COLOR_BLUE, null);

            // Both creating a new entity and editing an existing entity will contain an create/save-changes button.
            this.create_or_save_changes_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_GREEN, this.create_or_save_changes_button_pressed.bind(this));

            // Both creating a new entity and editing an existing entity will contain an delete/cancel button.
            this.cancel_or_delete_button = this.wall_entity_editor.add_row(null).add_2D_button([0, 1], 'SET MY TEXT', COLOR_RED, this.cancel_or_delete_button_pressed.bind(this));

            // Create the entity field creator.
            this.wall_entity_field_creater = new EntityFieldCreator(this);
            this.wall_entity_field_creater.set_display_button(this.add_new_field_button);
        } else {
            this.wall_entity_editor.detach_from_parent();
        }

        // Delete all previously made non-default entity field rows.
        this.wall_entity_editor.set_auto_adjust_height(false);
        var field_rows_to_delete = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key !== ENTITY_DEFAULT_PROPERTY_TYPE && key !== ENTITY_PROPERTY_NAME) {
                    field_rows_to_delete.push(key);
                }
            }
        }
        for (var r = 0; r < field_rows_to_delete.length; r++) {
            this.wall_entity_editor.delete_row_by_name(field_rows_to_delete[r]);
            delete this.entity_field_rows[field_rows_to_delete[r]];
        }

        if (edit_mode === EDITOR_MODE_CREATE) {
            this.current_mode = EDITOR_MODE_CREATE;

            this.wall_entity_editor.attach_to(this.create_new_entity_button);
            this.wall_entity_editor.set_auto_adjust_height(true);
            this.wall_title.update_text('Create New Entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_to_default();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_to_default();

            this.create_or_save_changes_button.update_text('create entity');
            this.cancel_or_delete_button.update_text('cancel');
        } else {
            this.current_mode = EDITOR_MODE_EDIT;

            this.wall_entity_editor.attach_to(this.entity_being_edited_button);
            this.wall_entity_editor.set_auto_adjust_height(true);
            this.wall_title.update_text('Editing : ' + this.entity_being_edited.get_value(ENTITY_PROPERTY_NAME));

            this.create_or_save_changes_button.update_text('save changes');
            this.cancel_or_delete_button.update_text('delete entity');

            this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].set_value_from_entity();
            this.entity_field_rows[ENTITY_PROPERTY_NAME].set_value_from_entity();

            // TODO : Populate all the required entity field rows.
            var all_non_default_editable_fields = this.entity_being_edited.get_all_non_default_editable_fields();
            // Sort the fields alphabetically.
            all_non_default_editable_fields = all_non_default_editable_fields.sort(function(a, b) {
                return a[0] > b[0];
            });

            for (var f = 0; f < all_non_default_editable_fields.length; f++) {
                this.add_entity_field(all_non_default_editable_fields[f][0], all_non_default_editable_fields[f][1]);
            }
        }

        this.wall_entity_editor.force_display_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    _add_entity_field: function(field_name) {
        if (field_name === ENTITY_PROPERTY_START_DATE_TIME || field_name === ENTITY_PROPERTY_END_DATE_TIME) {
            this.entity_field_rows[field_name] = new FieldRowDateTime(this, field_name);
        } else if (field_name === ENTITY_PROPERTY_COMPLETED) {
            this.entity_field_rows[field_name] = new FieldRowCompleted(this);
        } else {
            this.entity_field_rows[field_name] = new FieldRowRegular(this, field_name);
        }
        return this.entity_field_rows[field_name];
    },

    add_entity_field: function(field_name, field_value) {
        // Check if the field was already added.
        if (!this.wall_entity_editor.has_row_with_name(field_name)) {

            // Get the row index of the 'add new field' button.
            var insert_index_for_row = this.wall_entity_editor.get_row_with_name(ADD_NEW_FIELD_BUTTON_ROW).row_number;

            var new_entity_field = this._add_entity_field(field_name);
            new_entity_field.create(insert_index_for_row, field_value);

            this.base_wall.refresh_position_and_look_at();
        }
    },

    _opened_for_first_time: function() {
        this.entity_field_rows[ENTITY_DEFAULT_PROPERTY_TYPE].hide_extra_elements();
    },

    _hide_self_and_update: function() {
        this.wall_entity_editor.force_hide_self_and_all_child_attachments_recursively();
        this.base_wall.refresh_position_and_look_at();
    },

    /*___      ___   ___         ___  __    ___         __
     |__  |\ |  |  |  |  \ /    |__  |  \ |  |  | |\ | / _`
     |___ | \|  |  |  |   |     |___ |__/ |  |  | | \| \__> */
    edit_entity: function(entity, entity_row_button) {
        this.entity_being_edited_button = entity_row_button;
        this.entity_being_edited = entity;
        this.create(EDITOR_MODE_EDIT);
        this._opened_for_first_time();
    },

    _modify_entity: function() {
        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            this.entity_being_edited.set_property(all_entities_fields_and_values[f][0], all_entities_fields_and_values[f][1]);
            this.entity_being_edited_button.update_text(this.entity_being_edited.get_value(ENTITY_PROPERTY_NAME));
        }
        this._hide_self_and_update();
    },

    /*___      ___   ___         __   __   ___      ___    __
     |__  |\ |  |  |  |  \ /    /  ` |__) |__   /\   |  | /  \ |\ |
     |___ | \|  |  |  |   |     \__, |  \ |___ /~~\  |  | \__/ | \| */
    _entity_created: function() {
        var entity_to_create = new Entity();
        entity_to_create.add_parent(this.entity_wall_manager.entity_wall_entity);

        var all_entities_fields_and_values = this._get_all_entity_fields_and_values();
        for (var f = 0; f < all_entities_fields_and_values.length; f++) {
            entity_to_create.set_property(all_entities_fields_and_values[f][0], all_entities_fields_and_values[f][1]);
        }
        this.entity_wall_manager.add_entity(entity_to_create);
        this._hide_self_and_update();
    },

    set_create_entity_display_button: function(button) {
        this.create_new_entity_button = button;
        this.create_new_entity_button.set_engage_function(this._create_new_entity_button_pressed.bind(this));
    },

    _create_new_entity_button_pressed: function() {
        this.create(EDITOR_MODE_CREATE);
        this._opened_for_first_time();
    },

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    in_creation_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_CREATE;
        }
        return false;
    },

    in_editing_mode: function() {
        if (is_defined(this.current_mode)) {
            return this.current_mode === EDITOR_MODE_EDIT;
        }
        return false;
    },

    _get_all_entity_fields_and_values: function() {
        var entity_fields_and_values = [];
        for (var key in this.entity_field_rows) {
            if (this.entity_field_rows.hasOwnProperty(key)) {
                if (key.startsWith(ENTITY_PROPERTY_START_TOKEN)) {
                    entity_fields_and_values.push([key, this.entity_field_rows[key].get_value()]);
                }
            }
        }
        return entity_fields_and_values;
    },

    has_field: function(field_name) {
        return this.wall_entity_editor.has_row_with_name(field_name);
    }

};<|endoftext|>


<commit_before>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;
const ANIMATION_TIME = ONE_SECOND / 2;

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.floating_label = new Floating2DText(150, icon_type, TYPE_BUTTON, this.world.scene);

                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, this.y_position, position.z + nz * 5));

        this.normal = new THREE.Vector3(nx, 0, nz);
        this.left_right = new THREE.Vector3(0, 1, 0);
        this.left_right.cross(this.normal);
        this.left_right.normalize();

        this.floating_label.update_position_and_normal(new THREE.Vector3(this.object3D.position.x + this.left_right.x * 30, this.object3D.position.y, this.object3D.position.z + this.left_right.z * 30), this.normal);
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
        this.floating_label.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 >= ANIMATION_TIME) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / ANIMATION_TIME;
        }

        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 81<commit_after>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;
const ANIMATION_TIME = ONE_SECOND / 2;

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);

                var icon_label = '';
                switch (icon_type) {
                case ICON_SAVE:
                    icon_label = 'save';
                    break;
                case ICON_EXIT:
                    icon_label = 'exit';
                    break;
                case ICON_MULTIPLAYER:
                    icon_label = 'multiplayer';
                    break;
                case ICON_HOME:
                    icon_label = 'home';
                    break;
                case ICON_SETTINGS:
                    icon_label = 'settings';
                    break;
                }
                this.floating_label = new Floating2DText(100, icon_label, TYPE_BUTTON, this.world.scene);

                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, this.y_position, position.z + nz * 5));

        this.normal = new THREE.Vector3(nx, 0, nz);
        this.left_right = new THREE.Vector3(0, 1, 0);
        this.left_right.cross(this.normal);
        this.left_right.normalize();

        var horizontal_shift = 75;

        this.floating_label.update_position_and_normal(new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift, this.object3D.position.y, this.object3D.position.z + this.left_right.z * horizontal_shift), this.normal);
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
        this.floating_label.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 >= ANIMATION_TIME) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / ANIMATION_TIME;
        }

        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|>