<commit_before>window.onload = function() {
  // alert("HELLO");
  /* -- SETTINGS -- */
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "500",
    "hideDuration": "1000",
    "timeOut": "650",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  };

  /* Taken from http://jsfiddle.net/raving/2thfaxeu/ Author: raving 02-17-2016 */
  var originalLeave = $.fn.popover.Constructor.prototype.leave;
  $.fn.popover.Constructor.prototype.leave = function(obj){
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
    var container, timeout;

    originalLeave.call(this, obj);

    if(obj.currentTarget) {
      container = $(obj.currentTarget).siblings('.popover')
      timeout = self.timeout;
      container.one('mouseenter', function(){
        //We entered the actual popover – call off the dogs
        clearTimeout(timeout);
        //Let's monitor popover content instead
        container.one('mouseleave', function(){
          $.fn.popover.Constructor.prototype.leave.call(self, self);
        });
      })
    }
  };

  /* Taken from http://jsfiddle.net/raving/2thfaxeu/ Author: raving 02-17-2016 */
  $('body').popover({ selector: '[data-popover]', trigger: 'click hover', placement: 'auto', delay: {show: 50, hide: 400}});

  // Taken from https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax 2016-03-04
  function getCookie(name) {
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
  var csrftoken = getCookie('csrftoken');

  /* -- Deletes posts -- */
  $("button.delete-post").click(function(event) {
    var that = this;
    var id = this.id.slice(12);
    $.ajax({
      url: 'http://' + window.location.host +'/api/posts/' + id + '/',
      type: "DELETE",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        $(that).parent().parent().remove();
        toastr.info("Post Deleted!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  /* -- Deletes posts from editing page -- */
  $("button.delete-post-single").click(function(event) {
    var that = this;
    var id = this.id.slice(12);
    $.ajax({
      url: 'http://' + window.location.host +'/api/posts/' + id + '/',
      type: "DELETE",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        toastr.info("Post Deleted!");
        window.location.replace("http://" + window.location.host);
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  /* -- Deletes comments -- */
  $("button.delete-comment").click(function(event) {
    var that = this;
    var comment_id = this.id.slice(15);
    var post_id = $(this).data("post-id");
    $.ajax({
      url: 'http://' + window.location.host +'/api/posts/' + post_id + '/comments/' + comment_id,
      type: "DELETE",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        var commentItem = $(that).parent().parent().parent();
        var commentHR = commentItem.next();
        commentHR.remove();
        commentItem.remove();
        toastr.info("Comment Deleted!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  /* -- Hide Upload Image Modal Initially -- */
  $("#uploadImageModal").hide();
  $("#uploadProfileImageModal").hide();

  $("#uploadImageForm").submit(function(event){
    event.preventDefault();
    var formData = new FormData($("#uploadImageForm")[0]);
    $.ajax({
      url: 'http://' + window.location.host + '/api/images/',
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        // close modal
        $("button#closeUploadImageModal").click();
        // clear upload image form
        $("form#uploadImageForm").trigger("reset");
        // append "Image Attached" element
        $("#uploadImageTrigger").after('Image Attached!');
        // disable add image button in create post form
        $("#uploadImageTrigger").prop("disabled", true);
        // add image url to form's hidden image_url field (on create post form)
        $("input#id_image_url").val(response.photo);
        toastr.info("Image Uploaded!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  $("#uploadProfileImageForm").submit(function(event) {
    event.preventDefault();
    var formData = new FormData($("#uploadProfileImageForm")[0]);
    formData.append("github_name", "");
    formData.append("host", "");
    var authorID = $("#uploadProfileImageForm").data("author-id");
    $.ajax({
      url: 'http://' + window.location.host + '/api/authors/' + authorID + '/',
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        // close modal
        $("button#closeUploadProfileImageModal").click();
        // clear upload image form
        $("form#uploadProfileImageForm").trigger("reset");
        // change user profile image
        $("img#id-user-profile-image").attr('src', response.picture);
        toastr.info("Profile Image Updated!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });
};<commit_msg>user profile upload image fix<commit_after>window.onload = function() {
  // alert("HELLO");
  /* -- SETTINGS -- */
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "500",
    "hideDuration": "1000",
    "timeOut": "650",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  };

  /* Taken from http://jsfiddle.net/raving/2thfaxeu/ Author: raving 02-17-2016 */
  var originalLeave = $.fn.popover.Constructor.prototype.leave;
  $.fn.popover.Constructor.prototype.leave = function(obj){
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
    var container, timeout;

    originalLeave.call(this, obj);

    if(obj.currentTarget) {
      container = $(obj.currentTarget).siblings('.popover')
      timeout = self.timeout;
      container.one('mouseenter', function(){
        //We entered the actual popover – call off the dogs
        clearTimeout(timeout);
        //Let's monitor popover content instead
        container.one('mouseleave', function(){
          $.fn.popover.Constructor.prototype.leave.call(self, self);
        });
      })
    }
  };

  /* Taken from http://jsfiddle.net/raving/2thfaxeu/ Author: raving 02-17-2016 */
  $('body').popover({ selector: '[data-popover]', trigger: 'click hover', placement: 'auto', delay: {show: 50, hide: 400}});

  // Taken from https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax 2016-03-04
  function getCookie(name) {
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
  var csrftoken = getCookie('csrftoken');

  /* -- Deletes posts -- */
  $("button.delete-post").click(function(event) {
    var that = this;
    var id = this.id.slice(12);
    $.ajax({
      url: 'http://' + window.location.host +'/api/posts/' + id + '/',
      type: "DELETE",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        $(that).parent().parent().remove();
        toastr.info("Post Deleted!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  /* -- Deletes posts from editing page -- */
  $("button.delete-post-single").click(function(event) {
    var that = this;
    var id = this.id.slice(12);
    $.ajax({
      url: 'http://' + window.location.host +'/api/posts/' + id + '/',
      type: "DELETE",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        toastr.info("Post Deleted!");
        window.location.replace("http://" + window.location.host);
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  /* -- Deletes comments -- */
  $("button.delete-comment").click(function(event) {
    var that = this;
    var comment_id = this.id.slice(15);
    var post_id = $(this).data("post-id");
    $.ajax({
      url: 'http://' + window.location.host +'/api/posts/' + post_id + '/comments/' + comment_id,
      type: "DELETE",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        var commentItem = $(that).parent().parent().parent();
        var commentHR = commentItem.next();
        commentHR.remove();
        commentItem.remove();
        toastr.info("Comment Deleted!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  /* -- Hide Upload Image Modal Initially -- */
  $("#uploadImageModal").hide();
  $("#uploadProfileImageModal").hide();

  $("#uploadImageForm").submit(function(event){
    event.preventDefault();
    var formData = new FormData($("#uploadImageForm")[0]);
    $.ajax({
      url: 'http://' + window.location.host + '/api/images/',
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        console.log(response);
        // close modal
        $("button#closeUploadImageModal").click();
        // clear upload image form
        $("form#uploadImageForm").trigger("reset");
        // append "Image Attached" element
        $("#uploadImageTrigger").after('Image Attached!');
        // disable add image button in create post form
        $("#uploadImageTrigger").prop("disabled", true);
        // add image url to form's hidden image_url field (on create post form)
        $("input#id_image_url").val(response.photo);
        toastr.info("Image Uploaded!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });

  $("#uploadProfileImageForm").submit(function(event) {
    event.preventDefault();
    var formData = new FormData($("#uploadProfileImageForm")[0]);
    formData.append("github_name", "");
    formData.append("host", "");
    var authorID = $("#uploadProfileImageForm").data("author-id");
    $.ajax({
      url: 'http://' + window.location.host + '/api/author/' + authorID + '/',
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
      },
      success: function(response) {
        // close modal
        $("button#closeUploadProfileImageModal").click();
        // clear upload image form
        $("form#uploadProfileImageForm").trigger("reset");
        // change user profile image
        $("img#id-user-profile-image").attr('src', response.picture);
        toastr.info("Profile Image Updated!");
      },
      error: function(xhr, ajaxOptions, error) {
        console.log(xhr.status);
        console.log(xhr.responseText);
        console.log(error);
      }
    });
  });
};<|endoftext|>


<commit_before>canvasWidth = (window.innerWidth / 100) * 70;
canvasHeight = (window.innerHeight / 100) * 80;

players = [];
playerPositions = [];
playerNames = [];
velocity = [2,2];

startX = 0;
startY = 0;

$(document).ready(function() {

  stage = new Kinetic.Stage({
    container: "game-container",
    width: canvasWidth,
    height: canvasHeight
  });
  layer = new Kinetic.Layer();

  // Super shiny header
  herps();

  conn = new WebSocket('ws://109.109.137.94:8080');

  conn.onopen = function(e) {
    console.log("Connection established!");
    var gridRequest = '{"operation":"GAME","type":"create","message":"crystalmaze","size":"21","sender":"steph","id":388542958}';
    conn.send(gridRequest);
  };

  conn.onclose = function(e) {
    console.log("Connection closed!");
  };

  conn.onmessage = function(e) {
    var json = JSON.parse(e.data);
    if (json.operation === "PLAYER" && json.type === "move") {
      movePlayer(0, parseInt(json.x), parseInt(json.y));
    } else if (json.operation === "PLAYER" && json.type === "new") {
      playerNames.push(json.name);
      addPlayer();
    } else if (json.operation === "GAME" && json.type === "new") {
      grid = json.grid;
      gridWidth = grid[0].length;
      gridHeight = grid.length;

      mazeBlockWidth = Math.round(canvasWidth / gridWidth);
      mazeBlockHeight = Math.round(canvasHeight / gridHeight);

      buildMaze();

      // Add the layer to the stage
      stage.add(layer);

    } else if (json.operation === "GAME" && json.type === "win") {
      setInterval(function() {
        $("#win-box h2").css({ color: getRandomColor() });
      }, 100);
      $("#win-box").css({ display: "fixed" });
    }
  };

});

  function buildMaze() {
    for (var i = 0; i < grid.length; i++) {
      for (var j = 0; j < grid[i].length; j++) {
        buildMazeBlock(i,j);
      };
    };
  }

  function buildMazeBlock(i,j) {
    var blockFill = ""
    if (grid[j][i] === " ") {
       return;
    } else if (grid[j][i] === "#") {
      blockFill = "rgb(100,100,100)";
    } else if (grid[j][i] === "s") {
      startX = i;
      startY = j;
      return;
    }

    var block = new Kinetic.Rect({
      x: i * mazeBlockWidth,
      y: j * mazeBlockHeight,
      width: mazeBlockWidth,
      height: mazeBlockHeight,
      fill: blockFill
    });

    if (grid[j][i] === "e") {
      setInterval(function() {
        block.setFill(getRandomColor());
        layer.draw();
      },100);
    }

    layer.add(block);
    layer.draw();
  }

  function addPlayer() {
    var newPlayer = new Kinetic.Rect({
      x: startX * mazeBlockWidth,
      y: startY * mazeBlockHeight,
      width: mazeBlockWidth,
      height: mazeBlockHeight,
      fill: getRandomColor()
    });

    players.push(newPlayer);
    playerPositions.push([startX,startY]);

    // add the shape to the layer
    layer.add(newPlayer);
    stackPlayers(startX,startY);
    layer.draw();
  }

  function stackPlayers(i,j) {
    var stackedPlayers = [];
    for (var k = 0; k < players.length; k++) {
      if (playerPositions[k][0] === i && playerPositions[k][1] === j) {
        stackedPlayers.push(players[k]);
      }
    }

    var stackRows = Math.ceil(stackedPlayers.length / 2);
    for (var k = 0; k < stackedPlayers.length; k++) {
      var row = Math.floor(k / 2);
      var column = k % 2;

      // Adjust x and y
      stackedPlayers[k].setPosition(
        i * mazeBlockWidth + column * Math.round(mazeBlockWidth / 2),
        j * mazeBlockHeight + row * Math.round(mazeBlockHeight / stackRows)
      );

      // Adjust width and height
      if (stackedPlayers.length % 2 === 0 || row != (stackRows - 1)) {
        stackedPlayers[k].setWidth(Math.round(mazeBlockWidth / 2));
      } else {
        stackedPlayers[k].setWidth(mazeBlockWidth);
      }

      stackedPlayers[k].setHeight(Math.ceil(mazeBlockHeight / stackRows));
    }

    layer.draw();

  }

  function movePlayer(playerIndex, i, j) {
    players[playerIndex].setWidth(mazeBlockWidth);
    players[playerIndex].setHeight(mazeBlockHeight);

    var oldX = playerPositions[playerIndex][0];
    var oldY = playerPositions[playerIndex][1];

    playerPositions[playerIndex] = [i,j];
    stackPlayers(oldX,oldY);

    var tween = new Kinetic.Tween({
      node: players[playerIndex],
      duration: 1,
      x: i * mazeBlockWidth,
      y: j * mazeBlockHeight,
      opacity: 1,
      onFinish: function() {
        stackPlayers(playerPositions[playerIndex][0],playerPositions[playerIndex][1]);
      }
    });

    tween.play();
  }

  function whatIsWallWhatisNot() {
    $(".kineticjs-content").css({ background: "rgb(100,100,100)" });
    setTimeout(function() {
      $(".kineticjs-content").css({ background: "rgb(220,220,220)" });
    },2000);
  }

  function getRandomColor() {
      var letters = '0123456789ABCDEF'.split('');
      var color = '#';
      for (var i = 0; i < 6; i++ ) {
          color += letters[Math.round(Math.random() * 15)];
      }
      return color;
  }

  function herps() {

    var interval;
    $("header").mouseover(function() {
      interval = setInterval(function() {
        $("h1").css({ color: getRandomColor() });
      }, 100);
    });
    $("header").mouseout(function() {
      clearInterval(interval);
      $("h1").css({ color: "rgb(80,80,80)" });
    });
  }<commit_msg>uses name to figure out shape<commit_after>canvasWidth = (window.innerWidth / 100) * 70;
canvasHeight = (window.innerHeight / 100) * 80;

players = [];
playerPositions = [];
playerNames = [];
velocity = [2,2];

startX = 0;
startY = 0;

$(document).ready(function() {

  stage = new Kinetic.Stage({
    container: "game-container",
    width: canvasWidth,
    height: canvasHeight
  });
  layer = new Kinetic.Layer();

  // Super shiny header
  herps();

  conn = new WebSocket('ws://109.109.137.94:8080');

  conn.onopen = function(e) {
    console.log("Connection established!");
    var gridRequest = '{"operation":"GAME","type":"create","message":"crystalmaze","size":"21","sender":"steph","id":388542958}';
    conn.send(gridRequest);
  };

  conn.onclose = function(e) {
    console.log("Connection closed!");
  };

  conn.onmessage = function(e) {
    var json = JSON.parse(e.data);
    if (json.operation === "PLAYER" && json.type === "move") {
      var playerIndex = -1;
      for (var k = 0; k < playerNames.length; k++) {
        if (playerNames[k] === json.name) {
          playerIndex = k;
        }
      }
      if (playerIndex > -1) {
        movePlayer(0, parseInt(json.x), parseInt(json.y));
      } else {
        console.log("Couldn't find player " + json.name);
      }
    } else if (json.operation === "PLAYER" && json.type === "join") {
      playerNames.push(json.name);
      addPlayer();
    } else if (json.operation === "GAME" && json.type === "new") {
      grid = json.grid;
      gridWidth = grid[0].length;
      gridHeight = grid.length;

      mazeBlockWidth = Math.round(canvasWidth / gridWidth);
      mazeBlockHeight = Math.round(canvasHeight / gridHeight);

      buildMaze();

      // Add the layer to the stage
      stage.add(layer);

    } else if (json.operation === "GAME" && json.type === "win") {
      setInterval(function() {
        $("#win-box h2").css({ color: getRandomColor() });
      }, 100);
      $("#win-box").css({
        position: "fixed",
        display: "block"
      });
    }
  };

});

  function buildMaze() {
    for (var i = 0; i < grid.length; i++) {
      for (var j = 0; j < grid[i].length; j++) {
        buildMazeBlock(i,j);
      };
    };
  }

  function buildMazeBlock(i,j) {
    var blockFill = ""
    if (grid[j][i] === " ") {
       return;
    } else if (grid[j][i] === "#") {
      blockFill = "rgb(100,100,100)";
    } else if (grid[j][i] === "s") {
      startX = i;
      startY = j;
      return;
    }

    var block = new Kinetic.Rect({
      x: i * mazeBlockWidth,
      y: j * mazeBlockHeight,
      width: mazeBlockWidth,
      height: mazeBlockHeight,
      fill: blockFill
    });

    if (grid[j][i] === "e") {
      setInterval(function() {
        block.setFill(getRandomColor());
        layer.draw();
      },100);
    }

    layer.add(block);
    layer.draw();
  }

  function addPlayer() {
    var newPlayer = new Kinetic.Rect({
      x: startX * mazeBlockWidth,
      y: startY * mazeBlockHeight,
      width: mazeBlockWidth,
      height: mazeBlockHeight,
      fill: getRandomColor()
    });

    players.push(newPlayer);
    playerPositions.push([startX,startY]);

    // add the shape to the layer
    layer.add(newPlayer);
    stackPlayers(startX,startY);
    layer.draw();
  }

  function stackPlayers(i,j) {
    var stackedPlayers = [];
    for (var k = 0; k < players.length; k++) {
      if (playerPositions[k][0] === i && playerPositions[k][1] === j) {
        stackedPlayers.push(players[k]);
      }
    }

    var stackRows = Math.ceil(stackedPlayers.length / 2);
    for (var k = 0; k < stackedPlayers.length; k++) {
      var row = Math.floor(k / 2);
      var column = k % 2;

      // Adjust x and y
      stackedPlayers[k].setPosition(
        i * mazeBlockWidth + column * Math.round(mazeBlockWidth / 2),
        j * mazeBlockHeight + row * Math.round(mazeBlockHeight / stackRows)
      );

      // Adjust width and height
      if (stackedPlayers.length % 2 === 0 || row != (stackRows - 1)) {
        stackedPlayers[k].setWidth(Math.round(mazeBlockWidth / 2));
      } else {
        stackedPlayers[k].setWidth(mazeBlockWidth);
      }

      stackedPlayers[k].setHeight(Math.ceil(mazeBlockHeight / stackRows));
    }

    layer.draw();

  }

  function movePlayer(playerIndex, i, j) {
    players[playerIndex].setWidth(mazeBlockWidth);
    players[playerIndex].setHeight(mazeBlockHeight);

    var oldX = playerPositions[playerIndex][0];
    var oldY = playerPositions[playerIndex][1];

    playerPositions[playerIndex] = [i,j];
    stackPlayers(oldX,oldY);

    var tween = new Kinetic.Tween({
      node: players[playerIndex],
      duration: 1,
      x: i * mazeBlockWidth,
      y: j * mazeBlockHeight,
      opacity: 1,
      onFinish: function() {
        stackPlayers(playerPositions[playerIndex][0],playerPositions[playerIndex][1]);
      }
    });

    tween.play();
  }

  function whatIsWallWhatisNot() {
    $(".kineticjs-content").css({ background: "rgb(100,100,100)" });
    setTimeout(function() {
      $(".kineticjs-content").css({ background: "rgb(220,220,220)" });
    },2000);
  }

  function getRandomColor() {
      var letters = '0123456789ABCDEF'.split('');
      var color = '#';
      for (var i = 0; i < 6; i++ ) {
          color += letters[Math.round(Math.random() * 15)];
      }
      return color;
  }

  function herps() {

    var interval;
    $("header").mouseover(function() {
      interval = setInterval(function() {
        $("h1").css({ color: getRandomColor() });
      }, 100);
    });
    $("header").mouseout(function() {
      clearInterval(interval);
      $("h1").css({ color: "rgb(80,80,80)" });
    });
  }<|endoftext|>


<commit_before>// import neiTools from './nei';
import path from 'path';
import fs from 'fs';
import os from 'os';
import {util, fileUtil, DispatherTypes} from '../../helper';
import _ from 'util';
import globule from 'globule';

function getMockConfig(config) {
    const neiConfigRoot = path.resolve(config.neiConfigRoot, 'server.config.js');
    return require(neiConfigRoot);
}

function writeNEIConfig({NEIRoute}, formatR) {
    fileUtil.writeFile(NEIRoute, `module.exports = ${_.inspect(formatR, {maxArrayLength: null})}`, () => {
    }, (e) => {
        util.error(e);
    });
}

function updateLocalFiles(routes = [], genCommonPath) {
    return Promise.all(routes.map((route) =>
        new Promise((resolve, reject) => {
            /**
             * 本地路径（非nei）
             */
            let dataPath = genCommonPath(route);
            fs.stat(dataPath, error => {
                /**
                 * 文件不存在或者文件内容为空
                 */
                if (error) {
                    util.log('make empty file: ' + dataPath);
                    fileUtil.writeUnExistsFile(dataPath, '').then(resolve, resolve);
                    return 0;
                }
                resolve();
            });
        })));
}

function formatRoutes(rules) {
    function isSync(rule) {
        return rule.hasOwnProperty('list');
    }

    function getRouteFileInfo(rule) {
        return isSync(rule) ? {
            filePath: rule.list[0].path,
            id: rule.list[0].id
        } : {
            filePath: rule.path,
            id: rule.id
        };
    }

    function getRouteURLInfo(ruleName, rule) {
        const [method, url] = ruleName.split(' ');

        return {
            method,
            url: util.appendHeadBreak(url),
            sync: isSync(rule),
        }
    }

    return Object.keys(rules).map(ruleName => {
        const rule = rules[ruleName];
        return Object.assign(
            getRouteURLInfo(ruleName, rule),
            getRouteFileInfo(rule));
    });
}

function initData({key, update = false}) {
    const basedir = path.resolve(os.homedir(), 'localMock', key);
    const NEIRoute = path.resolve(basedir, 'nei.route.js');
    const [serverConfigFile] = globule.find(path.resolve(basedir, 'nei**/server.config.js'));

    return {key, update, basedir, NEIRoute, serverConfigFile};
}

/**
 * Nei 插件
 */
class NEISyncPlugin {
    constructor(options) {
        this.NEIInfo = initData(options);
    }

    init(serverPlugin) {
        this.server = serverPlugin.server;
        const {update} = this.NEIInfo;

        if (update) {
            this.syncNEIData();
        } else {
            this.useLocalData();
        }
    }

    useLocalData() {
        const {serverConfigFile, NEIRoute} = this.NEIInfo;
        if (!serverConfigFile) {
            return this.syncNEIData();
        }

        this.setMock(require(serverConfigFile));
        this.updateRoutes(require(NEIRoute));
    }

    setMock({mockApi, mockTpl}) {
        Object.assign(this.NEIInfo,
            {
                mock: {
                    api: mockApi,
                    tpl: mockTpl
                }
            }
        );
    }

    getMock() {
        return this.NEIInfo.mock;
    }

    syncNEIData() {
        const {key, basedir} = this.NEIInfo;

        return this.pending(end => require('./NEISync').default
            .run({key, basedir})
            .then((config) => this.getUpdate(config))
            .then((routes) => {
                this.updateRoutes(routes);
                end();
            })
            .catch(e => {
                console.error(e);
            })
        );
    }

    getUpdate(config) {

        const {routes, mockApi, mockTpl} = getMockConfig(config);
        const formatR = formatRoutes(routes);

        this.setMock({mockApi, mockTpl});

        writeNEIConfig(this.NEIInfo, formatR);

        updateLocalFiles(formatR, this.genCommonPath.bind(this));

        return formatR;
    }

    updateRoutes(routes) {
        const genCommonPath = this.genCommonPath.bind(this);
        const genNeiApiUrl = this.genNeiApiUrl.bind(this);
        const server = this.server;
        server.use(() => function *(next) {
            const dispatcher = this.dispatcher;

            if (!dispatcher
                || dispatcher.type == DispatherTypes.DIR
                || !dispatcher.isRouter) {
                return yield next;
            }

            const routeModel = {
                sync: DispatherTypes.SYNC == dispatcher.type,
                filePath: dispatcher.filePath,
            };
            const commonPath = genCommonPath(routeModel);

            dispatcher.dataPath = [genNeiApiUrl(routeModel), commonPath];
            yield next;
        });
        server.routers = server.routers.concat(routes);
    }

    genCommonPath(route) {
        const server = this.server;
        let filePath = route.filePath;

        if (route.sync) {
            return server.syncDataMatch(util.jsonPathResolve(route.filePath));
        }

        if (!server.divideMethod) {
            const methodReg = /(GET)|(DELETE)|(HEAD)|(PATCH)|(POST)|(PUT)\//i;
            filePath = filePath.replace(methodReg, '');
        }

        return server.asyncDataMatch(util.jsonPathResolve(filePath.replace(/\/data/g, '')));
    }

    genNeiApiUrl(route) {
        const {api, tpl} = this.getMock();
        return path.resolve(route.sync ? tpl : api, route.filePath + '.json');
    }
}

export default NEISyncPlugin;
<commit_msg>调整 NEI 阻塞，使创建mock文件的提示早于 Server Build 的提示<commit_after>// import neiTools from './nei';
import path from 'path';
import fs from 'fs';
import os from 'os';
import {util, fileUtil, DispatherTypes} from '../../helper';
import _ from 'util';
import globule from 'globule';

function getMockConfig(config) {
    const neiConfigRoot = path.resolve(config.neiConfigRoot, 'server.config.js');
    return require(neiConfigRoot);
}

function writeNEIConfig({NEIRoute}, formatR) {
    fileUtil.writeFile(NEIRoute, `module.exports = ${_.inspect(formatR, {maxArrayLength: null})}`, () => {
    }, (e) => {
        util.error(e);
    });
}

function updateLocalFiles(routes = [], getFilePath) {
    return Promise.all(routes.map((route) =>
        new Promise((resolve, reject) => {
            /**
             * 本地路径（非nei）
             */
            let dataPath = getFilePath(route);
            fs.stat(dataPath, error => {
                /**
                 * 文件不存在或者文件内容为空
                 */
                if (error) {
                    util.log('make empty file: ' + dataPath);
                    fileUtil.writeUnExistsFile(dataPath, '').then(resolve, resolve);
                    return 0;
                }
                resolve();
            });
        })));
}

function formatRoutes(rules) {
    function isSync(rule) {
        return rule.hasOwnProperty('list');
    }

    function getRouteFileInfo(rule) {
        return isSync(rule) ? {
            filePath: rule.list[0].path,
            id: rule.list[0].id
        } : {
            filePath: rule.path,
            id: rule.id
        };
    }

    function getRouteURLInfo(ruleName, rule) {
        const [method, url] = ruleName.split(' ');

        return {
            method,
            url: util.appendHeadBreak(url),
            sync: isSync(rule),
        }
    }

    return Object.keys(rules).map(ruleName => {
        const rule = rules[ruleName];
        return Object.assign(
            getRouteURLInfo(ruleName, rule),
            getRouteFileInfo(rule));
    });
}

function initData({key, update = false}) {
    const basedir = path.resolve(os.homedir(), 'localMock', key);
    const NEIRoute = path.resolve(basedir, 'nei.route.js');
    const [serverConfigFile] = globule.find(path.resolve(basedir, 'nei**/server.config.js'));

    return {key, update, basedir, NEIRoute, serverConfigFile};
}

/**
 * Nei 插件
 */
class NEISyncPlugin {
    constructor(options) {
        this.NEIInfo = initData(options);
    }

    init(serverPlugin) {
        this.server = serverPlugin.server;
        const {update} = this.NEIInfo;

        if (update) {
            this.syncNEIData();
        } else {
            this.useLocalData();
        }
    }

    useLocalData() {
        const {serverConfigFile, NEIRoute} = this.NEIInfo;
        if (!serverConfigFile) {
            return this.syncNEIData();
        }

        this.setMock(require(serverConfigFile));
        this.updateRoutes(require(NEIRoute));
    }

    setMock({mockApi, mockTpl}) {
        Object.assign(this.NEIInfo,
            {
                mock: {
                    api: mockApi,
                    tpl: mockTpl
                }
            }
        );
    }

    getMock() {
        return this.NEIInfo.mock;
    }

    syncNEIData() {
        const {key, basedir} = this.NEIInfo;

        return this.pending(end =>
            require('./NEISync')
                .default
                .run({key, basedir})
                .then(config => this.getUpdate(config))
                .then(routes => {
                    this.updateRoutes(routes);
                    end();
                })
                .catch(e => {
                    console.error(e);
                })
        );
    }

    getUpdate(config) {
        const {routes, mockApi, mockTpl} = getMockConfig(config);
        const formatR = formatRoutes(routes);
        const getFilePath = this.genCommonPath.bind(this);

        this.setMock({mockApi, mockTpl});
        writeNEIConfig(this.NEIInfo, formatR);

        return updateLocalFiles(formatR, getFilePath).then(() => {
            return formatR;
        });
    }

    updateRoutes(routes) {
        const genCommonPath = this.genCommonPath.bind(this);
        const genNeiApiUrl = this.genNeiApiUrl.bind(this);
        const server = this.server;
        server.use(() => function *(next) {
            const dispatcher = this.dispatcher;

            if (!dispatcher
                || dispatcher.type == DispatherTypes.DIR
                || !dispatcher.isRouter) {
                return yield next;
            }

            const routeModel = {
                sync: DispatherTypes.SYNC == dispatcher.type,
                filePath: dispatcher.filePath,
            };
            const commonPath = genCommonPath(routeModel);

            dispatcher.dataPath = [genNeiApiUrl(routeModel), commonPath];
            yield next;
        });
        server.routers = server.routers.concat(routes);
    }

    genCommonPath(route) {
        const server = this.server;
        let filePath = route.filePath;

        if (route.sync) {
            return server.syncDataMatch(util.jsonPathResolve(route.filePath));
        }

        if (!server.divideMethod) {
            const methodReg = /(GET)|(DELETE)|(HEAD)|(PATCH)|(POST)|(PUT)\//i;
            filePath = filePath.replace(methodReg, '');
        }

        return server.asyncDataMatch(util.jsonPathResolve(filePath.replace(/\/data/g, '')));
    }

    genNeiApiUrl(route) {
        const {api, tpl} = this.getMock();
        return path.resolve(route.sync ? tpl : api, route.filePath + '.json');
    }
}

export default NEISyncPlugin;
<|endoftext|>


<commit_before>// Here is where you can define configuration overrides based on the execution environment.
// Supply a key to the default export matching the NODE_ENV that you wish to target, and
// the base configuration will apply your overrides before exporting itself.
module.exports = {
  // ======================================================
  // Overrides when NODE_ENV === 'development'
  // ======================================================
  // NOTE: In development, we use an explicit public path when the assets
  // are served webpack by to fix this issue:
  // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
  development: (config) => ({
    compiler_public_path: `http://${config.server_host}:${config.server_port}/`
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'production'
  // ======================================================
  sandbox: (config) => ({
    compiler_public_path: `http://${config.server_host}:${config.server_port}/`
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'production'
  // ======================================================
  production: (config) => ({
    compiler_public_path: '/',
    compiler_fail_on_warning: false,
    compiler_hash_type: 'chunkhash',
    compiler_devtool: null,
    compiler_stats: {
      chunks: true,
      chunkModules: true,
      colors: true
    }
  })
};
<commit_msg>added quality env<commit_after>// Here is where you can define configuration overrides based on the execution environment.
// Supply a key to the default export matching the NODE_ENV that you wish to target, and
// the base configuration will apply your overrides before exporting itself.
module.exports = {
  // ======================================================
  // Overrides when NODE_ENV === 'development'
  // ======================================================
  // NOTE: In development, we use an explicit public path when the assets
  // are served webpack by to fix this issue:
  // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
  development: (config) => ({
    compiler_public_path: `http://${config.server_host}:${config.server_port}/`
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'quality'
  // ======================================================
  quality: (config) => ({
    compiler_public_path: `http://${config.server_host}:${config.server_port}/`
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'production'
  // ======================================================
  sandbox: (config) => ({
    compiler_public_path: `http://${config.server_host}:${config.server_port}/`
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'production'
  // ======================================================
  production: (config) => ({
    compiler_public_path: '/',
    compiler_fail_on_warning: false,
    compiler_hash_type: 'chunkhash',
    compiler_devtool: null,
    compiler_stats: {
      chunks: true,
      chunkModules: true,
      colors: true
    }
  })
};
<|endoftext|>


<commit_before>'use strict';

let Response = require('../../tools/response');
let mongoose = require('mongoose');
let async = require('async');

module.exports = function (projectSchema) {
    // Tools methods
    projectSchema.statics.create = function (params, callback) {
        let Self = this;

        params.kanban = null;
        params.userStories = [];

        let project = new Self(params);

        project.save(callback);
    };

    projectSchema.statics.edit = function (params, callback) {
        let Self = this;

        async.waterfall([
            (next) => Self.findOne({'_id': params._id}, next),
            (project, next) => {
                if (!project)
                    next('No project found !');
                else
                    Self.update({_id: params._id}, {$set: params}, next);
            }
        ], (err, project) => {
            if (err)
                return callback(err);

            callback(null, project);
        });
    };

    projectSchema.statics.addUser = function (params, callback) {
        let Self = this;

        async.waterfall([
            (next) => Self.findOne({'_id': params._id}, next),
            (project, next) => {
                if (!project)
                    next('No project found !');
                else
                    Self.update({_id: params._id}, {$push: {users: params.userId}}, next);
            }
        ], (err, project) => {
            if (err)
                return callback(err);

            callback(null, project);
        });
    };

    projectSchema.statics.getById = function(params, callback) {
        mongoose.model('Project')
            .findById(params.id)
            .exec(callback);
    };

    projectSchema.statics.getAll = function(params, callback) {
        mongoose.model('Project')
            .find()
            .exec(callback);
    };

    // Verifications methods
    function checkParametersForCreate(req, res, callback) {
        let parametersOk = false;

        if (!req.body || !req.body.name) {
            Response.missing(res, 'name', -11);
        } else if (!req.body.description) {
            Response.missing(res, 'description', -12);
        } else {
            parametersOk = true;
        }

        if (parametersOk) {
            callback();
        } else {
            callback({
                alreadySent: true
            });
        }
    }

    // Express calls
    projectSchema.statics.exCreate = function (req, res) {
        async.waterfall([
            (next) => checkParametersForCreate(req, res, next),
            (next) => mongoose.model('Project').create(req.body, next)
        ], (err, project) => {
            if (err && err.alreadySent) {
                return;
            }

            if (err && err.code === Response.MongoCodes.alreadyExist)
                return Response.alreadyExist(res, 'name');
            else if (err)
                return Response.insertError(res, err);

            return Response.success(res, 'Project added', project);
        });
    };

    projectSchema.statics.exEdit = function (req, res) {
        /*
         TODO: Wait for authentication to enable this code !
         if (!req.isLogged())
         return Response.notAllowed(res);
         */

        mongoose.model('Project').edit(req.body, (err) => {
            if (err)
                return Response.editError(res, err);

            return Response.success(res, 'Edit successfull', {});
        });
    };

    projectSchema.statics.exRegister = function (req, res) {
        async.waterfall([
            (next) => {
                let parametersOK = false;

                if (!req.body || !req.body.userId)
                    Response.missing(res, 'userId', -11);
                else
                    parametersOK = true;

                if (parametersOK) {
                    let params = req;
                    params.body._id = req.body.userId;
                    mongoose.model('User').exists(params, res, next);
                } else {
                    next({
                        alreadySent: true
                    });
                }
            },
            (next) => mongoose.model('Project').addUser(req.body, next)
        ], (err, project) => {
            if (err && err.alreadySent)
                return;

            if (err)
                return Response.insertError(res, err);

            return Response.success(res, 'User added', project);
        });
    };

    projectSchema.statics.exGet = function(req, res) {
        mongoose.model('Project').getById(req.params, (err, project) => {
            if (err)
                return Response.selectError(err);

            if (!project)
                return Response.resourceNotFound(res, 'project');

            Response.success(res, 'Project found !', project);
        });
    };

    projectSchema.statics.exGetAll = function (req, res) {
        mongoose.model('Project').getAll({}, (err, projects) => {
            if (err)
                return Response.selectError(err);

            if (!projects || projects.length === 0)
                return Response.resourceNotFound(res, 'projects');

            Response.success(res, 'Projects found !', projects);
        });
    };
};<commit_msg>fix(server): Replace bad code with easy object !<commit_after>'use strict';

let Response = require('../../tools/response');
let mongoose = require('mongoose');
let async = require('async');

module.exports = function (projectSchema) {
    // Tools methods
    projectSchema.statics.create = function (params, callback) {
        let Self = this;

        params.kanban = null;
        params.userStories = [];

        let project = new Self(params);

        project.save(callback);
    };

    projectSchema.statics.edit = function (params, callback) {
        let Self = this;

        async.waterfall([
            (next) => Self.findOne({'_id': params._id}, next),
            (project, next) => {
                if (!project)
                    next('No project found !');
                else
                    Self.update({_id: params._id}, {$set: params}, next);
            }
        ], (err, project) => {
            if (err)
                return callback(err);

            callback(null, project);
        });
    };

    projectSchema.statics.addUser = function (params, callback) {
        let Self = this;

        async.waterfall([
            (next) => Self.findOne({'_id': params._id}, next),
            (project, next) => {
                if (!project)
                    next('No project found !');
                else
                    Self.update({_id: params._id}, {$push: {users: params.userId}}, next);
            }
        ], (err, project) => {
            if (err)
                return callback(err);

            callback(null, project);
        });
    };

    projectSchema.statics.getById = function(params, callback) {
        mongoose.model('Project')
            .findById(params.id)
            .exec(callback);
    };

    projectSchema.statics.getAll = function(params, callback) {
        mongoose.model('Project')
            .find()
            .exec(callback);
    };

    // Verifications methods
    function checkParametersForCreate(req, res, callback) {
        let parametersOk = false;

        if (!req.body || !req.body.name) {
            Response.missing(res, 'name', -11);
        } else if (!req.body.description) {
            Response.missing(res, 'description', -12);
        } else {
            parametersOk = true;
        }

        if (parametersOk) {
            callback();
        } else {
            callback({
                alreadySent: true
            });
        }
    }

    // Express calls
    projectSchema.statics.exCreate = function (req, res) {
        async.waterfall([
            (next) => checkParametersForCreate(req, res, next),
            (next) => mongoose.model('Project').create(req.body, next)
        ], (err, project) => {
            if (err && err.alreadySent) {
                return;
            }

            if (err && err.code === Response.MongoCodes.alreadyExist)
                return Response.alreadyExist(res, 'name');
            else if (err)
                return Response.insertError(res, err);

            return Response.success(res, 'Project added', project);
        });
    };

    projectSchema.statics.exEdit = function (req, res) {
        /*
         TODO: Wait for authentication to enable this code !
         if (!req.isLogged())
         return Response.notAllowed(res);
         */

        mongoose.model('Project').edit(req.body, (err) => {
            if (err)
                return Response.editError(res, err);

            return Response.success(res, 'Edit successfull', {});
        });
    };

    projectSchema.statics.exRegister = function (req, res) {
        async.waterfall([
            (next) => {
                let parametersOK = false;

                if (!req.body || !req.body.userId)
                    Response.missing(res, 'userId', -11);
                else
                    parametersOK = true;

                if (parametersOK) {
                    mongoose.model('User').exists({body: {_id: req.body.userId}}, res, next);
                } else {
                    next({
                        alreadySent: true
                    });
                }
            },
            (next) => mongoose.model('Project').addUser(req.body, next)
        ], (err, project) => {
            if (err && err.alreadySent)
                return;

            if (err)
                return Response.insertError(res, err);

            return Response.success(res, 'User added', project);
        });
    };

    projectSchema.statics.exGet = function(req, res) {
        mongoose.model('Project').getById(req.params, (err, project) => {
            if (err)
                return Response.selectError(err);

            if (!project)
                return Response.resourceNotFound(res, 'project');

            Response.success(res, 'Project found !', project);
        });
    };

    projectSchema.statics.exGetAll = function (req, res) {
        mongoose.model('Project').getAll({}, (err, projects) => {
            if (err)
                return Response.selectError(err);

            if (!projects || projects.length === 0)
                return Response.resourceNotFound(res, 'projects');

            Response.success(res, 'Projects found !', projects);
        });
    };
};<|endoftext|>


<commit_before>var WikiParser = Editor.Parser = (function() {

	var run = 0;

	function log(message) {
		if (console && run <= 2)
			console.log(message);
	}

	var tokenizeWiki = (function() {

		function next(source) {
			if (source.endOfLine())
				throw "end-of-line";
			var ch = source.next();
			log("consumed: '" + ch + "'");
			return ch;
		}

		function reset(source) {
			var s = source.get();
			// log("reset: " + s);
			source.push(s);
		}

		function header(depth) {
			var endmarker = ' ';
			for (i = 0; i < depth; i++) {
				endmarker += '=';
			}
			return function(source, setState) {
				// log("header(" + source.peek() + ")")
				for (i = 0; i < depth; i++) {
					next(source);
				}
				next(source);
				// log("header-1(" + source.peek() + ")")
				var marker = '';
				while (!source.endOfLine()) {
					var ch = next(source);
					if (ch == ' ') {
						marker = ' ';
						continue;
					}
					if (ch != '=') {
						marker = '';
						continue;
					}
					marker += ch;
					if (source.endOfLine() && marker == endmarker) {
						setState(begin);
						return 'wiki-h' + depth;
					}
				}
				reset(source);
				setState(normal());
				return null;
			};
		}

		function list(source, setState) {
			// log("list(" + source.peek() + ")")
			next(source);
			next(source);
			if (source.endOfLine()) {
				setState(begin);
			} else {
				setState(normal());
			}
			return 'wiki-list';
		}

		function wrapper(prefix, suffix, style) {
			return function(source, setState) {
				// log("wrapper(" + source.peek() + ")");
				for (i = 0; i < prefix.length; i++) {
					next(source);
				}
				while (!source.endOfLine()) {
					if (source.lookAhead(suffix)) {
						for (i = 0; i < suffix.length; i++) {
							next(source);
						}
						if (source.endOfLine()) {
							setState(begin);
						} else {
							setState(normal());
						}
						return style;
					}
					next(source);
				}
				reset(source);
				next(source);
				setState(normal());
				return null;
			};
		}

		function code(source, setState) {
			// log("code(" + source.peek() + ")");
			while (!source.endOfLine()) {
				var ch = source.peek();
				if (ch == '<') {
					if (source.lookAhead('')) {
						next(source);
						next(source);
						next(source);
						next(source);
						next(source);
						next(source);
						next(source);
						if (source.endOfLine()) {
							setState(begin);
						} else {
							setState(normal());
						}
						return "wiki-code";
					}
				}
				next(source);
			}
			return "wiki-code";
		}

		function normal() {
			return normalUntil();
		}

		function normalUntil(breakTest, breakState) {
			return function(source, setState) {
				log("normal(" + source.peek() + ")");
				var prev = ' ';
				while (!source.endOfLine()) {
					var prevIsAlphaNum;
					var ch = source.peek();
					if (breakTest && breakTest(ch)) {
						setState(breakState);
						return 'wiki-text';
					}
					if (/\s/.test(prev)) {
						if (ch == '<' && source.lookAhead('')) {
							setState(wrapper('', '', 'wiki-code'));
							return 'wiki-text';
						}
						if (ch == "'" && source.lookAhead("'''''")) {
							setState(wrapper("'''''", "'''''", 'wiki-bold-italic'));
							return 'wiki-text';
						}
						if (ch == "'" && source.lookAhead("'''")) {
							setState(wrapper("'''", "'''", 'wiki-bold'));
							return 'wiki-text';
						}
						if (ch == "'" && source.lookAhead("''")) {
							setState(wrapper("''", "''", 'wiki-italic'));
							return 'wiki-text';
						}
					}
					prev = ch;
					next(source);
				}
				setState(begin);
				return 'wiki-text';
			}
		}

		function tableCell() {
			return function(source, setState) {
				log("tableCell(" + source.peek() + ")");
				while (!source.endOfLine()) {
					var ch = source.peek();
					if (ch == '|') {
						setState(table);
						return 'wiki-text';
					}
					next(source);
				}
				return 'wiki-text';
			};
		}

		function table(source, setState) {
			log("table(" + source.peek() + ")");
			if (!source.endOfLine()) {
				var ch = next(source);
				if (ch == '|') {
					if (source.lookAhead('}')) {
						next(source);
						if (source.endOfLine()) {
							setState(begin);
						} else {
							var test = function(ch) {return ch=='|' || ch=='!'};
							setState(normalUntil(test,table));
						}
						return 'wiki-table';
					}
					return 'wiki-table';
				}
				return 'wiki-text';
				setState(tableCell());
			}
			return 'wiki-table';
		}

		function begin(source, setState) {
			log("begin(" + source.peek() + ")");

			if (source.indented) {
				while (!source.endOfLine())
					source.next();
				return "wiki-preformated";
			}

			var ch = source.peek();

			if (ch == '=') {
				if (ch == '=' && source.lookAhead('= ')) {
					setState(header(1));
					return null;
				}
				if (source.lookAhead('== ')) {
					setState(header(2));
					return null;
				}
				if (source.lookAhead('=== ')) {
					setState(header(3));
					return null;
				}
				if (source.lookAhead('==== ')) {
					setState(header(4));
					return null;
				}
			}

			if (ch == '<' && source.lookAhead('')) {
				setState(code);
				return null;
			}

			if ((ch == '*' && source.lookAhead('* ')) || (ch == '#' && source.lookAhead('# '))) {
				setState(list);
				return null;
			}

			if (ch == '{' && source.lookAhead('{|')) {
				next(source);
				setState(table);
				return null;
			}

			setState(normal())
			return null;
		}

		return function(source, startState) {
			run++;
			return tokenizer(source, startState || begin);
		};

	})();

	function indentWiki(inBraces, inRule, base) {
		return function(nextChars) {
			return base;
		};
	}

	function parseWiki(source, basecolumn) {
		basecolumn = basecolumn || 0;
		tokens = tokenizeWiki(source);

		var iter = {
			next : function() {
				var token = tokens.next();
				var style = token.style;
				var content = token.content;

				// console.log("content: "+content);

				if (content == '\n') {
					token.indentation = indentWiki(false, false, basecolumn);
				}

				return token;
			},

			copy : function() {
				var _tokenState = tokens.state;
				return function(source) {
					tokens = tokenizeWiki(source, _tokenState);
					return iter;
				};
			}
		};
		return iter;
	}

	return {
		make : parseWiki
	};
})();
<commit_msg>wiki parser: tables<commit_after>var WikiParser = Editor.Parser = (function() {

	var run = 0;

	function log(message) {
		if (console && run <= 2)
			console.log(message);
	}

	var tokenizeWiki = (function() {

		function next(source) {
			if (source.endOfLine())
				throw "end-of-line";
			var ch = source.next();
			log("consumed: '" + ch + "'");
			return ch;
		}

		function reset(source) {
			var s = source.get();
			// log("reset: " + s);
			source.push(s);
		}

		function header(depth) {
			var endmarker = ' ';
			for (i = 0; i < depth; i++) {
				endmarker += '=';
			}
			return function(source, setState) {
				// log("header(" + source.peek() + ")")
				for (i = 0; i < depth; i++) {
					next(source);
				}
				next(source);
				// log("header-1(" + source.peek() + ")")
				var marker = '';
				while (!source.endOfLine()) {
					var ch = next(source);
					if (ch == ' ') {
						marker = ' ';
						continue;
					}
					if (ch != '=') {
						marker = '';
						continue;
					}
					marker += ch;
					if (source.endOfLine() && marker == endmarker) {
						setState(begin);
						return 'wiki-h' + depth;
					}
				}
				reset(source);
				setState(normal());
				return null;
			};
		}

		function list(source, setState) {
			// log("list(" + source.peek() + ")")
			next(source);
			next(source);
			if (source.endOfLine()) {
				setState(begin);
			} else {
				setState(normal());
			}
			return 'wiki-list';
		}

		function wrapper(prefix, suffix, style, lineEndState) {
			return function(source, setState) {
				// log("wrapper(" + source.peek() + ")");
				for (i = 0; i < prefix.length; i++) {
					next(source);
				}
				while (!source.endOfLine()) {
					if (source.lookAhead(suffix)) {
						for (i = 0; i < suffix.length; i++) {
							next(source);
						}
						if (source.endOfLine()) {
							setState(lineEndState);
						} else {
							setState(normal());
						}
						return style;
					}
					next(source);
				}
				reset(source);
				next(source);
				setState(normal());
				return null;
			};
		}

		function code(source, setState) {
			// log("code(" + source.peek() + ")");
			while (!source.endOfLine()) {
				var ch = source.peek();
				if (ch == '<') {
					if (source.lookAhead('')) {
						next(source);
						next(source);
						next(source);
						next(source);
						next(source);
						next(source);
						next(source);
						if (source.endOfLine()) {
							setState(begin);
						} else {
							setState(normal());
						}
						return "wiki-code";
					}
				}
				next(source);
			}
			return "wiki-code";
		}

		function normal() {
			return normalUntil(null, null, begin);
		}

		function normalUntil(breakTest, breakState, lineEndState) {
			return function(source, setState) {
				log("normal(" + source.peek() + ")");
				var prev = ' ';
				while (!source.endOfLine()) {
					var prevIsAlphaNum;
					var ch = source.peek();
					if (breakTest && breakTest(ch)) {
						setState(breakState);
						return 'wiki-text';
					}
					if (/\s/.test(prev)) {
						if (ch == '<' && source.lookAhead('')) {
							setState(wrapper('', '', 'wiki-code', lineEndState));
							return 'wiki-text';
						}
						if (ch == "'" && source.lookAhead("'''''")) {
							setState(wrapper("'''''", "'''''", 'wiki-bold-italic', lineEndState));
							return 'wiki-text';
						}
						if (ch == "'" && source.lookAhead("'''")) {
							setState(wrapper("'''", "'''", 'wiki-bold', lineEndState));
							return 'wiki-text';
						}
						if (ch == "'" && source.lookAhead("''")) {
							setState(wrapper("''", "''", 'wiki-italic', lineEndState));
							return 'wiki-text';
						}
					}
					prev = ch;
					next(source);
				}
				setState(lineEndState);
				return 'wiki-text';
			}
		}

		function tableCell() {
			return function(source, setState) {
				log("tableCell(" + source.peek() + ")");
				while (!source.endOfLine()) {
					var ch = source.peek();
					if (ch == '|') {
						setState(table);
						return 'wiki-text';
					}
					next(source);
				}
				return 'wiki-text';
			};
		}

		function table(source, setState) {
			log("table(" + source.peek() + ")");
			if (!source.endOfLine()) {
				var ch = next(source);
				if (ch == '|') {
					if (source.lookAhead('}')) {
						next(source);
						if (source.endOfLine()) {
							setState(begin);
						} else {
//							var test = function(ch) {return ch=='|' || ch=='!'};
//							setState(normalUntil(test,table,table));
							setState(normal());
						}
						return 'wiki-table';
					}
					return 'wiki-table';
				}
				return 'wiki-text';
				setState(tableCell());
			}
			return 'wiki-table';
		}

		function begin(source, setState) {
			log("begin(" + source.peek() + ")");

			if (source.indented) {
				while (!source.endOfLine())
					source.next();
				return "wiki-preformated";
			}

			var ch = source.peek();

			if (ch == '=') {
				if (ch == '=' && source.lookAhead('= ')) {
					setState(header(1));
					return null;
				}
				if (source.lookAhead('== ')) {
					setState(header(2));
					return null;
				}
				if (source.lookAhead('=== ')) {
					setState(header(3));
					return null;
				}
				if (source.lookAhead('==== ')) {
					setState(header(4));
					return null;
				}
			}

			if (ch == '<' && source.lookAhead('')) {
				setState(code);
				return null;
			}

			if ((ch == '*' && source.lookAhead('* ')) || (ch == '#' && source.lookAhead('# '))) {
				setState(list);
				return null;
			}

			if (ch == '{' && source.lookAhead('{|')) {
				next(source);
				setState(table);
				return null;
			}

			setState(normal())
			return null;
		}

		return function(source, startState) {
			run++;
			return tokenizer(source, startState || begin);
		};

	})();

	function indentWiki(inBraces, inRule, base) {
		return function(nextChars) {
			return base;
		};
	}

	function parseWiki(source, basecolumn) {
		basecolumn = basecolumn || 0;
		tokens = tokenizeWiki(source);

		var iter = {
			next : function() {
				var token = tokens.next();
				var style = token.style;
				var content = token.content;

				// console.log("content: "+content);

				if (content == '\n') {
					token.indentation = indentWiki(false, false, basecolumn);
				}

				return token;
			},

			copy : function() {
				var _tokenState = tokens.state;
				return function(source) {
					tokens = tokenizeWiki(source, _tokenState);
					return iter;
				};
			}
		};
		return iter;
	}

	return {
		make : parseWiki
	};
})();
<|endoftext|>


<commit_before>/* -*- mode: espresso; espresso-indent-level: 8; indent-tabs-mode: t -*- */
/**
 * project.js
 *
 * requirements:
 *	 tools.js
 *	 ui.js
 *	 request.js
 *
 */

/**
 */

/**
 * A TrakEM2 Web project.
 *
 * - contains abstract objects on top of a common project-specific semantic framework
 * - is related to one ore more stacks of statically aligned layers
 *   ( all stacks of a project are related by translation using physical dimensions )
 */
function Project( pid )
{
	this.getView = function()
	{
		return view;
	}

	/**
	 * add a stack to the project
	 */
	this.addStack = function( stack )
	{
		var opened = false;
		for ( var i = 0; i < stacks.length; ++i )
		{
			if ( stacks[ i ].id == stack.id )
			{
				stack = stacks[ i ];
				opened = true;
				break;
			}
		}
		if ( !opened )
		{
			stacks.push( stack );
			if ( rootWindow.getChild() == null )
				rootWindow.replaceChild( stack.getWindow() );
			else
				rootWindow.replaceChild( new CMWHSplitNode( rootWindow.getChild(), stack.getWindow() ) );

			stack.getWindow().focus();
			ui.onresize();
		}
		if ( stacks.length > 1 )
			self.moveTo( self.coordinates.z, self.coordinates.y, self.coordinates.x );
		else
		{
			var c = stack.projectCoordinates();
			self.moveTo( c.z, c.y, c.x );
		}

		// Only set focus if stack isn't already in focus
		if ( stack !== self.focusedStack )
		    self.setFocusedStack( stack );

		// only set the tool for the first stack
		if ( stacks.length == 1 )
		{
			if ( !tool )
				tool = new Navigator();
			self.setTool( tool );
			// self.focusedStack.setTool( tool );

		}

		return;
	}

	/**
	 * get one of the projects currently opened stacks
	 */
	this.getStack = function( sid )
	{
		for ( var i = 0; i < stacks.length; ++i )
		{
			if ( stacks[ i ].id == sid ) return stacks[ i ];
		}
		return false;
	}

	/**
	 * get all the currently opened stacks
	 */
	this.getStacks = function()
	{
		return stacks;
	}

	/**
	 * remove a stack from the list
	 */
	this.removeStack = function( sid )
	{
		for ( var i = 0; i < stacks.length; ++i )
		{
			if ( stacks[ i ].id == sid )
			{
				stacks.splice( i, 1 );
				if ( stacks.length == 0 )
					self.destroy();
				else
					stacks[ ( i + 1 ) % stacks.length ].getWindow().focus();
			}
		}
		ui.onresize();
		return;
	}

	/**
	 * focus a stack and blur the rest
	 */
	this.setFocusedStack = function( stack )
	{
		self.focusedStack = stack;
		if ( tool )
			self.focusedStack.setTool( tool );
		window.onresize();
		return;
	}

	/**
	 * focus the next or prior stack
	 */
	this.switchFocus = function( s )
	{
		var i;
		for ( i = 0; i < stacks.length; ++i )
			if ( self.focusedStack == stacks[ i ] ) break;

		stacks[ ( i + stacks.length + s ) % stacks.length ].getWindow().focus();
		return;
	}

	//!< Associative array of selected objects
	// in the Treenode Table and Object Tree.
	// I.e. enables communication between the Object Tree and the Table of Nodes.
	this.selectedObjects = {
		'tree_object': {},
		'table_treenode': {},
		'selectedneuron': null,
		'selectedskeleton': null,
        'selectedassembly': null
	};

    this.setSelectObject = function( type, id ) {
        this.selectedObjects.selectedneuron = null;
        this.selectedObjects.selectedskeleton = null;
        this.selectedObjects.selectedassembly = null;
        if( type == "neuron" ) {
            this.selectedObjects.selectedneuron = id;
        } else if( type == "skeleton" ) {
            this.selectedObjects.selectedskeleton = id;
        } else if( type == "assembly" ) {
            this.selectedObjects.selectedassembly = id;
        }
        // if the segmentation tool is select, we need to update
        // the assembly id
        if( self.getTool().toolname === 'segmentationtool' ) {
            SegmentationAnnotations.set_current_assembly_id( this.selectedObjects.selectedassembly );
        }

    };

    this.hideToolbars = function()
	{
		document.getElementById( "toolbar_nav" ).style.display = "none";
		document.getElementById( "toolbar_text" ).style.display = "none";
		document.getElementById( "toolbar_trace" ).style.display = "none";
	}

    this.hideToolboxes = function()
	{
		document.getElementById( "toolbox_segmentation" ).style.display = "none";
		document.getElementById( "toolbox_data" ).style.display = "none";
	}

	this.setTool = function( newTool )
	{
		if ( tool )
			tool.destroy();
		tool = newTool;

		self.hideToolboxes();
        if( self.getTool().toolname === 'segmentationtool' ) {
            document.getElementById( "toolbox_segmentation" ).style.display = "block";
        } else if( self.getTool().toolname === 'tracingtool' ) {
        	document.getElementById( "toolbox_data" ).style.display = "block";
        }

		if ( !self.focusedStack && stacks.length > 0 ) {
			self.setFocusedStack( stacks[ 0 ] )
		}

		self.focusedStack.setTool( tool )

		if ( self.focusedStack ) {
			if (!self.focusedStack.getWindow().hasFocus())
				self.focusedStack.getWindow().focus();
		}
		window.onresize();
		WindowMaker.setKeyShortcuts();
		return;
	}

	this.getTool = function( )
	{
		return tool;
	}

	this.toggleShow = function( m )
	{
		switch ( m )
		{
		case "text":
			if ( show_textlabels && mode != "text" )
			{
				show_textlabels = false;
				document.getElementById( "show_button_text" ).className = "button";
				for ( var i = 0; i < stacks.length; ++i )
					stacks[ i ].showTextlabels( false );
			}
			else
			{
				show_textlabels = true;
				for ( var i = 0; i < stacks.length; ++i )
					stacks[ i ].showTextlabels( true );
				document.getElementById( "show_button_text" ).className = "button_active";
			}
		}
		return;
	}

	/**
	 * register all GUI elements
	 */
	this.register = function()
	{
		document.getElementById( "content" ).style.display = "none";
		document.body.appendChild( view );
		ui.registerEvent( "onresize", resize );
		//window.onresize();

		document.onkeydown = onkeydown;

		return;
	}

	/**
	 * unregister and remove all stacks, free the event-handlers, hide the stack-toolbar
	 *
	 * @todo: should not the stack handle the navigation toolbar?
	 */
	this.destroy = function()
	{
		if ( tool ) tool.destroy();

		//! close all windows
		//rootWindow.closeAllChildren();
		rootWindow.close();

		ui.removeEvent( "onresize", resize );
		try
		{
			document.body.removeChild( view );
		}
		catch ( error ) {}
		self.id = 0;
		document.onkeydown = null;
		document.getElementById( "content" ).style.display = "block";
		document.getElementById( "project_menu_current" ).style.display = "none";
        // TODO: bars should be unset by tool on unregister
		document.getElementById("toolbox_edit").style.display = "none";
		document.getElementById("toolbox_data").style.display = "none";
		document.getElementById("toolbox_segmentation").style.display = "none";
        document.getElementById( "toolbox_project" ).style.display = "none";
        document.getElementById( "toolbar_nav" ).style.display = "none";

		project = null;

		return;
	}

	/**
	 * set the project to be editable or not
	 */
	this.setEditable = function(bool)
	{
		editable = bool;
		if (editable) {
			document.getElementById("toolbox_edit").style.display = "block";
			//document.getElementById("toolbox_data").style.display = "block";
			//document.getElementById("toolbox_segmentation").style.display = "block";
			document.getElementById("toolbox_data").style.display = "block";
		}
		else
		{
			document.getElementById("toolbox_edit").style.display = "none";
			//document.getElementById("toolbox_data").style.display = "none";
			//document.getElementById("toolbox_segmentation").style.display = "none";
			document.getElementById("toolbox_data").style.display = "none";
		}
		window.onresize();

		return;
	}

	this.moveToInStacks = function(
		zp,
		yp,
		xp,
		sp,
		stacks,
		completionCallback)
	{
		var stackToMove;
		if (stacks.length === 0) {
			// FIXME: do we need a callback for tool.redraw as well?
			if ( tool && tool.redraw )
				tool.redraw();
			if (typeof completionCallback !== "undefined") {
				completionCallback();
			}
		} else {
			stackToMove = stacks.shift();
			stackToMove.moveTo( zp,
					    yp,
					    xp,
					    sp,
					    function () {
						    self.moveToInStacks( zp, yp, xp, sp, stacks, completionCallback );
					    });
		}
	}

	/**
	 * move all stacks to the physical coordinates
	 */
	this.moveTo = function(
		zp,
		yp,
		xp,
		sp,
		completionCallback)
	{
		var stacksToMove = [];
		self.coordinates.x = xp;
		self.coordinates.y = yp;
		self.coordinates.z = zp;

		for ( var i = 0; i < stacks.length; ++i )
		{
			stacksToMove.push( stacks[ i ] );
		}

		self.moveToInStacks( zp, yp, xp, sp, stacksToMove, completionCallback );
	};

  this.updateTool = function()
  {
		if ( tool && tool.updateLayer )
			tool.updateLayer();
  };

  // Need to add this "tool-specific" function
  // to project because need to call it from the
  // object tree widget
  this.deselectActiveNode = function()
  {
		if ( tool && tool.deselectActiveNode )
			tool.deselectActiveNode();
  };

	/**
	 * create a URL to the current view
	 */
	this.createURL = function()
	{
		var coords;
		var url="?pid=" + self.id;
		if ( stacks.length > 0 )
		{
			//coords = stacks[ 0 ].projectCoordinates();		//!< @todo get this from the SELECTED stack to avoid approximation errors!
			url += "&zp=" + self.coordinates.z + "&yp=" + self.coordinates.y + "&xp=" + self.coordinates.x;
			url += "&tool=" + project.getTool().toolname;
      if( project.getTool().toolname === 'tracingtool' ) {
        var active_skeleton_id = SkeletonAnnotations.getActiveSkeletonId();
        if( active_skeleton_id ) {
          url += "&active_skeleton_id=" + active_skeleton_id;
          url += "&active_node_id=" + SkeletonAnnotations.getActiveNodeId();
        }
      }
			for ( var i = 0; i < stacks.length; ++i )
			{
				url += "&sid" + i + "=" + stacks[ i ].id + "&s" + i + "=" + stacks[ i ].s;
			}
		}
		return url;
	}

	/** This function should return true if there was any action
		linked to the key code, or false otherwise. */

	this.handleKeyPress = function( e ) {
		var keyAction = keyCodeToAction[e.keyCode];
		if (keyAction) {
			return keyAction.run(e);
		} else {
			return false;
		}
	}

	var onkeydown = function( e )
	{
		var projectKeyPress;
		var key;
		var shift;
		var alt;
		var ctrl;
		var keyAction;

		/* The code here used to modify 'e' and pass it
		   on, but Firefox no longer allows this.  So, create
		   a fake event object instead, and pass that down. */
		var fakeEvent = {};

		if ( e )
		{
			if ( e.keyCode ) {
				key = e.keyCode;
			} else if ( e.charCode ) {
				key = e.charCode;
			} else {
				key = e.which;
			}
			fakeEvent.keyCode = key;
			fakeEvent.shiftKey = e.shiftKey;
			fakeEvent.altKey = e.altKey;
			fakeEvent.ctrlKey = e.ctrlKey;
			shift = e.shiftKey;
			alt = e.altKey;
			ctrl = e.ctrlKey;
		}
		else if ( event && event.keyCode )
		{
			fakeEvent.keyCode = event.keyCode;
			fakeEvent.shiftKey = event.shiftKey;
			fakeEvent.altKey = event.altKey;
			fakeEvent.ctrlKey = event.ctrlKey;
			shift = event.shiftKey;
			alt = event.altKey;
			ctrl = event.ctrlKey;
		}
		fakeEvent.target = UI.getTargetElement(e || event);
		var n = fakeEvent.target.nodeName.toLowerCase();
		var fromATextField = false;
		if (n == "input") {
			var inputType = fakeEvent.target.type.toLowerCase();
			if (inputType == "text" || inputType == "password") {
				fromATextField = true;
			}
		}
		if (!(fromATextField || n == "textarea" || n == "area")) //!< @todo exclude all useful keyboard input elements e.g. contenteditable...
		{
			/* Note that there are two different
			   conventions for return values here: the
			   handleKeyPress() methods return true if the
			   event has been dealt with (i.e. it should
			   not be propagated) but the onkeydown
			   function should only return true if the
			   event should carry on for default
			   processing. */
			if (tool && tool.handleKeyPress(fakeEvent)) {
				return false;
			} else {
				projectKeyPress = self.handleKeyPress(fakeEvent);
				return ! projectKeyPress;
			}
		} else {
			return true;
		}
	}

	/**
	 * Get project ID.
	 */
	this.getId = function(){ return pid; }

	// initialise
	var self = this;
	this.id = pid;
	if ( typeof ui == "undefined" ) ui = new UI();
	if ( typeof requestQueue == "undefined" ) requestQueue = new RequestQueue();

	var tool = null;

	var view = rootWindow.getFrame();
	view.className = "projectView";

	this.coordinates =
	{
		x : 0,
		y : 0,
		z : 0
	};

	var template;				//!< DTD like abstract object tree (classes)
	var data;					//!< instances in a DOM representation

	var stacks = new Array();	//!< a list of stacks related to the project
	this.focusedStack;

	var editable = false;
	var mode = "move";
	var show_textlabels = true;

	var icon_text_apply = document.getElementById( "icon_text_apply" );

	/** The only actions that should be added to Project are those
	    that should be run regardless of the current tool, such as
	    actions that switch tools. */

	var actions = toolActions.concat(editToolActions);

	this.getActions = function () {
		return actions;
	}

	var keyCodeToAction = getKeyCodeToActionMap(actions);
}
<commit_msg>Return the actually used stack after added a stack to a project<commit_after>/* -*- mode: espresso; espresso-indent-level: 8; indent-tabs-mode: t -*- */
/**
 * project.js
 *
 * requirements:
 *	 tools.js
 *	 ui.js
 *	 request.js
 *
 */

/**
 */

/**
 * A TrakEM2 Web project.
 *
 * - contains abstract objects on top of a common project-specific semantic framework
 * - is related to one ore more stacks of statically aligned layers
 *   ( all stacks of a project are related by translation using physical dimensions )
 */
function Project( pid )
{
	this.getView = function()
	{
		return view;
	}

	/**
	 * Add a stack to the project. The stack reference is returned. In
	 * case a stack with the same ID is already loaded, a reference to
	 * this existing stack is returned.
	 */
	this.addStack = function( stack )
	{
		var opened = false;
		for ( var i = 0; i < stacks.length; ++i )
		{
			if ( stacks[ i ].id == stack.id )
			{
				stack = stacks[ i ];
				opened = true;
				break;
			}
		}
		if ( !opened )
		{
			stacks.push( stack );
			if ( rootWindow.getChild() == null )
				rootWindow.replaceChild( stack.getWindow() );
			else
				rootWindow.replaceChild( new CMWHSplitNode( rootWindow.getChild(), stack.getWindow() ) );

			stack.getWindow().focus();
			ui.onresize();
		}
		if ( stacks.length > 1 )
			self.moveTo( self.coordinates.z, self.coordinates.y, self.coordinates.x );
		else
		{
			var c = stack.projectCoordinates();
			self.moveTo( c.z, c.y, c.x );
		}

		// Only set focus if stack isn't already in focus
		if ( stack !== self.focusedStack )
		    self.setFocusedStack( stack );

		// only set the tool for the first stack
		if ( stacks.length == 1 )
		{
			if ( !tool )
				tool = new Navigator();
			self.setTool( tool );
			// self.focusedStack.setTool( tool );

		}

		// return the (possibly updated) stack reference
		return stack;
	}

	/**
	 * get one of the projects currently opened stacks
	 */
	this.getStack = function( sid )
	{
		for ( var i = 0; i < stacks.length; ++i )
		{
			if ( stacks[ i ].id == sid ) return stacks[ i ];
		}
		return false;
	}

	/**
	 * get all the currently opened stacks
	 */
	this.getStacks = function()
	{
		return stacks;
	}

	/**
	 * remove a stack from the list
	 */
	this.removeStack = function( sid )
	{
		for ( var i = 0; i < stacks.length; ++i )
		{
			if ( stacks[ i ].id == sid )
			{
				stacks.splice( i, 1 );
				if ( stacks.length == 0 )
					self.destroy();
				else
					stacks[ ( i + 1 ) % stacks.length ].getWindow().focus();
			}
		}
		ui.onresize();
		return;
	}

	/**
	 * focus a stack and blur the rest
	 */
	this.setFocusedStack = function( stack )
	{
		self.focusedStack = stack;
		if ( tool )
			self.focusedStack.setTool( tool );
		window.onresize();
		return;
	}

	/**
	 * focus the next or prior stack
	 */
	this.switchFocus = function( s )
	{
		var i;
		for ( i = 0; i < stacks.length; ++i )
			if ( self.focusedStack == stacks[ i ] ) break;

		stacks[ ( i + stacks.length + s ) % stacks.length ].getWindow().focus();
		return;
	}

	//!< Associative array of selected objects
	// in the Treenode Table and Object Tree.
	// I.e. enables communication between the Object Tree and the Table of Nodes.
	this.selectedObjects = {
		'tree_object': {},
		'table_treenode': {},
		'selectedneuron': null,
		'selectedskeleton': null,
        'selectedassembly': null
	};

    this.setSelectObject = function( type, id ) {
        this.selectedObjects.selectedneuron = null;
        this.selectedObjects.selectedskeleton = null;
        this.selectedObjects.selectedassembly = null;
        if( type == "neuron" ) {
            this.selectedObjects.selectedneuron = id;
        } else if( type == "skeleton" ) {
            this.selectedObjects.selectedskeleton = id;
        } else if( type == "assembly" ) {
            this.selectedObjects.selectedassembly = id;
        }
        // if the segmentation tool is select, we need to update
        // the assembly id
        if( self.getTool().toolname === 'segmentationtool' ) {
            SegmentationAnnotations.set_current_assembly_id( this.selectedObjects.selectedassembly );
        }

    };

    this.hideToolbars = function()
	{
		document.getElementById( "toolbar_nav" ).style.display = "none";
		document.getElementById( "toolbar_text" ).style.display = "none";
		document.getElementById( "toolbar_trace" ).style.display = "none";
	}

    this.hideToolboxes = function()
	{
		document.getElementById( "toolbox_segmentation" ).style.display = "none";
		document.getElementById( "toolbox_data" ).style.display = "none";
	}

	this.setTool = function( newTool )
	{
		if ( tool )
			tool.destroy();
		tool = newTool;

		self.hideToolboxes();
        if( self.getTool().toolname === 'segmentationtool' ) {
            document.getElementById( "toolbox_segmentation" ).style.display = "block";
        } else if( self.getTool().toolname === 'tracingtool' ) {
        	document.getElementById( "toolbox_data" ).style.display = "block";
        }

		if ( !self.focusedStack && stacks.length > 0 ) {
			self.setFocusedStack( stacks[ 0 ] )
		}

		self.focusedStack.setTool( tool )

		if ( self.focusedStack ) {
			if (!self.focusedStack.getWindow().hasFocus())
				self.focusedStack.getWindow().focus();
		}
		window.onresize();
		WindowMaker.setKeyShortcuts();
		return;
	}

	this.getTool = function( )
	{
		return tool;
	}

	this.toggleShow = function( m )
	{
		switch ( m )
		{
		case "text":
			if ( show_textlabels && mode != "text" )
			{
				show_textlabels = false;
				document.getElementById( "show_button_text" ).className = "button";
				for ( var i = 0; i < stacks.length; ++i )
					stacks[ i ].showTextlabels( false );
			}
			else
			{
				show_textlabels = true;
				for ( var i = 0; i < stacks.length; ++i )
					stacks[ i ].showTextlabels( true );
				document.getElementById( "show_button_text" ).className = "button_active";
			}
		}
		return;
	}

	/**
	 * register all GUI elements
	 */
	this.register = function()
	{
		document.getElementById( "content" ).style.display = "none";
		document.body.appendChild( view );
		ui.registerEvent( "onresize", resize );
		//window.onresize();

		document.onkeydown = onkeydown;

		return;
	}

	/**
	 * unregister and remove all stacks, free the event-handlers, hide the stack-toolbar
	 *
	 * @todo: should not the stack handle the navigation toolbar?
	 */
	this.destroy = function()
	{
		if ( tool ) tool.destroy();

		//! close all windows
		//rootWindow.closeAllChildren();
		rootWindow.close();

		ui.removeEvent( "onresize", resize );
		try
		{
			document.body.removeChild( view );
		}
		catch ( error ) {}
		self.id = 0;
		document.onkeydown = null;
		document.getElementById( "content" ).style.display = "block";
		document.getElementById( "project_menu_current" ).style.display = "none";
        // TODO: bars should be unset by tool on unregister
		document.getElementById("toolbox_edit").style.display = "none";
		document.getElementById("toolbox_data").style.display = "none";
		document.getElementById("toolbox_segmentation").style.display = "none";
        document.getElementById( "toolbox_project" ).style.display = "none";
        document.getElementById( "toolbar_nav" ).style.display = "none";

		project = null;

		return;
	}

	/**
	 * set the project to be editable or not
	 */
	this.setEditable = function(bool)
	{
		editable = bool;
		if (editable) {
			document.getElementById("toolbox_edit").style.display = "block";
			//document.getElementById("toolbox_data").style.display = "block";
			//document.getElementById("toolbox_segmentation").style.display = "block";
			document.getElementById("toolbox_data").style.display = "block";
		}
		else
		{
			document.getElementById("toolbox_edit").style.display = "none";
			//document.getElementById("toolbox_data").style.display = "none";
			//document.getElementById("toolbox_segmentation").style.display = "none";
			document.getElementById("toolbox_data").style.display = "none";
		}
		window.onresize();

		return;
	}

	this.moveToInStacks = function(
		zp,
		yp,
		xp,
		sp,
		stacks,
		completionCallback)
	{
		var stackToMove;
		if (stacks.length === 0) {
			// FIXME: do we need a callback for tool.redraw as well?
			if ( tool && tool.redraw )
				tool.redraw();
			if (typeof completionCallback !== "undefined") {
				completionCallback();
			}
		} else {
			stackToMove = stacks.shift();
			stackToMove.moveTo( zp,
					    yp,
					    xp,
					    sp,
					    function () {
						    self.moveToInStacks( zp, yp, xp, sp, stacks, completionCallback );
					    });
		}
	}

	/**
	 * move all stacks to the physical coordinates
	 */
	this.moveTo = function(
		zp,
		yp,
		xp,
		sp,
		completionCallback)
	{
		var stacksToMove = [];
		self.coordinates.x = xp;
		self.coordinates.y = yp;
		self.coordinates.z = zp;

		for ( var i = 0; i < stacks.length; ++i )
		{
			stacksToMove.push( stacks[ i ] );
		}

		self.moveToInStacks( zp, yp, xp, sp, stacksToMove, completionCallback );
	};

  this.updateTool = function()
  {
		if ( tool && tool.updateLayer )
			tool.updateLayer();
  };

  // Need to add this "tool-specific" function
  // to project because need to call it from the
  // object tree widget
  this.deselectActiveNode = function()
  {
		if ( tool && tool.deselectActiveNode )
			tool.deselectActiveNode();
  };

	/**
	 * create a URL to the current view
	 */
	this.createURL = function()
	{
		var coords;
		var url="?pid=" + self.id;
		if ( stacks.length > 0 )
		{
			//coords = stacks[ 0 ].projectCoordinates();		//!< @todo get this from the SELECTED stack to avoid approximation errors!
			url += "&zp=" + self.coordinates.z + "&yp=" + self.coordinates.y + "&xp=" + self.coordinates.x;
			url += "&tool=" + project.getTool().toolname;
      if( project.getTool().toolname === 'tracingtool' ) {
        var active_skeleton_id = SkeletonAnnotations.getActiveSkeletonId();
        if( active_skeleton_id ) {
          url += "&active_skeleton_id=" + active_skeleton_id;
          url += "&active_node_id=" + SkeletonAnnotations.getActiveNodeId();
        }
      }
			for ( var i = 0; i < stacks.length; ++i )
			{
				url += "&sid" + i + "=" + stacks[ i ].id + "&s" + i + "=" + stacks[ i ].s;
			}
		}
		return url;
	}

	/** This function should return true if there was any action
		linked to the key code, or false otherwise. */

	this.handleKeyPress = function( e ) {
		var keyAction = keyCodeToAction[e.keyCode];
		if (keyAction) {
			return keyAction.run(e);
		} else {
			return false;
		}
	}

	var onkeydown = function( e )
	{
		var projectKeyPress;
		var key;
		var shift;
		var alt;
		var ctrl;
		var keyAction;

		/* The code here used to modify 'e' and pass it
		   on, but Firefox no longer allows this.  So, create
		   a fake event object instead, and pass that down. */
		var fakeEvent = {};

		if ( e )
		{
			if ( e.keyCode ) {
				key = e.keyCode;
			} else if ( e.charCode ) {
				key = e.charCode;
			} else {
				key = e.which;
			}
			fakeEvent.keyCode = key;
			fakeEvent.shiftKey = e.shiftKey;
			fakeEvent.altKey = e.altKey;
			fakeEvent.ctrlKey = e.ctrlKey;
			shift = e.shiftKey;
			alt = e.altKey;
			ctrl = e.ctrlKey;
		}
		else if ( event && event.keyCode )
		{
			fakeEvent.keyCode = event.keyCode;
			fakeEvent.shiftKey = event.shiftKey;
			fakeEvent.altKey = event.altKey;
			fakeEvent.ctrlKey = event.ctrlKey;
			shift = event.shiftKey;
			alt = event.altKey;
			ctrl = event.ctrlKey;
		}
		fakeEvent.target = UI.getTargetElement(e || event);
		var n = fakeEvent.target.nodeName.toLowerCase();
		var fromATextField = false;
		if (n == "input") {
			var inputType = fakeEvent.target.type.toLowerCase();
			if (inputType == "text" || inputType == "password") {
				fromATextField = true;
			}
		}
		if (!(fromATextField || n == "textarea" || n == "area")) //!< @todo exclude all useful keyboard input elements e.g. contenteditable...
		{
			/* Note that there are two different
			   conventions for return values here: the
			   handleKeyPress() methods return true if the
			   event has been dealt with (i.e. it should
			   not be propagated) but the onkeydown
			   function should only return true if the
			   event should carry on for default
			   processing. */
			if (tool && tool.handleKeyPress(fakeEvent)) {
				return false;
			} else {
				projectKeyPress = self.handleKeyPress(fakeEvent);
				return ! projectKeyPress;
			}
		} else {
			return true;
		}
	}

	/**
	 * Get project ID.
	 */
	this.getId = function(){ return pid; }

	// initialise
	var self = this;
	this.id = pid;
	if ( typeof ui == "undefined" ) ui = new UI();
	if ( typeof requestQueue == "undefined" ) requestQueue = new RequestQueue();

	var tool = null;

	var view = rootWindow.getFrame();
	view.className = "projectView";

	this.coordinates =
	{
		x : 0,
		y : 0,
		z : 0
	};

	var template;				//!< DTD like abstract object tree (classes)
	var data;					//!< instances in a DOM representation

	var stacks = new Array();	//!< a list of stacks related to the project
	this.focusedStack;

	var editable = false;
	var mode = "move";
	var show_textlabels = true;

	var icon_text_apply = document.getElementById( "icon_text_apply" );

	/** The only actions that should be added to Project are those
	    that should be run regardless of the current tool, such as
	    actions that switch tools. */

	var actions = toolActions.concat(editToolActions);

	this.getActions = function () {
		return actions;
	}

	var keyCodeToAction = getKeyCodeToActionMap(actions);
}
<|endoftext|>


<commit_before>// Show / apply seeds
//

"use strict";

// stdlib
var path  = require('path');
var fs    = require('fs');

// 3rd-party
var async   = require("async");
var fstools = require("fs-tools");

////////////////////////////////////////////////////////////////////////////////

var SEEDS_DIR = 'db/seeds';

////////////////////////////////////////////////////////////////////////////////

function seed_run(N, app_name, seed_path, callback) {
  console.log('Applying seed...\n');

  require(seed_path)(N, function (err) {
    var prefix = '  ' + app_name + ':' + path.basename(seed_path) + ' -- ';

    if (err) {
      console.log(prefix + 'failed');
      callback(err);
      return;
    }

    console.log(prefix + 'success');
    process.exit(0);
  });
}

module.exports.parserParameters = {
  addHelp: true,
  description: 'That will run `.<app_name>/db/seeds/<seed_name>.js` if exists. ' +
    'Or, all seeds from `./db/seeds/seed-name/` folder. If <seed-name>' +
    'missed, then script will show all available seeds for given app. ' +
    'If `-a` missed, then all seed for all apps will be shown.',
  epilog : 'Note: Loading seeds is limited to development/test enviroment. ' +
    'If you really need to run seed  on production/stageing, use ' +
    'option -f.',
  help: 'show or run existing seeds'
};

module.exports.commandLineArguments = [
  {
    args: ['-f'],
    options: {
      help: 'force run without env checking',
      action: 'storeTrue'
    }
  },
  {
    args: ['-a', '--app'],
    options: {
      help: 'application name',
      type: 'string'
    }
  },
  {
    args: ['-n'],
    options: {
      metavar: 'SEED_NUMBER',
      dest: 'number',
      help: 'run seed by number',
      type: 'int'
    }
  },
  {
    args: ['seed'],
    options: {
      metavar: 'SEED_NAME',
      help: 'seed name',
      nargs: '?',
      defaultValue: null
    }
  },
];

module.exports.run = function (N, args, callback) {
  var app_name = args.app;
  var seed_name = args.seed;
  var seed_pos =  args.number ? args.number - 1 : -1;

  function get_app_path(app_name) {
    for (var i = 0; i < N.runtime.apps.length; i++) {
      if (app_name === N.runtime.apps[i].name) {
        return N.runtime.apps[i].root;
      }
    }
    return null;
  }

  N.wire.emit([
      'init:models'
    ], N,

    function (err) {
      if (err) {
        callback(err);
        return;
      }

      // execute seed by name
      if (!!app_name && !!seed_name) {
        var env = N.runtime.env;
        if ('development' !== env && 'testing' !== env && !args.force) {
          console.log('Error: Can\'t run seed from ' + env + ' enviroment. Please, use -f to force.');
          process.exit(1);
        }

        var seed_path = path.join(get_app_path(app_name), SEEDS_DIR, seed_name);
        if (!fs.existsSync(seed_path)) {
          console.log('Error: Application "' + app_name + '"does not have "' + seed_name);
          process.exit(1);
        }

        seed_run(N, app_name, seed_path, callback);
      }
      else {
        var apps;
        if (app_name) {
          apps = [{name: app_name, root: get_app_path(app_name)}];
        }
        else {
          apps = N.runtime.apps;
        }

        // collect seeds
        var seed_list = [];
        async.forEachSeries(apps, function (app, next_app) {
          var seed_dir = path.join(app.root, SEEDS_DIR);
          fstools.walk(seed_dir, /\.js$/, function (file, stats, next_file) {
            // skip files when
            // - filename starts with _, e.g.: /foo/bar/_baz.js
            // - dirname in path starts _, e.g. /foo/_bar/baz.js
            if (file.match(/(^|\/|\\)_/)) {
              next_file();
              return;
            }

            seed_list.push({
              name: app.name,
              seed_path: file
            });
            next_file();
          }, next_app);
        }, function (err) {
          if (err) {
            callback(err);
            return;
          }

          if (!!args.number && seed_list[seed_pos]) {
            // execute seed by number
            seed_run(N, seed_list[seed_pos].name, seed_list[seed_pos].seed_path, callback);
          } else {
            // display seed list
            if (!!args.number) {
              console.log(args.number + ' seed not found\n');
            }

            console.log('Available seeds:\n');

            for (var i = 0; i < seed_list.length; i++) {
              console.log('  ' + (i + 1) + '. ' + seed_list[i].name + ': ' + path.basename(seed_list[i].seed_path));
            }

            console.log('\nSeeds are shown in `<APP>: <SEED_NAME>` form.');
            console.log('See `seed --help` for details');
            process.exit(0);
          }
        });
      }
    }
  );
};
<commit_msg>typo fix<commit_after>// Show / apply seeds
//

"use strict";

// stdlib
var path  = require('path');
var fs    = require('fs');

// 3rd-party
var async   = require("async");
var fstools = require("fs-tools");

////////////////////////////////////////////////////////////////////////////////

var SEEDS_DIR = 'db/seeds';

////////////////////////////////////////////////////////////////////////////////

function seed_run(N, app_name, seed_path, callback) {
  console.log('Applying seed...\n');

  require(seed_path)(N, function (err) {
    var prefix = '  ' + app_name + ':' + path.basename(seed_path) + ' -- ';

    if (err) {
      console.log(prefix + 'failed');
      callback(err);
      return;
    }

    console.log(prefix + 'success');
    process.exit(0);
  });
}

module.exports.parserParameters = {
  addHelp: true,
  description: 'That will run `.<app_name>/db/seeds/<seed_name>.js` if exists. ' +
    'Or, all seeds from `./db/seeds/seed-name/` folder. If <seed-name>' +
    'missed, then script will show all available seeds for given app. ' +
    'If `-a` missed, then all seed for all apps will be shown.',
  epilog : 'Note: Loading seeds is limited to development/test enviroment. ' +
    'If you really need to run seed  on production/stageing, use ' +
    'option -f.',
  help: 'show or run existing seeds'
};

module.exports.commandLineArguments = [
  {
    args: ['-f'],
    options: {
      help: 'force run without env checking',
      action: 'storeTrue'
    }
  },
  {
    args: ['-a', '--app'],
    options: {
      help: 'application name',
      type: 'string'
    }
  },
  {
    args: ['-n'],
    options: {
      metavar: 'SEED_NUMBER',
      dest: 'number',
      help: 'run seed by number',
      type: 'int'
    }
  },
  {
    args: ['seed'],
    options: {
      metavar: 'SEED_NAME',
      help: 'seed name',
      nargs: '?',
      defaultValue: null
    }
  }
];

module.exports.run = function (N, args, callback) {
  var app_name = args.app;
  var seed_name = args.seed;
  var seed_pos =  args.number ? args.number - 1 : -1;

  function get_app_path(app_name) {
    for (var i = 0; i < N.runtime.apps.length; i++) {
      if (app_name === N.runtime.apps[i].name) {
        return N.runtime.apps[i].root;
      }
    }
    return null;
  }

  N.wire.emit([
      'init:models'
    ], N,

    function (err) {
      if (err) {
        callback(err);
        return;
      }

      // execute seed by name
      if (!!app_name && !!seed_name) {
        var env = N.runtime.env;
        if ('development' !== env && 'testing' !== env && !args.force) {
          console.log('Error: Can\'t run seed from ' + env + ' enviroment. Please, use -f to force.');
          process.exit(1);
        }

        var seed_path = path.join(get_app_path(app_name), SEEDS_DIR, seed_name);
        if (!fs.existsSync(seed_path)) {
          console.log('Error: Application "' + app_name + '"does not have "' + seed_name);
          process.exit(1);
        }

        seed_run(N, app_name, seed_path, callback);
      }
      else {
        var apps;
        if (app_name) {
          apps = [{name: app_name, root: get_app_path(app_name)}];
        }
        else {
          apps = N.runtime.apps;
        }

        // collect seeds
        var seed_list = [];
        async.forEachSeries(apps, function (app, next_app) {
          var seed_dir = path.join(app.root, SEEDS_DIR);
          fstools.walk(seed_dir, /\.js$/, function (file, stats, next_file) {
            // skip files when
            // - filename starts with _, e.g.: /foo/bar/_baz.js
            // - dirname in path starts _, e.g. /foo/_bar/baz.js
            if (file.match(/(^|\/|\\)_/)) {
              next_file();
              return;
            }

            seed_list.push({
              name: app.name,
              seed_path: file
            });
            next_file();
          }, next_app);
        }, function (err) {
          if (err) {
            callback(err);
            return;
          }

          if (!!args.number && seed_list[seed_pos]) {
            // execute seed by number
            seed_run(N, seed_list[seed_pos].name, seed_list[seed_pos].seed_path, callback);
          } else {
            // display seed list
            if (!!args.number) {
              console.log(args.number + ' seed not found\n');
            }

            console.log('Available seeds:\n');

            for (var i = 0; i < seed_list.length; i++) {
              console.log('  ' + (i + 1) + '. ' + seed_list[i].name + ': ' + path.basename(seed_list[i].seed_path));
            }

            console.log('\nSeeds are shown in `<APP>: <SEED_NAME>` form.');
            console.log('See `seed --help` for details');
            process.exit(0);
          }
        });
      }
    }
  );
};
<|endoftext|>