code
stringlengths 2
1.05M
|
---|
exports.commands = {
'c8': 'crazyeights',
crazyeights: function(arg, by, room) {
if (room.charAt(0) === ',') return false;
if (!crazyeight.gameStatus[room]) {
crazyeight.gameStatus[room] = 'off';
}
if (!arg) {
return false;
}
else {
arg = toId(arg);
}
switch (arg) {
case 'new':
if (!Bot.canUse('crazyeights', room, by)) return false;
if (crazyeight.gameStatus[room] !== 'off') return Bot.say(by, room, 'A crazyeights game is already going on!');
if (checkGame(room)) return Bot.say(by, room, 'There is already a game going on in this room!');
Bot.say(by, room, 'A new game of Crazy Eights is starting. Do +crazyeights join to join the game!');
Bot.say(config.nick, room, 'The goal is to be the first player to get rid of all your cards. A [ 2] will cause the next player to draw 2 cards and lose their turn.');
Bot.say(config.nick, room, 'A [ J] will skip the next player\'s turn and a [♠Q] will make the next player forfeit his/her turn and draw 4 cards. An [ 8] will allow the player to change the suit.');
Bot.say(config.nick, room, 'You can play a card with either the same suit or number/letter. The goal is to get rid of your cards before the other players do so.');
Bot.say(config.nick, room, 'You only need to say first letter of the suit + value to play your card. Ex. ' + config.commandcharacter[0] + 'play sQ would be playing the Queen of Spades.');
game('crazyeights', room);
crazyeight.gameStatus[room] = 'signups';
crazyeight.playerData[room] = {};
crazyeight.playerList[room] = [];
crazyeight.currentPlayer[room] = '';
break;
case 'join':
if (crazyeight.gameStatus[room] !== 'signups') return false;
if (crazyeight.playerData[room][toId(by)]) return Bot.say(by, room, 'You\'ve already signed up!');
Bot.say(by, ',' + by, '(' + room + ') Thank you for joining!');
crazyeight.playerData[room][toId(by)] = {
name: by.slice(1),
hand: [],
disqualified: false,
};
crazyeight.playerList[room][crazyeight.playerList[room].length] = toId(by);
break;
case 'leave':
if (crazyeight.gameStatus[room] !== 'signups') return false;
var pIndex = crazyeight.playerList[room].indexOf(toId(by));
if (pIndex < 0) return false;
var pushPlayer = [];
for (var x = 0; x < crazyeight.playerList[room].length; x++) {
if (x === pIndex) {
continue;
}
pushPlayer.push(crazyeight.playerList[room][x]);
}
//reset playerlist
crazyeight.playerList[room] = pushPlayer;
delete crazyeight.playerData[room][toId(by)];
break;
case 'end':
if (!Bot.canUse('crazyeights', room, by)) return false;
if (gameStatus === 'off') return false;
clearInterval(crazyeight.interval[room]);
crazyeight.gameStatus[room] = 'off';
Bot.say(by, room, 'The game was forcibly ended.');
break;
case 'start':
if (!Bot.canUse('crazyeights', room, by)) return false;
if (crazyeight.gameStatus[room] !== 'signups') return false;
if (crazyeight.playerList[room].length < 2) return Bot.say(by, room, 'There aren\'t enough players ;-;');
crazyeight.gameStatus[room] = 'on';
crazyeight.deck[room] = Tools.generateDeck(1);
Bot.say(by, room, 'Use ' + config.commandcharacter[0] + 'play [card] to play a card. c for clubs, h for hearts, s for spades and, d for diamonds. When playing a [ 8], be sure to include what you\'re changing to (' + config.commandcharacter[0] + 'play c8 s)');
//deal the cards
for (var j = 0; j < 7; j++) {
for (var i = 0; i < crazyeight.playerList[room].length; i++) {
var tarPlayer = crazyeight.playerList[room][i];
crazyeight.playerData[room][tarPlayer].hand[crazyeight.playerData[room][tarPlayer].hand.length] = crazyeight.deck[room][0];
crazyeight.deck[room] = crazyeight.deck[room].slice(1);
if (crazyeight.deck[room].length === 0) {
crazyeight.deck[room] = Tools.generateDeck(1);
}
}
}
// Determine/initialize topCard
crazyeight.topCard[room] = crazyeight.deck[room][0];
crazyeight.deck[room] = crazyeight.deck[room].slice(1);
Bot.talk(room, '**Top Card: [' + crazyeight.topCard[room] + ']**');
//new deck if all used up
if (crazyeight.deck[room].length === 0) {
crazyeight.deck[room] = Tools.generateDeck(1);
}
//start the turns
//init first player
crazyeight.currentPlayer[room] = crazyeight.playerList[room][0];
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
Bot.talk(room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn! __(' + config.commandcharacter[0] + 'play [card] or ' + config.commandcharacter[0] + 'draw)__');
crazyeight.interval[room] = setInterval(function() {
if (crazyeight.gameStatus[room] !== 'on') {
clearInterval(crazyeight.interval[room]);
return false;
}
//disqualify for inactivity
crazyeight.playerData[room][crazyeight.currentPlayer[room]].disqualified = true;
//re-make playerlist
var pIndex = crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]);
var pushPlayer = [];
for (var x = 0; x < crazyeight.playerList[room].length; x++) {
if (x === pIndex) {
continue;
}
pushPlayer.push(crazyeight.playerList[room][x]);
}
//reset playerlist
crazyeight.playerList[room] = pushPlayer;
//checking if all players are DQ'd
if (crazyeight.playerList[room].length === 0) {
Bot.say(config.nick, room, 'Nobody wins this game :(');
}
else if (crazyeight.playerList[room].length === 1) {
Bot.say(config.nick, room, crazyeight.playerData[room][crazyeight.playerList[room][0]].name + ' wins!');
Bot.say(config.nick, room, 'Rewards: ' + Economy.getPayout(crazyeight.playerList[room].length, room) + ' ' + Economy.currency(room));
Economy.give(crazyeight.playerData[room][crazyeight.playerList[room][0]].name, Economy.getPayout(crazyeight.playerList[room].length, room), room);
}
if (crazyeight.playerList[room].length < 2) {
clearInterval(crazyeight.interval[room]);
crazyeight.gameStatus[room] = 'off';
return false;
}
//change to next player
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
//pming next user their hand
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
Bot.talk(room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn! __(' + config.commandcharacter[0] + 'play [card] or ' + config.commandcharacter[0] + 'draw)__');
Bot.talk(room, '**Top Card: [' + crazyeight.topCard[room] + ']**');
}, 90000);
}
},
play: function(arg, by, room) {
if (toId(by) !== crazyeight.currentPlayer[room] || !crazyeight.gameStatus[room] || crazyeight.gameStatus[room] !== 'on') return false;
var suitList = ['♥', '♣', '♦', '♠'];
var valueList = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
arg = arg.split(' ');
if (arg[1]) {
var modifier = arg[1].slice(0, 1).toLowerCase().replace('c', '♣').replace('h', '♥').replace('d', '♦').replace('s', '♠');
}
else {
modifier = '';
}
var suit = arg[0].slice(0, 1).toLowerCase().replace('c', '♣').replace('h', '♥').replace('d', '♦').replace('s', '♠');
var value = arg[0].slice(1).toUpperCase();
if (suitList.indexOf(suit) === -1 || valueList.indexOf(value) === -1) return Bot.say(by, ',' + by, 'To play a card use the first letter of the card\'s suit + the value of the card. (ex. ' + config.commandcharacter[0] + 'play cK would be [♣K])');
var card = suit + value;
if (crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.indexOf(card) === -1) {
return Bot.say(by, room, 'You don\'t have this card!');
}
if (crazyeight.topCard[room].slice(1) !== value && crazyeight.topCard[room][0] !== suit && value !== '8') {
return Bot.say(by, room, 'You can\'t play this card now.');
}
if (value === '8' && !modifier) {
return Bot.say(by, room, 'Please choose what suit to change to. Ex. ' + config.commandcharacter[0] + 'play c8 s');
}
if (modifier) {
if (suitList.indexOf(modifier) === -1) {
return Bot.say(by, room, 'Not a correct suit.');
}
}
clearInterval(crazyeight.interval[room]);
//new top card
crazyeight.topCard[room] = card;
Bot.talk(room, '**Top Card: [' + crazyeight.topCard[room] + ']**');
//remove card from hand
//determine position of the one card
var idx = crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.indexOf(card);
var newHand = [];
for (var i = 0; i < crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.length; i++) {
if (i === idx) {
continue;
}
newHand.push(crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand[i]);
}
crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand = newHand;
if (crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.length === 1) {
Bot.say(config.nick, room, 'Last Card!');
}
//special effects;
switch (value) {
case '8':
crazyeight.topCard[room] = modifier + value;
Bot.talk(room, 'Suit is changed to: ' + modifier);
break;
case '2':
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
//for loop - draw 2
var tarPlayer = crazyeight.currentPlayer[room];
for (var y = 0; y < 2; y++) {
crazyeight.playerData[room][tarPlayer].hand[crazyeight.playerData[room][tarPlayer].hand.length] = crazyeight.deck[room][0];
crazyeight.deck[room] = crazyeight.deck[room].slice(1);
if (crazyeight.deck[room].length === 0) {
crazyeight.deck[room] = Tools.generateDeck(1);
}
}
Bot.say(config.nick, room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn has been skipped and is forced to draw 2 cards!');
break;
case 'J':
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
Bot.say(config.nick, room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn has been skipped!');
break;
}
if (crazyeight.topCard[room] === '♠Q') {
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
//for loop - draw 4
tarPlayer = crazyeight.currentPlayer[room];
for (var y = 0; y < 4; y++) {
crazyeight.playerData[room][tarPlayer].hand[crazyeight.playerData[room][tarPlayer].hand.length] = crazyeight.deck[room][0];
crazyeight.deck[room] = crazyeight.deck[room].slice(1);
if (crazyeight.deck[room].length === 0) {
crazyeight.deck[room] = Tools.generateDeck(1);
}
}
Bot.say(config.nick, room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn has been skipped and is forced to draw 4 cards!');
}
if (crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.length < 1) {
Bot.say(config.nick, room, by.slice(1) + ' wins!');
Bot.say(config.nick, room, 'Rewards: ' + Economy.getPayout(crazyeight.playerList[room].length, room) + ' ' + Economy.currency(room));
Economy.give(crazyeight.playerData[room][crazyeight.playerList[room][0]].name, Economy.getPayout(crazyeight.playerList[room].length, room), room);
clearInterval(crazyeight.interval[room]);
crazyeight.gameStatus[room] = 'off';
return;
}
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
Bot.talk(room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn! __(' + config.commandcharacter[0] + 'play [card] or ' + config.commandcharacter[0] + 'draw)__');
//start new dq cycle
crazyeight.interval[room] = setInterval(function() {
if (crazyeight.gameStatus[room] !== 'on') {
clearInterval(crazyeight.interval[room]);
return false;
}
//disqualify for inactivity
crazyeight.playerData[room][crazyeight.currentPlayer[room]].disqualified = true;
//re-make playerlist
var pIndex = crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]);
var pushPlayer = [];
for (var x = 0; x < crazyeight.playerList[room].length; x++) {
if (x === pIndex) {
continue;
}
pushPlayer.push(crazyeight.playerList[room][x]);
}
//reset playerlist
crazyeight.playerList[room] = pushPlayer;
//checking if all players are DQ'd
if (crazyeight.playerList[room].length === 0) {
Bot.say(config.nick, room, 'Nobody wins this game :(');
}
else if (crazyeight.playerList[room].length === 1) {
Bot.say(config.nick, room, crazyeight.playerData[room][crazyeight.playerList[room][0]].name + ' wins!');
Bot.say(config.nick, room, 'Rewards: ' + Economy.getPayout(crazyeight.playerList[room].length, room) + ' ' + Economy.currency(room));
Economy.give(crazyeight.playerData[room][crazyeight.playerList[room][0]].name, Economy.getPayout(crazyeight.playerList[room].length, room), room);
}
if (crazyeight.playerList[room].length < 2) {
clearInterval(crazyeight.interval[room]);
crazyeight.gameStatus[room] = 'off';
return false;
}
//change to next player
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
//pming next user their hand
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
Bot.talk(room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn! __(' + config.commandcharacter[0] + 'play [card] or ' + config.commandcharacter[0] + 'draw)__');
Bot.talk(room, '**Top Card: [' + crazyeight.topCard[room] + ']**');
}, 90000);
},
draw: function(arg, by, room) {
if (toId(by) !== crazyeight.currentPlayer[room] || !crazyeight.gameStatus[room] || crazyeight.gameStatus[room] !== 'on') return false;
clearInterval(crazyeight.interval[room]);
tarPlayer = toId(by);
crazyeight.playerData[room][tarPlayer].hand[crazyeight.playerData[room][tarPlayer].hand.length] = crazyeight.deck[room][0];
crazyeight.deck[room] = crazyeight.deck[room].slice(1);
if (crazyeight.deck[room].length === 0) {
crazyeight.deck[room] = Tools.generateDeck(1);
}
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
//next player
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
Bot.talk(room, '**Top Card: [' + crazyeight.topCard[room] + ']**');
Bot.talk(room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn! __(' + config.commandcharacter[0] + 'play [card] or ' + config.commandcharacter[0] + 'draw)__');
//start new dq cycle
crazyeight.interval[room] = setInterval(function() {
if (crazyeight.gameStatus[room] !== 'on') {
clearInterval(crazyeight.interval[room]);
return false;
}
//disqualify for inactivity
crazyeight.playerData[room][crazyeight.currentPlayer[room]].disqualified = true;
//re-make playerlist
var pIndex = crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]);
var pushPlayer = [];
for (var x = 0; x < crazyeight.playerList[room].length; x++) {
if (x === pIndex) {
continue;
}
pushPlayer.push(crazyeight.playerList[room][x]);
}
//reset playerlist
crazyeight.playerList[room] = pushPlayer;
//checking if all players are DQ'd
if (crazyeight.playerList[room].length === 0) {
Bot.say(config.nick, room, 'Nobody wins this game :(');
}
else if (crazyeight.playerList[room].length === 1) {
Bot.say(config.nick, room, crazyeight.playerData[room][crazyeight.playerList[room][0]].name + ' wins!');
Bot.say(config.nick, room, 'Rewards: ' + Economy.getPayout(crazyeight.playerList[room].length, room) + ' ' + Economy.currency(room));
Economy.give(crazyeight.playerData[room][crazyeight.playerList[room][0]].name, Economy.getPayout(crazyeight.playerList[room].length, room), room);
}
if (crazyeight.playerList[room].length < 2) {
clearInterval(crazyeight.interval[room]);
crazyeight.gameStatus[room] = 'off';
return false;
}
//change to next player
crazyeight.currentPlayer[room] = crazyeight.playerList[room][(crazyeight.playerList[room].indexOf(crazyeight.currentPlayer[room]) + 1) % crazyeight.playerList[room].length];
//pming next user their hand
Bot.talk(',' + crazyeight.currentPlayer[room], '(' + room + ') ' + '[' + crazyeight.playerData[room][crazyeight.currentPlayer[room]].hand.join('], [') + ']');
Bot.talk(room, crazyeight.playerData[room][crazyeight.currentPlayer[room]].name + '\'s turn! __(' + config.commandcharacter[0] + 'play [card] or ' + config.commandcharacter[0] + 'draw)__');
Bot.talk(room, '**Top Card: [' + crazyeight.topCard[room] + ']**');
}, 90000);
},
};
/****************************
* For C9 Users *
*****************************/
// Yes, sadly it can't be done in one huge chunk w/o undoing it / looking ugly :(
/* globals toId */
/* globals Bot */
/* globals config */
/* globals Economy */
/* globals game */
/* globals checkGame */
/* globals crazyeight */
/* globals Tools */
/* globals tarPlayer */
/* globals gameStatus */
|
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './layout.js';
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(<Layout />, document.getElementById('main'));
});
|
$.fn.onEnterKey =
function( closure ) {
$(this).keypress(
function( event ) {
var code = event.keyCode ? event.keyCode : event.which;
if (code == 13) {
closure();
return false;
}
} );
}
String.prototype.trunc = String.prototype.trunc ||
function(n){
return this.length>n ? this.substr(0,n-1)+'…' : this;
}; |
/**
* Pipedrive API v1
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
/**
* The UpdateFileRequest model module.
* @module model/UpdateFileRequest
* @version 1.0.0
*/
class UpdateFileRequest {
/**
* Constructs a new <code>UpdateFileRequest</code>.
* @alias module:model/UpdateFileRequest
*/
constructor() {
UpdateFileRequest.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>UpdateFileRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/UpdateFileRequest} obj Optional instance to populate.
* @return {module:model/UpdateFileRequest} The populated <code>UpdateFileRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new UpdateFileRequest();
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
delete data['name'];
}
if (data.hasOwnProperty('description')) {
obj['description'] = ApiClient.convertToType(data['description'], 'String');
delete data['description'];
}
if (Object.keys(data).length > 0) {
obj['extra'] = data;
}
}
return obj;
}
}
/**
* Visible name of the file
* @member {String} name
*/
UpdateFileRequest.prototype['name'] = undefined;
/**
* Description of the file
* @member {String} description
*/
UpdateFileRequest.prototype['description'] = undefined;
export default UpdateFileRequest;
|
export default class ContestType {
constructor(options) {
let _id = null;
let _name = null;
let _berryFlavor = null;
let _color = null;
Object.defineProperty(this, 'id', {
enumarable: true,
get() {
return _id;
}
});
Object.defineProperty(this, 'name', {
enumarable: true,
get() {
return _name;
}
});
Object.defineProperty(this, 'berryFlavor', {
enumerable: true,
get() {
return _berryFlavor;
}
});
Object.defineProperty(this, 'color', {
enumerable: true,
get() {
return _color;
}
});
_id = parseInt(options.id) || null;
_name = options.name || "No name";
_berryFlavor = options.berryFlavor || "No flavor";
_color = options.color || "No color";
Object.seal(this);
}
}
|
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
(function() {
Event.observe(window, 'load', main);
var WIDTH = 400;
var HEIGHT = 200;
var canvas = null;
var context = null;
var groundCanvas = null;
var groundContext = null;
var groundImage = null;
var scaleCanvas = null;
var scaleContext = null;
// Physics Variables
var lastTime = null;
var dt = null;
var av = 0;
var lv = 0;
var px = 953;
var py = 792;
var pa = 0;
// Viewport Settings
var omega = 120 * Math.PI/180;
var theta = 60 * Math.PI/180;
var alpha = 30 * Math.PI/180;
var h = 15;
var H = 180;
var LH = 1;
var modes = [];
// Input Settings
var codeOffset = 37;
var LEFT = 0;
var UP = 1;
var RIGHT = 2;
var DOWN = 3;
var downKeys = [false, false, false, false];
MAX_VELOCITY = 100/1000;
ANGULAR_VELOCITY = Math.PI/(4 * 1000);
var images = {
'img/mariocircuit.png': null
};
function main()
{
canvas = new Element('canvas', { 'width': WIDTH, 'height': HEIGHT});
context = canvas.getContext("2d");
$$('body')[0].insert(canvas);
Event.observe(window, 'keydown', handleKeydown);
Event.observe(window, 'keyup', handleKeyup);
canvas.observe('mousedown', handleMousedown);
canvas.observe('mouseup', handleMouseup);
canvas.observe('mouseover', function() {
Event.observe(document, 'touchmove', function(e){ e.preventDefault(); });
});
loadImages();
}
function loadImages()
{
for(var key in images) {
console.log(key);
if(images[key] == null) {
var img = new Image();
img.addEventListener("load", handleLoadImageSuccess.bindAsEventListener(this, key), false);
img.addEventListener("error", handleLoadImageFailure.bindAsEventListener(this), false);
img.src = key;
return;
}
}
handleLoadComplete();
}
function handleLoadImageSuccess(event, key)
{
images[key] = event.target;
loadImages();
}
function handleLoadImageFailure(event)
{
loadImages();
}
function handleLoadComplete()
{
window.requestAnimationFrame(update.bind(this));
groundImage = images['img/mariocircuit.png'];
var max = Math.max(groundImage.width, groundImage.height);
groundCanvas = new Element('canvas', { 'width': max, 'height': max, 'style': 'width:' + max/2 + 'px;height:' + max/2 + 'px'});
groundContext = groundCanvas.getContext("2d");
//$$('body')[0].insert(groundCanvas);
/*
scaleCanvas = new Element('canvas', { 'width': max, 'height': max, 'style': 'width:' + max/2 + 'px;height:' + max/2 + 'px'});
scaleContext = scaleCanvas.getContext("2d");
$$('body')[0].insert(scaleCanvas);
*/
// MODES
var sx, sy, sw, sh, dx, dw;
var w = 0,
w1 = 0,
w2 = 0,
d1 = 0,
d2 = 0;
for(var L = 1; L <= H; L++) {
modes[L] = null;
w1 = 2 * h * Math.tan( (Math.PI - theta)/2 + alpha*(L - 1)/H ) / Math.tan(omega/2);
w2 = 2 * h * Math.tan( (Math.PI - theta)/2 + alpha*L/H ) / Math.tan(omega/2);
d1 = h * Math.tan( (Math.PI - theta)/2 + alpha*(L - 1)/H );
d2 = h * Math.tan( (Math.PI - theta)/2 + alpha*L/H );
//w = w1 + (w2-w1)/2;
w = w1;
//if(d2 > groundCanvas.height) continue;
sx = (groundCanvas.width - w)/2;
sy = groundCanvas.height - d1;
sw = w;
sh = d2 - d1;
dw = WIDTH;
dx = 0;
if(w > groundCanvas.width) {
sx = 0;
sw = groundCanvas.width;
dw = WIDTH * (sw/w);
dx = (WIDTH - dw) / 2;
}
/*
context.drawImage(
groundCanvas,
sx,
sy,
sw,
sh,
dx,
HEIGHT - L,
dw,
1
);
*/
modes[L] = {
'sx': sx,
'sy': sy,
'sw': sw,
'sh': sh,
'dx': dx,
'dw': dw
};
}
}
function update(t)
{
window.requestAnimationFrame(update.bind(this));
if(lastTime == null) lastTime = t;
dt = t - lastTime;
lastTime = t;
lv = 0;
av = 0;
//if(lv < 0.05 * MAX_VELOCITY) lv = 0;
//if(av < 0.05 * ANGULAR_VELOCITY) av = 0;
if(downKeys[LEFT] || downKeys[RIGHT] || downKeys[UP] || downKeys[DOWN]) {
lv = MAX_VELOCITY * ((0+downKeys[DOWN]) + (0+downKeys[UP])*-1);
if(lv == -1) lv *= 0.5;
av = ANGULAR_VELOCITY * ((0+downKeys[LEFT]) + (0+downKeys[RIGHT])*-1);
}
pa += (dt * av);
px += (dt * lv) * Math.sin(pa);
py += (dt * lv) * Math.cos(pa);
// Clear the canvas
groundCanvas.width = groundCanvas.width;
//scaleCanvas.width = scaleCanvas.width;
canvas.width = canvas.width;
var dx = (groundCanvas.width/2 - px);
var dy = (groundCanvas.height - py);
groundContext.save();
groundContext.translate(dx + px, dy + py);
groundContext.rotate(pa);
groundContext.translate((dx + px)*-1, (dy + py)*-1);
groundContext.drawImage(groundImage, dx, dy);
groundContext.restore();
for(var L = 1; L <= H; L++) {
var val = modes[L];
if(val == undefined) continue;
context.drawImage(
groundCanvas,
val.sx,
val.sy,
val.sw,
val.sh,
val.dx,
HEIGHT - (L*LH),
val.dw,
LH
);
/*
scaleContext.drawImage(
groundCanvas,
val.sx,
val.sy,
val.sw,
val.sh,
val.dx,
val.sy,
val.dw,
val.sh
);
*/
}
}
function handleKeydown(event)
{
var code = event.keyCode - codeOffset;
//console.log('keydown: ' + code);
switch(code) {
case UP:
case DOWN:
case LEFT:
case RIGHT:
downKeys[code] = true;
break;
}
}
function handleKeyup(event)
{
var code = event.keyCode - codeOffset;
//console.log('keyup: ' + code);
switch(code) {
case UP:
case DOWN:
case LEFT:
case RIGHT:
downKeys[code] = false;
break;
}
}
function handleMousedown(event)
{
if(event.layerY < HEIGHT / 3) {
downKeys[UP] = true;
} else if(event.layerY < HEIGHT * 2 / 3) {
if(event.layerX < WIDTH/2) {
downKeys[LEFT] = true;
} else {
downKeys[RIGHT] = true;
}
} else {
downKeys[DOWN] = true;
}
}
function handleMouseup(event)
{
downKeys[UP] = false;
downKeys[DOWN] = false;
downKeys[LEFT] = false;
downKeys[RIGHT] = false;
}
}());
|
// Looking at closures
// http://stackoverflow.com/q/111102/137001
$(document).ready(function() {
closureTest();
function closureTest() {
//console.log
}
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:0f088644576fe6fee42bb3ce7f1d056f5db1079bf284c312f2acb895c5510851
size 11112
|
// # Ghost Configuration
// Setup your Ghost install for various environments
var path = require('path'),
config;
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://objectiveclem.local',
// Example mail config
// Visit http://docs.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'objective-clem.azurewebsites.net',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: process.env.PORT
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
}
},
// ### Travis
// Automated testing run through Github
travis: {
url: 'http://127.0.0.1:2368',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-travis.db')
}
},
server: {
host: '127.0.0.1',
port: '2368'
}
}
};
// Export config
module.exports = config;
|
import { FETCH_AUTHOR, UPDATE_AUTHOR } from 'shared/constants/actions';
const INITIAL_STATE = {
author: {},
errorMessage: ''
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_AUTHOR.SUCCESS:
// author -> { id, email, name, image, description, introduction }
return { author: action.payload.author, errorMessage: '' };
case UPDATE_AUTHOR.SUCCESS:
return { ...state, author: {}, errorMessage: '' };
case UPDATE_AUTHOR.FAILURE:
return { ...state, errorMessage: action.payload.errorMessage };
default:
return state;
}
} |
'use strict'
// Load requirements
const slack = require('slack')
const path = require('path')
// Load utilities
const i18n = require('../locale')
const logger = require('../log')
// Data directory
const dataDir = path.join(__dirname, '../../../data/')
// User tracking and handling
module.exports = {
// User flags to avoid, edit these depending on your privileges
flags: [
// 'is_admin',
// 'is_owner',
// 'is_primary_owner',
// 'is_restricted',
'is_ultra_restricted',
'is_bot'
],
// Load the user blacklist
blacklist: require(path.join(dataDir, 'blacklist')),
// Contains the list of tracked users
users: {},
// Check if id or username is on the blacklist
blacklisted: function (user) {
return this.blacklist.some((handle) => {
return handle === user.id || handle === user.name
})
},
// Check if a user is restricted
restricted: function (user) {
return this.flags.some((flag) => {
return user[flag] === true
})
},
// Add a user to the track list
add: function (user, ignore) {
// DEBUG
logger.verbose(i18n.t('users.add.added'), user.name)
// Add to object for tracking
this.users[user.id] = {
id: user.id,
name: user.name,
real_name: user.real_name,
short_name: (user.real_name || '').split(' ')[0],
emoji: (user.profile.status_emoji || '').replace(/:/g, ''),
text: user.profile.status_text || '',
ignore: ignore || false
}
},
// Load the available users
load: function () {
return new Promise((resolve, reject) => {
// Get the list from the slack API
slack.users.list({token: process.env.SLACK_TOKEN}, (err, data) => {
// Check for errors
if (err !== null) {
return reject(new Error(i18n.t('users.load.errors.slack', err.message)))
}
// Check for a response
if (data.ok !== true) {
return reject(new Error(i18n.t('users.load.errors.invalid')))
}
// Loop members and add them to ze list
data.members.forEach((user) => {
if (!this.restricted(user)) this.add(user)
})
// resolve the promise with data
return resolve(this.users)
})
})
}
}
|
/*
* Adjust display of page based on search results
*/
function findSearchResults(data, dataLength) {
$("#duplicate_box").remove();
var userString = $("#searchForm #searchField").val();
var minSearchLength = 1;
if (userString.length >= minSearchLength) {
//this calls search() inside itself
var numResults = populateResults(userString, dataLength, data);
// If "results" is empty, activate the "add new client" button.
if (numResults > 0) {
// We've found some results, but we may still have to add a
// new client (maybe a person with the same name as an
// existing client). The "add new client" button will be
// activated, but with a caveat.
caveatText = "None Of The Above -- Add New Client";
$("#addNewClient").text(caveatText);
}
else {
// No need for the caveat.
$("#addNewClient").text(noCaveatText);
}
// If we're over the minimum length, we may add a new client.
$("#searchForm #addNewClient").prop("disabled", false);
}
else if (userString.length == 0) {
$("#searchForm #results").empty();
$("#addNewClient").text(noCaveatText);
$("#searchForm #addNewClient").prop("disabled", true);
}
};
/*
* Takes a user-entered string and returns the number of matching
* entries. Along the way it fills in the result divs.
*/
function populateResults(userString, data_length, dataset) {
var newHits = search(userString, data_length, dataset);
// Create an array to hold indices of all the latest hits. If an
// old hit isn't found in here, it gets removed.
var newHitIndices = [];
for (var i=0; i<newHits.length; i++) {
newHitIndices.push(newHits[i].index);
}
var oldHits = $("#searchForm #results .hit");
oldHits.each(function() {
// Remember these are not objects of class Hit;
// they're DOM elements (of class "hit").
var oldHitIndex = $(this).data("entity-index");
for (var i=newHits.length-1; i>=0; i--) {
if (oldHitIndex == newHits[i].index) {
// There is already a <div> in the results field that
// matches the one just returned; replace it with an
// updated version (like a longer match string).
$(this).empty();
$(this).replaceWith(getSummaryDiv(newHits[i]));
newHits.splice(i, 1); // remove the match from "newHits"
}
}
// Finally, if the entity of an old hit is no longer
// represented in new hits, mark it for removal from the
// results area.
if ($.inArray(oldHitIndex, newHitIndices) < 0) {
$(this).addClass("removeMe");
}
});
// Now remove from the "results" div...
$("#searchForm #results .hit.removeMe").remove();
// And add all newHits...
for (var i=0; i<newHits.length; i++) {
$("#searchForm #results").append(getSummaryDiv(newHits[i]));
}
// Return the number of matching entities.
return $("#searchForm #results > .hit").length;
};
function Entity() {
// Start by setting all values to the empty string.
for (var i=0; i<propertyListLength; i++) {
this[propertyList[i]] = "";
}
// Set some default values.
this.personalId = -1;
this.picture = "unknown.png";
// Use the names stored in the search form as default vals.
// Usually they'll be overwritten, but not if this is a new client.
this.firstName = $("#searchForm #firstName").val();
this.lastName = $("#searchForm #lastName").val();
};
function Hit(entity) {
this.index = entity.personalId;
this.removeMe = false; // Used when comparing to already-matched records.
this.picture = entity.picture;
this.firstName = entity.firstName;
this.lastName = entity.lastName;
this.gender = entity.gender;
this.dob = entity.dob ? getFormattedDOB(entity.dob) : "";
this.age = entity.dob ? getYearsOld(entity.dob) : "";
};
function getFormattedDOB(date) {
return moment(date).format('DD MMM YYYY');
};
function getYearsOld(date) {
return moment().diff(date, 'years');
};
/* Hit factory holds a dictionary of hits (with entity indices as
keys) that match user input. */
function HitFactory() {
this.hits = {};
};
HitFactory.prototype.getHit = function(entity) {
var hit = null;
if (this.hits.hasOwnProperty(entity.personalId)) {
hit = this.hits[entity.personalId];
}
else {
hit = new Hit(entity);
this.hits[entity.personalId] = hit;
}
return hit;
};
HitFactory.prototype.killHit = function(entity) {
if (this.hits.hasOwnProperty(entity.index)) {
delete this.hits[entity.index];
}
};
HitFactory.prototype.allTheHits = function() {
var hitList = [];
for (index in this.hits) {
hitList.push(this.hits[index]);
}
return hitList;
};
/*
* Takes a user-entered string and returns the set of matching
* clients, as "hit" objects.
*/
function search(userString, data_length, dataset) {
// First Trim any non-alphanumerics from the ends of the user's input.
userString = userString.replace(/^[^\w]+/i, "").replace(/[^\w]+$/i, "");
// Then split the user's string on non-alphanumeric sequences. This
// eliminates a dot after a middle initial, a comma if name is
// entered as "Doe, John" (or as "Doe , John"), etc.
userSubstrings = userString.split(/\s+[^\w]+\s*|\s*[^\w]+\s+|\s+/);
// Store the first and second user substrings into some hidden form
// fields. They might be used later if a new client is created.
$("#searchForm #firstName").val(userSubstrings[0]);
$("#searchForm #lastName").val(userSubstrings.length > 1 ? userSubstrings[1] : "");
// The hit factory will generate new a Hit object or return an
// already instantiated one with the requested index.
var hitFactory = new HitFactory();
var entity = null;
var result = null;
var matchLength = 0;
var hit = null;
// Turn the user's input into a list of regexes that will try to match against our matching terms.
var userRegexes = $.map(userSubstrings, function(userSubstring) { return new RegExp("^" + userSubstring, "i"); });
// This is the list of "matching terms" we will try to match to user input.
var matchingTerms = ["firstName", "lastName"];
for (var i=0; i<data_length; i++) {
entity = dataset[i];
// Make a copies of "userRegexes" and "matchingTerms" that we can
// alter as we search.
var userRegexesCopy = userRegexes.slice(0);
var matchingTermsCopy = matchingTerms.slice(0);
while (userRegexesCopy.length > 0) {
var userRegex = userRegexesCopy.shift();
var matchFound = false;
for (var j=0; j < matchingTermsCopy.length; ) {
if (entity[matchingTermsCopy[j]] !== null){
result = entity[matchingTermsCopy[j]].match(userRegex);
}
else {
result = null;
}
if (result !== null) {
// We found a match. Figure out how long it is.
matchLength = result[0].length;
// If the match is perfect OR if there are no more
// user-entered search terms after this one, we may mark it
// as a hit.
if (matchLength == entity[matchingTermsCopy[j]].length || userRegexesCopy.length == 0) {
hit = hitFactory.getHit(entity);
hit[matchingTermsCopy[j]] = "<span class='marked'>" + entity[matchingTermsCopy[j]].substr(0, matchLength) + "</span>" + entity[matchingTermsCopy[j]].substr(matchLength);
matchFound = true;
// Remove this matching term from consideration when
// processing other user search terms by splicing it out
// of our copy of matching terms.
matchingTermsCopy.splice(j, 1);
// Since "matchingTermsCopy" is now shorter by 1, continue
// the loop without incrementing the counter.
continue;
}
}
j++;
}
if (matchFound == false) {
// If any part of the user-entered search terms failed to find
// a match, previous matches don't matter. The entity should
// not appear in the list of hits.
hitFactory.killHit(entity);
break;
}
}
}
return hitFactory.allTheHits();
};
function getSummaryDiv(hit) {
var summaryDiv = $("<div class='hit'></div>");
if (hit.picture){
var picture = $("<div class='picture'><img src=\"img/" + hit.picture + "\"></div>");
}
var text = $("<div class='text'></div>");
var fullName = $("<div class='summaryElement'><span>" + hit.firstName + " " + hit.lastName + "</span></div>");
var clear = $("<div class='clear'></div>");
var dob = $("<div class='summaryElement'><span class='label'>DOB: </span><span>" + hit.dob + "</span></div>");
var age = $("<div class='summaryElement'><span class='label'>age: </span><span>" + getYearsOld(hit.dob) + "</span></div>");
summaryDiv.append(picture);
text.append(fullName);
text.append(clear);
text.append(dob);
text.append(age);
summaryDiv.append(text);
summaryDiv.data("entity-index", hit.index);
return summaryDiv;
};
|
Rickshaw.namespace('Rickshaw.Graph.Axis.Y.Scaled');
Rickshaw.Graph.Axis.Y.Scaled = Rickshaw.Class.create( Rickshaw.Graph.Axis.Y, {
initialize: function($super, args) {
if (typeof(args.scale) === 'undefined') {
throw new Error('Scaled requires scale');
}
this.scale = args.scale;
if (typeof(args.grid) === 'undefined') {
this.grid = true;
} else {
this.grid = args.grid;
}
$super(args);
},
_drawAxis: function($super, scale) {
// Adjust scale's domain to compensate for adjustments to the
// renderer's domain (e.g. padding).
var domain = this.scale.domain();
var renderDomain = this.graph.renderer.domain().y;
var extents = [
Math.min.apply(Math, domain),
Math.max.apply(Math, domain)];
// A mapping from the ideal render domain [0, 1] to the extent
// of the original scale's domain. This is used to calculate
// the extents of the adjusted domain.
var extentMap = d3.scaleLinear().domain([0, 1]).range(extents);
var adjExtents = [
extentMap(renderDomain[0]),
extentMap(renderDomain[1])];
// A mapping from the original domain to the adjusted domain.
var adjustment = d3.scaleLinear().domain(extents).range(adjExtents);
// Make a copy of the custom scale, apply the adjusted domain, and
// copy the range to match the graph's scale.
var adjustedScale = this.scale.copy()
.domain(domain.map(adjustment))
.range(scale.range());
return $super(adjustedScale);
},
_drawGrid: function($super, axis) {
if (this.grid) {
// only draw the axis if the grid option is true
$super(axis);
}
}
} );
|
//Here is all the code that builds the list of objects on the right-hand
//side of the Labelme tool.
//The styles for this tools are defined inside:
//annotationTools/css/object_list.css
var IsHidingAllPolygons = false;
var ProgressChecking = false;
//var IsHidingAllFilled = true;
var ListOffSet = 0;
//This function creates and populates the list
function RenderObjectList() {
// If object list has been rendered, then remove it:
var scrollPos = $("#anno_list").scrollTop();
if($('#anno_list').length) {
$('#anno_list').remove();
}
var html_str = '<div class="object_list" id="anno_list" style="border:0px solid black;z-index:0;" ondrop="drop(event, -1)" ondragenter="return dragEnter(event)" ondragover="return dragOver(event)">';
var Npolygons = LMnumberOfObjects(LM_xml);
// name of image
html_str += '<p style="font-size:14px;line-height:100%"><h>Image: <a href="javascript:GetThisURL();">'+main_media.file_info.im_name+'</a></h></p>';
if (!ProgressChecking){
//Checks progress by filling all polygons
html_str += '<p style="font-size:12px;line-height:50%" id="check_progress" ><a href="javascript:CheckProgress();"><b>Check progress</b></a> (s)</p>';
} else {//Clear Progress check
html_str += '<p style="font-size:12px;line-height:50%" id="end_check_progress"><a href="javascript:EndCheckProgress();" style="color:red"><b>Clear progress check</b></a> (h)</p>';
}
if (IsHidingAllPolygons){ //Polygons hidden, press to show outlines permanently
html_str += '<p style="font-size:12px;line-height:50%"><a id="hold_poly" href="javascript:ShowAllPolygons();"><b>Press to hold outlines</b></a></p>';
} else
{ //Outlines held status msg
html_str += '<p style="font-size:12px;line-height:50%"><a id="poly_held" style="text-decoration:none; font-style:italic; color:#708090;">Outlines held (\'Hide all\' to release)</a></p>';
}
//Hide all polygons
html_str += '<p style="font-size:12px;line-height:50%"><a id="hide_all" href="javascript:HideAllPolygons();"><b>Hide all </b></a></p>';
// Create DIV
html_str += '<u><i>'+ Npolygons +'</i> classes labeled in all:</u>';
html_str += '<ol>';
for(var i=0; i < Npolygons; i++) {
html_str += '<div class="objectListLink" id="LinkAnchor' + i + '" style="z-index:1; margin-left:0em"> ';
html_str += '<li>';
// show object name:
html_str += '<a class="objectListLink" id="Link' + i + '" '+
'href="javascript:main_handler.AnnotationLinkClick('+ i +');" '+
'onmouseover="main_handler.AnnotationLinkMouseOver('+ i +');" ' +
'onmouseout="main_handler.AnnotationLinkMouseOut();" ';
html_str += '>';
var obj_name = LMgetObjectField(LM_xml,i,'name');
html_str += obj_name;
html_str += '</a>';
html_str += '</li></div>';
}
html_str += '</ol><p><br/></p></div>';
// Attach annotation list to 'anno_anchor' DIV element:
$('#anno_anchor').append(html_str);
$('#Link'+add_parts_to).css('font-weight',700); //
$('#anno_list').scrollTop(scrollPos);
}
function RemoveObjectList() {
$('#anno_list').remove();
}
function ChangeLinkColorBG(idx) {
if(document.getElementById('Link'+idx)) {
var isDeleted = parseInt($(LM_xml).children("annotation").children("object").eq(idx).children("deleted").text());
if(isDeleted) document.getElementById('Link'+idx).style.color = '#888888';
else document.getElementById('Link'+idx).style.color = '#0000FF';
var anid = main_canvas.GetAnnoIndex(idx);
// If we're hiding all polygons, then remove rendered polygon from canvas:
if(IsHidingAllPolygons && main_canvas.annotations[anid].hidden) {
main_canvas.annotations[anid].DeletePolygon();
}
}
}
function ChangeLinkColorFG(idx) {
document.getElementById('Link'+idx).style.color = '#FF0000';
var anid = main_canvas.GetAnnoIndex(idx);
// If we're hiding all polygons, then render polygon on canvas:
if(IsHidingAllPolygons && main_canvas.annotations[anid].hidden) {
main_canvas.annotations[anid].DrawPolygon(main_media.GetImRatio(), main_canvas.annotations[anid].GetPtsX(), main_canvas.annotations[anid].GetPtsY());
}
}
function HideAllPolygons() {
if(!edit_popup_open) {
IsHidingAllPolygons = true;
ProgressChecking = false;
// Delete all polygons from the canvas:
for(var i = 0; i < main_canvas.annotations.length; i++) {
main_canvas.annotations[i].DeletePolygon();
main_canvas.annotations[i].hidden = true;
}
// Create "show all" button:
$('#poly_held').replaceWith('<a id="hold_poly" href="javascript:ShowAllPolygons();"><b>Press to hold outlines</b></a>');
$('#end_check_progress').replaceWith('<p style="font-size:12px;line-height:50%" id="check_progress" ><a href="javascript:CheckProgress();"><b>Check progress</b></a> (s)</p>');
}
else {
alert('Close edit popup bubble first');
}
}
function ShowAllPolygons() {
if (ProgressChecking) return; //hold outline setting not allowed to be trigger when progress checking ongoing
// Set global variable:
IsHidingAllPolygons = false;
ProgressChecking = false;
// Render the annotations:
main_canvas.UnhideAllAnnotations();
main_canvas.RenderAnnotations();
// swap hold poly with poly held
$('#hold_poly').replaceWith('<a id="poly_held" style="text-decoration:none; font-style:italic; color:#708090;">Outlines held (\'Hide all\' to release)</a>');
}
function CheckProgress() {
ProgressChecking = true;
//clear all polygons first
if(!edit_popup_open) {
// Delete all polygons from the canvas:
for(var i = 0; i < main_canvas.annotations.length; i++) {
main_canvas.annotations[i].DeletePolygon();
main_canvas.annotations[i].hidden = true;
}
}
else {
alert('Close edit popup bubble first');
}
//reset annotations to take into account user editting labels while checking progress.
main_canvas.annotations.length = 0;
// Attach valid annotations to the main_canvas:
for(var pp = 0; pp < LMnumberOfObjects(LM_xml); pp++) {
// Attach to main_canvas:
main_canvas.AttachAnnotation(new annotation(pp));
if (!video_mode && LMgetObjectField(LM_xml, pp, 'x') == null){
main_canvas.annotations[main_canvas.annotations.length -1].SetType(1);
main_canvas.annotations[main_canvas.annotations.length -1].scribble = new scribble(pp);
}
}
// Render the annotations:
main_canvas.UnhideAllAnnotations();
main_canvas.RenderAnnotations();
//Fill all
for (var i= 0; i < LMnumberOfObjects(LM_xml); i++){
main_canvas.annotations[i].FillPolygon();
}
console.log("check progress");
// Create "hide all" button:
$('#show_all_filled_button').replaceWith('<a id="hide_all_filled_button" href="javascript:HideAllFilled();">Hide back</a>');
$('#check_progress').replaceWith('<p style="font-size:12px;line-height:50%" id="end_check_progress"><a href="javascript:EndCheckProgress();" style="color:red"><b>Clear progress check</b></a> (h)</p>');
}
function EndCheckProgress() {
if(!edit_popup_open) {
ProgressChecking = false;
if(IsHidingAllPolygons){
// Delete all polygons from the canvas:
for(var i = 0; i < main_canvas.annotations.length; i++) {
main_canvas.annotations[i].DeletePolygon();
main_canvas.annotations[i].hidden = true;
}
}
else {//if we are holding all polygons
for(var i = 0; i < main_canvas.annotations.length; i++) {
main_canvas.annotations[i].UnfillPolygon();
}
}
console.log("end check progress");
// Create "show all" button:
$('#end_check_progress').replaceWith('<p style="font-size:12px;line-height:50%" id="check_progress" ><a href="javascript:CheckProgress();"><b>Check progress</b></a> (s)</p>');
}
else {
alert('Close edit popup bubble first');
}
}
//*******************************************
//Private functions:
//*******************************************
//DRAG FUNCTIONS
function drag(event, part_id) {
// stores the object id in the data that is being dragged.
event.dataTransfer.setData("Text", part_id);
}
function dragend(event, object_id) {
event.preventDefault();
// Write XML to server:
WriteXML(SubmitXmlUrl,LM_xml,function(){return;});
}
function dragEnter(event) {
event.preventDefault();
return true;
}
function dragOver(event) {
event.preventDefault();
}
function drop(event, object_id) {
event.preventDefault();
var part_id=event.dataTransfer.getData("Text");
event.stopPropagation();
// modify part structure
if(object_id!=part_id) {
addPart(object_id, part_id);
// redraw object list
RenderObjectList();
}
}
|
define([
"knockout",
// mappoint needs to be here first for addEventListener
"../modules/mappoint",
], function (ko) {
// create result object
var result = {
cityname : ko.observable(''),
citydata : ko.observableArray([])
};
// subscribe to custom event
window.addEventListener("getTitle", getWikipedia, false);
// use for jsonp call to wikipedia
var city ='',
// oldValue
oldValue = '';
// call function
function getWikipedia (e) {
// listen to custom event
city = e.detail.title;
// store data object
var data = '';
// if city equals old value do nothing
if (city === oldValue) {
// do something when element is clicked twice
console.log("you have allready clicked this " + city + " marker");
}
// if city contains new value
else {
// check if city is in LocalStorage
if (localStorage[city]) {
// get localstorage item and store it
data = JSON.parse(localStorage[city]);
// populate observables
result.citydata([data]);
result.cityname(city);
}
else {
// if no localstorage, sent request
sentJSONPRequest(city);
}
// set city to old value
oldValue = city;
}
}
// found jsonp solution for wikipedia after trying it many times with xmlhttprequest and cors
function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
// create callback and delete it
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
// add script
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
// simple error handling (works in firefox and chrome)
window.onerror = function (errorMsg, url, lineNumber) {
alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber);
};
document.body.appendChild(script);
}
// set api url
var sentJSONPRequest = function (city) {
// set url for jsonp request
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' + city + '&format=json&callback=?';
// call jsonp request
jsonp(url, function(data) {
// fill result with wikipedia object
result.citydata([data[1]]);
// use change in city for observable
result.cityname(data[0]);
// if localstorage support
if (window.localStorage) {
// store city object with data array
localStorage[data[0]] = JSON.stringify(data[1]);
}
});
};
return result;
}); |
import path from 'path';
import os from 'os';
import { assert, test } from 'yeoman-generator';
describe('sails-rest-api:logger', () => {
describe('Should properly scaffold default configuration', () => {
before(done => test.run(path.join(__dirname, '../../src/logger')).on('end', done));
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /timestamp: true/);
});
});
describe('Should properly scaffold bunyan configuration', () => {
before(done => {
test
.run(path.join(__dirname, '../../src/logger'))
.withArguments(['bunyan'])
.on('end', done)
});
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /bunyan:/);
});
});
describe('Should properly scaffold Sails default configuration', () => {
before(done => {
test
.run(path.join(__dirname, '../../src/logger'))
.withArguments(['default'])
.on('end', done)
});
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /level: 'verbose'/);
});
});
describe('Should properly scaffold winston configuration', () => {
before(done => {
test
.run(path.join(__dirname, '../../src/logger'))
.withArguments(['winston'])
.on('end', done)
});
it('Should properly create configuration files', () => {
assert.file([
'config/log.js'
]);
assert.fileContent('config/log.js', /timestamp: true/);
});
});
});
|
angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/'
function cmd(){
return _.cloneDeep( command );
}
function sendRequest( data ){
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Input.Up";
break;
case 'down':
data.method = "Input.Down";
break;
case 'select':
data.method = "Input.Select";
break;
case 'info':
data.method = "Input.Info";
break;
case 'context':
data.method = "Input.ContextMenu";
break;
}
return sendRequest( data );
}
XBMC.sendToPlayer = function( link ){
var data = cmd();
data.params = { method: "Player.Open", item: { file: link } };
return sendRequest( data );
}
}) |
import Ember from "ember";
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';
import { authenticateSession } from 'code-corps-ember/tests/helpers/ember-simple-auth';
import indexPage from '../pages/index';
let application;
module('Acceptance: Logout', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test("Logging out", function(assert) {
assert.expect(2);
let user = server.create('user');
authenticateSession(application, { user_id: user.id });
indexPage.visit();
andThen(function() {
assert.equal(indexPage.navMenu.userMenu.logOut.text, "Log out", "Page contains logout link");
indexPage.navMenu.userMenu.logOut.click();
});
andThen(function() {
assert.equal(indexPage.navMenu.logIn.text, "Sign in", "Page contains login link");
});
});
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
Cu.import("resource://gre/modules/Services.jsm");
const TEST_DATA = "ftp://ftp.mozqa.com/";
var setupModule = function(aModule) {
aModule.controller = mozmill.getBrowserController();
}
var testNavigateFTP = function () {
// opens the mozilla.org ftp page then navigates through a couple levels.
controller.open(TEST_DATA);
controller.waitForPageLoad();
var dataLink = new elementslib.Link(controller.tabs.activeTab, 'data');
controller.click(dataLink);
controller.waitForPageLoad();
var up = new elementslib.Selector(controller.tabs.activeTab, '.up');
controller.click(up);
controller.waitForPageLoad();
controller.waitForElement(dataLink);
}
|
var data = {videos-content: {}} |
(function ($) {
// Navigation scrolls
$('.navbar-nav li a').bind('click', function (event) {
$('.navbar-nav li').removeClass('active');
$(this).closest('li').addClass('active');
var $anchor = $(this);
var nav = $($anchor.attr('href'));
if (nav.length) {
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
}
});
// About section scroll
$(".overlay-detail a").on('click', function (event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function () {
window.location.hash = hash;
});
});
//jQuery to collapse the navbar on scroll
$(window).scroll(function () {
if ($(".navbar-default").offset().top > 40) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
$('.navbar-collapse').on('show.bs.collapse', function () {
$(".navbar-fixed-top").addClass("top-nav-collapse-shadow");
})
$('.navbar-collapse').on('hide.bs.collapse', function () {
$(".navbar-fixed-top").removeClass("top-nav-collapse-shadow");
})
})(jQuery); |
(window.yoastWebpackJsonp=window.yoastWebpackJsonp||[]).push([[23],{947:function(t,i,o){"use strict";jQuery("#posts-filter .tablenav.top").after('<div class="notice notice-info inline wpseo-filter-explanation"><p class="dashicons-before dashicons-lightbulb">'+yoastFilterExplanation.text+"</p></div>")}},[[947,0]]]); |
import util from 'util'
import mongoose from 'mongoose'
import seedData from '../seedData'
const debug = require('debug')('api:server:db')
mongoose.Promise = require('bluebird')
const host = process.env.MONGO_HOST || 'localhost'
const database = process.env.MONGO_DATABASE || 'admin'
const port = process.env.MONGO_PORT || 27017
const url = `mongodb://${host}:${port}/${database}`
const configureMongo = () => {
debug(`connecting to ${url}...`)
mongoose.connect(url).then(
() => seedData(),
err => {
debug(`unable to connect to database: ${err}`)
setTimeout(configureMongo, 5000)
}
)
if (process.env.MONGO_DEBUG) {
mongoose.set('debug', (collectionName, method, query, doc) => {
debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
});
}
}
export default configureMongo |
$(function() {
$(".ajax_filter_choice").click(function() {
$(this).parent().siblings().css("font-weight", "normal");
$(this).parent().css("font-weight","bold");
})
});
ajax_filtered_fields = {
request_url: "/ajax_filtered_fields/json_index/",
data_loaded: "data_loaded",
_appendOption: function(obj, selector) {
// append a json data row as an option to the selector
var option = $('<option>' + obj[1] + '</option>');
option.attr({value: obj[0]});
option.appendTo(selector);
return option;
},
_removeOptions: function(selector) {
// remove all options from selector
selector.children("option").each(function(i) {
$(this).remove();
});
},
getManyToManyJSON: function(element_id, app_label, object_name,
lookup_string, select_related) {
// manage the ManyToMany ajax request
var selector_from = $("#" + element_id + "_from");
var selector_to = $("#" + element_id + "_to");
$("#" + element_id + "_input").val("");
selector_from.attr("disabled", true);
selector_to.attr("disabled", true);
this._removeOptions(selector_from);
$.getJSON(this.request_url, {
app_label: app_label,
object_name: object_name,
lookup_string: lookup_string,
select_related: select_related},
function(data){
$.each(data, function(i, obj){
var option_is_selected = selector_to.children("option[value='" + obj[0] + "']").length;
if (!option_is_selected) {
ajax_filtered_fields._appendOption(obj, selector_from);
};
});
SelectBox.init(element_id + "_from");
selector_from.attr("disabled", false);
selector_to.attr("disabled", false);
selector_from.trigger(ajax_filtered_fields.data_loaded);
});
},
getForeignKeyJSON: function(element_id, app_label, object_name,
lookup_string, select_related) {
// manage the ForeignKey ajax request
var selector = $("#" + element_id);
var hidden = $("#hidden-" + element_id);
$("#" + element_id + "_input").val("");
selector.attr("disabled", true);
this._removeOptions(selector);
$.getJSON(this.request_url, {
app_label: app_label,
object_name: object_name,
lookup_string: lookup_string,
select_related: select_related},
function(data){
var selection = hidden.val();
ajax_filtered_fields._appendOption(new Array("", "---------"), selector);
$.each(data, function(i, obj){
ajax_filtered_fields._appendOption(obj, selector);
});
selector.children("option[value='" + selection + "']").attr("selected", "selected");
selector.attr("disabled", false);
SelectBox.init(element_id);
ajax_filtered_fields.bindForeignKeyOptions(element_id);
selector.trigger(ajax_filtered_fields.data_loaded);
});
},
bindForeignKeyOptions: function(element_id) {
// bind the dummy options to the hidden field that do the work
var selector = $("#" + element_id);
var hidden = $("#hidden-" + element_id);
selector.change(function(e) {
hidden.val($(this).val());
});
}
};
|
'use strict';
var type = require('type-detect');
var path = require('path');
var removeTrailingSeparator = require('remove-trailing-path-separator');
var errors = require('common-errors');
var prettyFormat = require('pretty-format');
module.exports = function (input, cb) {
if (type(input) !== 'string') {
cb(new errors.TypeError('input requires string'), null);
return;
}
var split = removeTrailingSeparator(path.normalize(input)).split(path.sep);
var inputLast = split[split.length - 1];
if (['', '.', '..'].some(function (value) {
return inputLast === value;
})) {
cb(new errors.ArgumentError('input is not allowed: ' + prettyFormat(inputLast)), null);
return;
}
cb(null, inputLast);
};
|
const test = require('tape')
const nlp = require('../_lib')
test('before-basic', function(t) {
let doc = nlp('one two three four five. one three four')
let arr = doc.before('three four').out('array')
t.equal(arr.length, 2, 'two-matches')
t.equal(arr[0], 'one two', 'first-match')
t.equal(arr[1], 'one', 'second-match')
doc = nlp('one two three four five. one three four. three four')
arr = doc.before('three').out('array')
t.equal(arr.length, 2, 'two-matches')
t.equal(arr[0], 'one two', 'first-match')
t.equal(arr[1], 'one', 'second-match')
t.end()
})
test('before-match:', function(t) {
let r = nlp('one two three four five').before('two')
t.equal(r.out('normal'), 'one', 'before-two')
r = nlp('one two three four five').before('three . five')
t.equal(r.out('normal'), 'one two', 'before-several')
r = nlp('one two three four five').before('one two')
t.equal(r.out('normal'), '', 'no-before-start')
// r = nlp('one two three four').before('.'); //tricky
// t.equal(r.out('normal'), '', 'before-any');
r = nlp('one two three four. No, not here. He said two days a week.').before('two')
let arr = r.out('array')
t.equal(arr[0], 'one', 'before-twice-1')
t.equal(arr[1], 'He said', 'before-twice-2')
r = nlp('it was all the way over to two. It was the number two.').before('it')
t.equal(r.found, false, 'no-empty-matches')
t.end()
})
test('after-match:', function(t) {
let r = nlp('one two three four five').after('two')
t.equal(r.out('normal'), 'three four five', 'after-one')
r = nlp('one two three four five').after('one . three')
t.equal(r.out('normal'), 'four five', 'after-several')
r = nlp('one two three four five').after('four five')
t.equal(r.out('normal'), '', 'no-afters-end')
r = nlp('one two three four').after('.')
t.equal(r.out('normal'), 'two three four', 'after-any')
r = nlp('one two three four. No, not here. He said two days a week.').after('two')
let arr = r.out('array')
t.equal(arr[0], 'three four.', 'after-twice-1')
t.equal(arr[1], 'days a week.', 'after-twice-2')
r = nlp('all the way over to two. It was the number two.').after('two')
t.equal(r.found, false, 'no-empty-matches')
t.end()
})
|
/**
* The DOM Element unit handling
*
* Copyright (C) 2008-2011 Nikolay Nemshilov
*/
var Element = RightJS.Element = new Class(Wrapper, {
/**
* constructor
*
* NOTE: this constructor will dynamically typecast
* the wrappers depending on the element tag-name
*
* @param String element tag name or an HTMLElement instance
* @param Object options
* @return Element element
*/
initialize: function(element, options) {
Element_initialize(this, element, options);
}
}, Element_Klass),
Element_wrappers = Element.Wrappers = {},
elements_cache = {},
/**
* bulds dom-elements
*
* @param String element tag name
* @param Object options
* @return HTMLElement
*/
make_element = function (tag, options) {
return (tag in elements_cache ? elements_cache[tag] : (
elements_cache[tag] = document.createElement(tag)
)).cloneNode(false);
};
//
// IE 6,7,8 (not 9!) browsers have a bug with checkbox and radio input elements
// it doesn't place the 'checked' property correctly, plus there are some issues
// with clonned SELECT objects, so we are replaceing the elements maker in here
//
if (IE8_OR_LESS) {
make_element = function(tag, options) {
if (options !== undefined && (tag === 'input' || tag === 'button')) {
tag = '<'+ tag +' name="'+ options.name +
'" type="'+ options.type +'"'+
(options.checked ? ' checked' : '') + ' />';
delete(options.name);
delete(options.type);
}
return document.createElement(tag);
};
}
/**
* Basic element's constructor
*
* @param Element wrapper instance
* @param mixed raw dom element of a string tag name
* @param Object options
* @return void
*/
function Element_initialize(inst, element, options) {
if (typeof element === 'string') {
inst._ = make_element(element, options);
if (options !== undefined) {
for (var key in options) {
switch (key) {
case 'id': inst._.id = options[key]; break;
case 'html': inst._.innerHTML = options[key]; break;
case 'class': inst._.className = options[key]; break;
case 'on': inst.on(options[key]); break;
default: inst.set(key, options[key]);
}
}
}
} else {
inst._ = element;
}
}
|
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var json2csv = require('json2csv');
var fs = require('fs');
var path = require('path');
// var fields = ['car', 'price', 'color'];
// var myCars = [
// {
// "car": "Audi",
// "price": 40000,
// "color": "blue"
// }, {
// "car": "BMW",
// "price": 35000,
// "color": "black"
// }, {
// "car": "Porsche",
// "price": 60000,
// "color": "green"
// }
// ];
// json2csv({ data: myCars, fields: fields }, function(err, csv) {
// if (err) console.log(err);
// fs.writeFile('file.csv', csv, function(err) {
// if (err) throw err;
// console.log('file saved');
// });
// });
var mongoose = require('mongoose');
mongoose.connect('mongodb://192.168.10.62:27000/tempTW'); // connect to our database
var Bear = require('./models/bear');
var CFSOrg = require('./models/CFSOrganization');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoding'}));
app.use(bodyParser.json({limit:1024*1024*20, type:'application/json'}));
var port = process.env.PORT || 9001; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9999');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.use('/downloadFile', express.static(path.join(__dirname, 'exports')));
// more routes for our API will happen here
// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
bear.shortName = req.body.shortName;
bear.subName = req.body.subName;
bear.city = req.body.city;
bear.state = req.body.state;
bear.country = req.body.country;
// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
// get all the bears (accessed at GET http://localhost:8080/api/bears)
.get(function(req, res) {
Bear.find(function(err, result) {
if (err)
res.send(err);
res.json(result);
});
});
router.route('/export')
.post(function(req, res) {
debugger;
console.log(req);
var fields = [
'_id',
'name',
'shortName',
'subName',
'city',
'state',
'country'
];
var myBears = [];
myBears = req.body;
json2csv({ data: myBears, fields: fields }, function(err, csv) {
if (err) console.log(err);
var exportDir = '/exports'
var fileName = 'myBears_file_' + new Date().getTime() + '.csv';
fs.writeFile(path.join(__dirname, exportDir, fileName), csv, function(err) {
if (err) throw err;
console.log('file saved as : ' + fileName);
res.send({csvFile: fileName});
// res.send(path.join(__dirname, exportDir, fileName));
var filePath = path.join(__dirname, exportDir, fileName);
var readStream = fs.createReadStream(filePath);
readStream.pipe(res);
// res.sendFile(exportDir, fileName);
});
});
});
// get all the bears (accessed at GET http://localhost:8080/api/bears)
// .get(function(req, res) {
// var fields = ['name', 'shortName', 'subName'];
// var myBears = [];
// myBears = req.body;
// json2csv({ data: myBears, fields: fields }, function(err, csv) {
// if (err) console.log(err);
// var fileName = 'myBears_file_' + new Date().getTime() + '_.csv';
// fs.writeFile(fileName, csv, function(err) {
// if (err) throw err;
// console.log('file saved as : ' + filename);
// res.send({csvFile: filename});
// });
// });
// // res.sendFile('myBears_file.csv');
// });
router.route('/CFSOrganizations')
.get(function(req, res) {
// CFSOrg.find(function(err, result) {
// if (err)
// res.send(err);
// res.json(result);
// });
CFSOrg.find(function(err, records) {
if (err) {
handleError(res, err.message, "Failed to get contacts.");
} else {
res.status(200).json(records);
}
});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port); |
/**
* @fileoverview
* Base types and classes used by chem editor.
* @author Partridge Jiang
*/
/*
* requires /lan/classes.js
* requires /chemDoc/issueCheckers/kekule.issueCheckers.js
* requires /widgets/operation/kekule.operations.js
* requires /render/kekule.render.base.js
* requires /render/kekule.render.boundInfoRecorder.js
* requires /html/xbrowsers/kekule.x.js
* requires /widgets/kekule.widget.base.js
* requires /widgets/chem/kekule.chemWidget.chemObjDisplayers.js
* requires /widgets/chem/editor/kekule.chemEditor.extensions.js
* requires /widgets/chem/editor/kekule.chemEditor.editorUtils.js
* requires /widgets/chem/editor/kekule.chemEditor.configs.js
* requires /widgets/chem/editor/kekule.chemEditor.operations.js
* requires /widgets/chem/editor/kekule.chemEditor.modifications.js
*/
(function(){
"use strict";
var OU = Kekule.ObjUtils;
var AU = Kekule.ArrayUtils;
var EU = Kekule.HtmlElementUtils;
var CU = Kekule.CoordUtils;
var CNS = Kekule.Widget.HtmlClassNames;
var CCNS = Kekule.ChemWidget.HtmlClassNames;
/** @ignore */
Kekule.ChemWidget.HtmlClassNames = Object.extend(Kekule.ChemWidget.HtmlClassNames, {
EDITOR: 'K-Chem-Editor',
EDITOR_CLIENT: 'K-Chem-Editor-Client',
EDITOR_UIEVENT_RECEIVER: 'K-Chem-Editor-UiEvent-Receiver',
EDITOR2D: 'K-Chem-Editor2D',
EDITOR3D: 'K-Chem-Editor3D'
});
/**
* Namespace for chem editor.
* @namespace
*/
Kekule.ChemWidget.Editor = {};
/**
* Alias to {@link Kekule.ChemWidget.Editor}.
* @namespace
*/
Kekule.Editor = Kekule.ChemWidget.Editor;
/**
* In editor, there exist three types of coord: one based on object system (inner coord),
* another one based on context of editor (outer coord, context coord),
* and the third based on screen.
* This enum is an alias of Kekule.Render.CoordSystem
* @class
*/
Kekule.Editor.CoordSys = Kekule.Render.CoordSystem;
/**
* Enumeration of regions in/out box.
* @enum
* @ignore
*/
Kekule.Editor.BoxRegion = {
OUTSIDE: 0,
CORNER_TL: 1,
CORNER_TR: 2,
CORNER_BL: 3,
CORNER_BR: 4,
EDGE_TOP: 11,
EDGE_LEFT: 12,
EDGE_BOTTOM: 13,
EDGE_RIGHT: 14,
INSIDE: 20
};
/**
* Enumeration of mode in selecting object in editor.
* @enum
* @ignore
*/
Kekule.Editor.SelectMode = {
/** Draw a box in editor when selecting, select all object inside a box. **/
RECT: 0,
/** Draw a curve in editor when selecting, select all object inside this curve polygon. **/
POLYGON: 1,
/** Draw a curve in editor when selecting, select all object intersecting this curve. **/
POLYLINE: 2,
/** Click on a child object to select the whole standalone ancestor. **/
ANCESTOR: 10
};
// add some global options
Kekule.globalOptions.add('chemWidget.editor', {
'enableIssueCheck': true,
'enableCreateNewDoc': true,
'enableOperHistory': true,
'enableOperContext': true,
'initOnNewDoc': true,
'enableSelect': true,
'enableMove': true,
'enableResize': true,
'enableAspectRatioLockedResize': true,
'enableRotate': true,
'enableGesture': true
});
Kekule.globalOptions.add('chemWidget.editor.issueChecker', {
'enableAutoIssueCheck': true,
'enableAutoScrollToActiveIssue': true,
'enableIssueMarkerHint': true,
'durationLimit': 50 // issue check must be finished in 50ms, avoid blocking the UI
});
/**
* A base chem editor.
* @class
* @augments Kekule.ChemWidget.ChemObjDisplayer
* @param {Variant} parentOrElementOrDocument
* @param {Kekule.ChemObject} chemObj initially loaded chemObj.
* @param {Int} renderType Display in 2D or 3D. Value from {@link Kekule.Render.RendererType}.
* @param {Kekule.Editor.BaseEditorConfigs} editorConfigs Configuration of this editor.
*
* @property {Kekule.Editor.BaseEditorConfigs} editorConfigs Configuration of this editor.
* @property {Bool} enableCreateNewDoc Whether create new object in editor is allowed.
* @property {Bool} initOnNewDoc Whether create a new doc when editor instance is initialized.
* Note, the new doc will only be created when property enableCreateNewDoc is true.
* @property {Bool} enableOperHistory Whether undo/redo is enabled.
* @property {Kekule.OperationHistory} operHistory History of operations. Used to enable undo/redo function.
* @property {Int} renderType Display in 2D or 3D. Value from {@link Kekule.Render.RendererType}.
* @property {Kekule.ChemObject} chemObj The root object in editor.
* @property {Bool} enableIssueCheck Whether issue check is available in editor.
* @property {Array} issueCheckerIds Issue checker class IDs used in editor.
* @property {Bool} enableAutoIssueCheck Whether the issue checking is automatically executed when objects changing in editor.
* @property {Array} issueCheckResults Array of {@link Kekule.IssueCheck.CheckResult}, results of auto or manual check.
* @property {Kekule.IssueCheck.CheckResult} activeIssueCheckResult Current selected issue check result in issue inspector.
* @property {Bool} showAllIssueMarkers Whether all issue markers shouled be marked in editor.
* Note, the active issue will always be marked.
* @property {Bool} enableIssueMarkerHint Whether display hint text on issue markers.
* @property {Bool} enableAutoScrollToActiveIssue Whether the editor will automatically scroll to the issue object when selecting in issue inspector.
* @property {Bool} enableOperContext If this property is set to true, object being modified will be drawn in a
* separate context to accelerate the interface refreshing.
* @property {Object} objContext Context to draw basic chem objects. Can be 2D or 3D context. Alias of property drawContext
* @property {Object} operContext Context to draw objects being operated. Can be 2D or 3D context.
* @property {Object} uiContext Context to draw UI marks. Usually this is a 2D context.
* @property {Object} objDrawBridge Bridge to draw chem objects. Alias of property drawBridge.
* @property {Object} uiDrawBridge Bridge to draw UI markers.
* @property {Int} selectMode Value from Kekule.Editor.SelectMode, set the mode of selecting operation in editor.
* @property {Array} selection An array of selected basic object.
* @property {Hash} zoomCenter The center coord (based on client element) when zooming editor.
* //@property {Bool} standardizeObjectsBeforeSaving Whether standardize molecules (and other possible objects) before saving them.
*/
/**
* Invoked when the an chem object is loaded into editor.
* event param of it has one fields: {obj: Object}
* @name Kekule.Editor.BaseEditor#load
* @event
*/
/**
* Invoked when the chem object inside editor is changed.
* event param of it has one fields: {obj: Object, propNames: Array}
* @name Kekule.Editor.BaseEditor#editObjChanged
* @event
*/
/**
* Invoked when multiple chem objects inside editor is changed.
* event param of it has one fields: {details}.
* @name Kekule.Editor.BaseEditor#editObjsChanged
* @event
*/
/**
* Invoked when chem objects inside editor is changed and the changes has been updated by editor.
* event param of it has one fields: {details}.
* Note: this event is not the same as editObjsChanged. When beginUpdateObj is called, editObjsChanged
* event still will be invoked but editObjsUpdated event will be suppressed.
* @name Kekule.Editor.BaseEditor#editObjsUpdated
* @event
*/
/**
* Invoked when the selected objects in editor has been changed.
* When beginUpdateObj is called, selectedObjsUpdated event will be suppressed.
* event param of it has one fields: {objs}.
* @name Kekule.Editor.BaseEditor#selectedObjsUpdated
* @event
*/
/**
* Invoked when the pointer (usually the mouse) hovering on basic objects(s) in editor.
* Event param of it has field {objs}. When the pointer move out of the obj, the objs field will be a empty array.
* @name Kekule.Editor.BaseEditor#hoverOnObjs
* @event
*/
/**
* Invoked when the selection in editor has been changed.
* @name Kekule.Editor.BaseEditor#selectionChange
* @event
*/
/**
* Invoked when the operation history has modifications.
* @name Kekule.Editor.BaseEditor#operChange
* @event
*/
/**
* Invoked when the an operation is pushed into operation history.
* event param of it has one fields: {operation: Kekule.Operation}
* @name Kekule.Editor.BaseEditor#operPush
* @event
*/
/**
* Invoked when the an operation is popped from history.
* event param of it has one fields: {operation: Kekule.Operation}
* @name Kekule.Editor.BaseEditor#operPop
* @event
*/
/**
* Invoked when one operation is undone.
* event param of it has two fields: {operation: Kekule.Operation, currOperIndex: Int}
* @name Kekule.Editor.BaseEditor#operUndo
* @event
*/
/**
* Invoked when one operation is redone.
* event param of it has two fields: {operation: Kekule.Operation, currOperIndex: Int}
* @name Kekule.Editor.BaseEditor#operRedo
* @event
*/
/**
* Invoked when the operation history is cleared.
* event param of it has one field: {currOperIndex: Int}
* @name Kekule.Editor.BaseEditor#operHistoryClear
* @event
*/
Kekule.Editor.BaseEditor = Class.create(Kekule.ChemWidget.ChemObjDisplayer,
/** @lends Kekule.Editor.BaseEditor# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.BaseEditor',
/** @private */
BINDABLE_TAG_NAMES: ['div', 'span'],
/** @private */
OBSERVING_GESTURES: ['rotate', 'rotatestart', 'rotatemove', 'rotateend', 'rotatecancel',
'pinch', 'pinchstart', 'pinchmove', 'pinchend', 'pinchcancel', 'pinchin', 'pinchout'],
/** @constructs */
initialize: function(/*$super, */parentOrElementOrDocument, chemObj, renderType, editorConfigs)
{
this._objSelectFlag = 0; // used internally
this._objectUpdateFlag = 0; // used internally
this._objectManipulateFlag = 0; // used internally
this._uiMarkerUpdateFlag = 0; // used internally
this._updatedObjectDetails = []; // used internally
this._operatingObjs = []; // used internally
this._operatingRenderers = []; // used internally
this._initialRenderTransformParams = null; // used internally, must init before $super
// as in $super, chemObj may be loaded and _initialRenderTransformParams will be set at that time
this._objChanged = false; // used internally, mark whether some changes has been made to chem object
this._lengthCaches = {}; // used internally, stores some value related to distance and length
var getOptionValue = Kekule.globalOptions.get;
/*
this.setPropStoreFieldValue('enableIssueCheck', true);
this.setPropStoreFieldValue('enableCreateNewDoc', true);
this.setPropStoreFieldValue('enableOperHistory', true);
this.setPropStoreFieldValue('enableOperContext', true);
this.setPropStoreFieldValue('initOnNewDoc', true);
*/
this.setPropStoreFieldValue('enableIssueCheck', getOptionValue('chemWidget.editor.enableIssueCheck', true));
this.setPropStoreFieldValue('enableCreateNewDoc', getOptionValue('chemWidget.editor.enableCreateNewDoc', true));
this.setPropStoreFieldValue('enableOperHistory', getOptionValue('chemWidget.editor.enableOperHistory', true));
this.setPropStoreFieldValue('enableOperContext', getOptionValue('chemWidget.editor.enableOperContext', true));
this.setPropStoreFieldValue('initOnNewDoc', getOptionValue('chemWidget.editor.initOnNewDoc', true));
//this.setPropStoreFieldValue('initialZoom', 1.5);
//this.setPropStoreFieldValue('selectMode', Kekule.Editor.SelectMode.POLYGON); // debug
this.tryApplySuper('initialize', [parentOrElementOrDocument, chemObj, renderType]) /* $super(parentOrElementOrDocument, chemObj, renderType) */;
//this.initEventHandlers();
if (!this.getChemObj() && this.getInitOnNewDoc() && this.getEnableCreateNewDoc())
this.newDoc();
this.setPropStoreFieldValue('editorConfigs', editorConfigs || this.createDefaultConfigs());
//this.setPropStoreFieldValue('uiMarkers', []);
//this.setEnableGesture(true);
this.setEnableGesture(getOptionValue('chemWidget.editor.enableGesture', true));
},
/** @private */
initProperties: function()
{
this.defineProp('editorConfigs', {'dataType': 'Kekule.Editor.BaseEditorConfigs', 'serializable': false,
'getter': function() { return this.getDisplayerConfigs(); },
'setter': function(value) { return this.setDisplayerConfigs(value); }
});
this.defineProp('defBondLength', {'dataType': DataType.FLOAT, 'serializable': false,
'getter': function()
{
var result = this.getPropStoreFieldValue('defBondLength');
if (!result)
result = this.getEditorConfigs().getStructureConfigs().getDefBondLength();
return result;
}
});
this.defineProp('defBondScreenLength', {'dataType': DataType.FLOAT, 'serializable': false, 'setter': null,
'getter': function()
{
/*
var result = this.getPropStoreFieldValue('defBondScreenLength');
if (!result)
{
var bLength = this.getDefBondLength();
result = this.translateDistance(bLength, Kekule.Render.CoordSys.CHEM, Kekule.Render.CoordSys.SCREEN);
}
return result;
*/
var cached = this._lengthCaches.defBondScreenLength;
if (cached)
return cached;
else
{
var bLength = this.getDefBondLength() || 0;
var result = this.translateDistance(bLength, Kekule.Render.CoordSystem.CHEM, Kekule.Render.CoordSystem.SCREEN);
this._lengthCaches.defBondScreenLength = result;
return result;
}
}
});
// Different pointer event (mouse, touch) has different bound inflation settings, stores here
this.defineProp('currBoundInflation', {'dataType': DataType.NUMBER, 'serializable': false, 'setter': null,
'getter': function(){
var pType = this.getCurrPointerType();
return this.getInteractionBoundInflation(pType);
}
});
// The recent pointer device interacted with this editor
this.defineProp('currPointerType', {'dataType': DataType.STRING, 'serializable': false});
//this.defineProp('standardizeObjectsBeforeSaving', {'dataType': DataType.BOOL});
this.defineProp('enableCreateNewDoc', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('initOnNewDoc', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('enableOperHistory', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('operHistory', {
'dataType': 'Kekule.OperationHistory', 'serializable': false,
'getter': function()
{
/*
if (!this.getEnableOperHistory())
return null;
*/
var result = this.getPropStoreFieldValue('operHistory');
if (!result)
{
result = new Kekule.OperationHistory();
this.setPropStoreFieldValue('operHistory', result);
// install event handlers
result.addEventListener('push', this.reactOperHistoryPush, this);
result.addEventListener('pop', this.reactOperHistoryPop, this);
result.addEventListener('undo', this.reactOperHistoryUndo, this);
result.addEventListener('redo', this.reactOperHistoryRedo, this);
result.addEventListener('clear', this.reactOperHistoryClear, this);
result.addEventListener('change', this.reactOperHistoryChange, this);
}
return result;
},
'setter': null
});
this.defineProp('operationsInCurrManipulation', {'dataType': DataType.ARRAY, 'scope': Class.PropertyScope.PRIVATE, 'serializable': false}); // private
this.defineProp('selection', {'dataType': DataType.ARRAY, 'serializable': false,
'getter': function()
{
var result = this.getPropStoreFieldValue('selection');
if (!result)
{
result = [];
this.setPropStoreFieldValue('selection', result);
}
return result;
},
'setter': function(value)
{
this.setPropStoreFieldValue('selection', value);
this.selectionChanged();
}
});
this.defineProp('selectMode', {'dataType': DataType.INT,
'getter': function()
{
var result = this.getPropStoreFieldValue('selectMode');
if (Kekule.ObjUtils.isUnset(result))
result = Kekule.Editor.SelectMode.RECT; // default value
return result;
},
'setter': function(value)
{
if (this.getSelectMode() !== value)
{
//console.log('set select mode', value);
this.setPropStoreFieldValue('selectMode', value);
this.hideSelectingMarker();
}
}
});
// private, whether defaultly select in toggle mode
this.defineProp('isToggleSelectOn', {'dataType': DataType.BOOL});
this.defineProp('hotTrackedObjs', {'dataType': DataType.ARRAY, 'serializable': false,
'setter': function(value)
{
/*
if (this.getHotTrackedObjs() === value)
return;
*/
var objs = value? Kekule.ArrayUtils.toArray(value): [];
//console.log('setHotTrackedObjs', objs);
if (this.getEditorConfigs() && this.getEditorConfigs().getInteractionConfigs().getEnableHotTrack())
{
this.setPropStoreFieldValue('hotTrackedObjs', objs);
var bounds;
if (objs && objs.length)
{
bounds = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var bound = this.getBoundInfoRecorder().getBound(this.getObjContext(), objs[i]);
if (bounds)
{
//bounds.push(bound);
Kekule.ArrayUtils.pushUnique(bounds, bound); // bound may be an array of composite shape
}
}
}
if (bounds)
{
this.changeHotTrackMarkerBounds(bounds);
//console.log('show');
}
else
{
if (this.getUiHotTrackMarker().getVisible())
this.hideHotTrackMarker();
//console.log('hide');
}
}
}
});
this.defineProp('hotTrackedObj', {'dataType': DataType.OBJECT, 'serializable': false,
'getter': function() { return this.getHotTrackedObjs() && this.getHotTrackedObjs()[0]; },
'setter': function(value) { this.setHotTrackedObjs(value); }
});
this.defineProp('hoveredBasicObjs', {'dataType': DataType.ARRAY, 'serializable': false}); // a readonly array caching the basic objects at current pointer position
this.defineProp('enableOperContext', {'dataType': DataType.BOOL,
'setter': function(value)
{
this.setPropStoreFieldValue('enableOperContext', !!value);
if (!value) // release operContext
{
var ctx = this.getPropStoreFieldValue('operContext');
var b = this.getPropStoreFieldValue('drawBridge');
if (b && ctx)
b.releaseContext(ctx);
}
}
});
this.defineProp('issueCheckExecutor', {'dataType': 'Kekule.IssueCheck.Executor', 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('issueCheckExecutor');
if (!result) // create default executor
{
result = this.createIssueCheckExecutor(); // new Kekule.IssueCheck.Executor();
var self = this;
result.addEventListener('execute', function(e){
self.setIssueCheckResults(e.checkResults);
});
this.setPropStoreFieldValue('issueCheckExecutor', result);
}
return result;
}
});
this.defineProp('issueCheckerIds', {'dataType': DataType.ARRAY,
'getter': function() { return this.getIssueCheckExecutor().getCheckerIds(); },
'setter': function(value) { this.getIssueCheckExecutor().setCheckerIds(value); }
});
this.defineProp('enableIssueCheck', {'dataType': DataType.BOOL,
'getter': function() { return this.getIssueCheckExecutor().getEnabled(); },
'setter': function(value) {
this.getIssueCheckExecutor().setEnabled(!!value);
if (!value) // when disable issue check, clear the check results
{
this.setIssueCheckResults(null);
}
}
});
this.defineProp('issueCheckDurationLimit', {'dataType': DataType.NUMBER,
'getter': function() { return this.getIssueCheckExecutor().getDurationLimit(); },
'setter': function(value) { this.getIssueCheckExecutor().setDurationLimit(value); }
});
this.defineProp('enableAutoIssueCheck', {'dataType': DataType.BOOL,
'setter': function(value)
{
if (!!value !== this.getEnableAutoIssueCheck())
{
this.setPropStoreFieldValue('enableAutoIssueCheck', !!value);
if (value) // when turn on from off, do a issue check
this.checkIssues();
// adjust property showAllIssueMarkers according to enableAutoIssueCheck
// If auto check is on, markers should be defaultly opened;
// if auto check is off, markers should be defaultly hidden.
this.setShowAllIssueMarkers(!!value);
}
}});
this.defineProp('issueCheckResults', {'dataType': DataType.ARRAY, 'serializable': false,
'setter': function(value)
{
var oldActive = this.getActiveIssueCheckResult();
this.setPropStoreFieldValue('issueCheckResults', value);
if (oldActive && (value || []).indexOf(oldActive) < 0)
this.setPropStoreFieldValue('activeIssueCheckResult', null);
this.issueCheckResultsChanged();
}
});
this.defineProp('activeIssueCheckResult', {'dataType': DataType.OBJECT, 'serializable': false,
'setter': function(value)
{
if (this.getActiveIssueCheckResult() !== value)
{
this.setPropStoreFieldValue('activeIssueCheckResult', value);
if (value) // when set active issue, deselect all selections to extrusive it
this.deselectAll();
this.issueCheckResultsChanged();
}
}
});
this.defineProp('enableAutoScrollToActiveIssue', {'dataType': DataType.BOOL});
this.defineProp('showAllIssueMarkers', {'dataType': DataType.BOOL,
'setter': function(value)
{
if (!!value !== this.getShowAllIssueMarkers())
{
this.setPropStoreFieldValue('showAllIssueMarkers', !!value);
this.recalcIssueCheckUiMarkers();
}
}
});
this.defineProp('enableIssueMarkerHint', {'dataType': DataType.BOOL});
this.defineProp('enableGesture', {'dataType': DataType.BOOL,
'setter': function(value)
{
var bValue = !!value;
if (this.getEnableGesture() !== bValue)
{
this.setPropStoreFieldValue('enableGesture', bValue);
if (bValue)
{
this.startObservingGestureEvents(this.OBSERVING_GESTURES);
}
else
{
this.startObservingGestureEvents(this.OBSERVING_GESTURES);
}
}
}
});
// private
this.defineProp('uiEventReceiverElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null});
// context parent properties, private
this.defineProp('objContextParentElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null});
this.defineProp('operContextParentElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null});
this.defineProp('uiContextParentElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null});
this.defineProp('objContext', {'dataType': DataType.OBJECT, 'serializable': false, setter: null,
'getter': function() { return this.getDrawContext(); }
});
this.defineProp('operContext', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null,
'getter': function()
{
if (!this.getEnableOperContext())
return null;
else
{
var result = this.getPropStoreFieldValue('operContext');
if (!result)
{
var bridge = this.getDrawBridge();
if (bridge)
{
var elem = this.getOperContextParentElem();
if (!elem)
return null;
else
{
var dim = Kekule.HtmlElementUtils.getElemScrollDimension(elem);
result = bridge.createContext(elem, dim.width, dim.height);
this.setPropStoreFieldValue('operContext', result);
}
}
}
return result;
}
}
});
this.defineProp('uiContext', {'dataType': DataType.OBJECT, 'serializable': false,
'getter': function()
{
var result = this.getPropStoreFieldValue('uiContext');
if (!result)
{
var bridge = this.getUiDrawBridge();
if (bridge)
{
var elem = this.getUiContextParentElem();
if (!elem)
return null;
else
{
var dim = Kekule.HtmlElementUtils.getElemScrollDimension(elem);
//var dim = Kekule.HtmlElementUtils.getElemClientDimension(elem);
result = bridge.createContext(elem, dim.width, dim.height);
this.setPropStoreFieldValue('uiContext', result);
}
}
}
return result;
}
});
this.defineProp('objDrawBridge', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null,
'getter': function() { return this.getDrawBridge(); }
});
this.defineProp('uiDrawBridge', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('uiDrawBridge');
if (!result && !this.__$uiDrawBridgeInitialized$__)
{
this.__$uiDrawBridgeInitialized$__ = true;
result = this.createUiDrawBridge();
this.setPropStoreFieldValue('uiDrawBridge', result);
}
return result;
}
});
this.defineProp('uiPainter', {'dataType': 'Kekule.Render.ChemObjPainter', 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('uiPainter');
if (!result)
{
// ui painter will always in 2D mode
var markers = this.getUiMarkers();
result = new Kekule.Render.ChemObjPainter(Kekule.Render.RendererType.R2D, markers, this.getUiDrawBridge());
result.setCanModifyTargetObj(true);
this.setPropStoreFieldValue('uiPainter', result);
return result;
}
return result;
}
});
this.defineProp('uiRenderer', {'dataType': 'Kekule.Render.AbstractRenderer', 'serializable': false, 'setter': null,
'getter': function()
{
var p = this.getUiPainter();
if (p)
{
var r = p.getRenderer();
if (!r)
p.prepareRenderer();
return p.getRenderer() || null;
}
else
return null;
}
});
// private ui marks properties
//this.defineProp('uiMarkers', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': null});
this.defineProp('uiMarkers', {'dataType': 'Kekule.ChemWidget.UiMarkerCollection', 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('uiMarkers');
if (!result)
{
result = new Kekule.ChemWidget.UiMarkerCollection();
this.setPropStoreFieldValue('uiMarkers', result);
}
return result;
}
});
/*
this.defineProp('uiHotTrackMarker', {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false,
'getter': function() { return this.getUiMarkers().hotTrackMarker; },
'setter': function(value) { this.getUiMarkers().hotTrackMarker = value; }
});
this.defineProp('uiSelectionAreaMarker', {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false,
'getter': function() { return this.getUiMarkers().selectionAreaMarker; },
'setter': function(value) { this.getUiMarkers().selectionAreaMarker = value; }
});
this.defineProp('uiSelectingMarker', {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false,
'getter': function() { return this.getUiMarkers().selectingMarker; },
'setter': function(value) { this.getUiMarkers().selectingMarker = value; }
}); // marker of selecting rubber band
*/
this._defineUiMarkerProp('uiHotTrackMarker');
this._defineUiMarkerProp('uiSelectionAreaMarker'); // marker of selected range
this._defineUiMarkerProp('uiSelectingMarker'); // marker of selecting rubber band
this._defineIssueCheckUiMarkerGroupProps(); // error check marker group
this.defineProp('uiSelectionAreaContainerBox',
{'dataType': DataType.Object, 'serializable': false, 'scope': Class.PropertyScope.PRIVATE});
// a private chemObj-renderer map
this.defineProp('objRendererMap', {'dataType': 'Kekule.MapEx', 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('objRendererMap');
if (!result)
{
result = new Kekule.MapEx(true);
this.setPropStoreFieldValue('objRendererMap', result);
}
return result;
}
});
// private object to record all bound infos
//this.defineProp('boundInfoRecorder', {'dataType': 'Kekule.Render.BoundInfoRecorder', 'serializable': false, 'setter': null});
this.defineProp('zoomCenter', {'dataType': DataType.HASH});
},
/** @ignore */
initPropValues: function(/*$super*/)
{
this.tryApplySuper('initPropValues') /* $super() */;
this.setOperationsInCurrManipulation([]);
/*
this.setEnableAutoIssueCheck(false);
this.setEnableAutoScrollToActiveIssue(true);
var ICIDs = Kekule.IssueCheck.CheckerIds;
this.setIssueCheckerIds([ICIDs.ATOM_VALENCE, ICIDs.BOND_ORDER, ICIDs.NODE_DISTANCE_2D]);
*/
var ICIDs = Kekule.IssueCheck.CheckerIds;
var getGlobalOptionValue = Kekule.globalOptions.get;
this.setEnableAutoIssueCheck(getGlobalOptionValue('chemWidget.editor.issueChecker.enableAutoIssueCheck', true));
this.setEnableAutoScrollToActiveIssue(getGlobalOptionValue('chemWidget.editor.issueChecker.enableAutoScrollToActiveIssue', true));
this.setIssueCheckerIds(getGlobalOptionValue('chemWidget.editor.issueChecker.issueCheckerIds', [ICIDs.ATOM_VALENCE, ICIDs.BOND_ORDER, ICIDs.NODE_DISTANCE_2D]));
this.setIssueCheckDurationLimit(getGlobalOptionValue('chemWidget.editor.issueChecker.durationLimit') || null);
this.setEnableIssueMarkerHint(getGlobalOptionValue('chemWidget.editor.issueChecker.enableIssueMarkerHint') || this.getEnableAutoIssueCheck());
},
/** @private */
_defineUiMarkerProp: function(propName, uiMarkerCollection)
{
return this.defineProp(propName, {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false,
'getter': function()
{
var result = this.getPropStoreFieldValue(propName);
if (!result)
{
result = this.createShapeBasedMarker(propName, null, null, false); // prop value already be set in createShapeBasedMarker method
}
return result;
},
'setter': function(value)
{
if (!uiMarkerCollection)
uiMarkerCollection = this.getUiMarkers();
var old = this.getPropValue(propName);
if (old)
{
uiMarkerCollection.removeMarker(old);
old.finalize();
}
uiMarkerCollection.addMarker(value);
this.setPropStoreFieldValue(propName, value);
}
});
},
/** @private */
_defineIssueCheckUiMarkerGroupProps: function(uiMarkerCollection)
{
var EL = Kekule.ErrorLevel;
var getSubPropName = function(baseName, errorLevel)
{
return baseName + '_' + EL.levelToString(errorLevel);
};
var baseName = 'issueCheckUiMarker';
var errorLevels = [EL.ERROR, EL.WARNING, EL.NOTE, EL.LOG];
for (var i = 0, l = errorLevels.length; i < l; ++i)
{
var pname = getSubPropName(baseName, errorLevels[i]);
this._defineUiMarkerProp(pname, uiMarkerCollection);
}
this._defineUiMarkerProp(baseName + '_active', uiMarkerCollection); // 'active' is special marker to mark the selected issue objects
// define getter/setter method for group
this['get' + baseName.upperFirst()] = function(level){
var p = getSubPropName(baseName, level);
return this.getPropValue(p);
};
this['set' + baseName.upperFirst()] = function(level, value){
var p = getSubPropName(baseName, level);
return this.setPropValue(p, value);
};
this['getActive' + baseName.upperFirst()] = function()
{
return this.getPropValue(baseName + '_active');
};
this['getAll' + baseName.upperFirst() + 's'] = function(){
var result = [];
for (var i = 0, l = errorLevels.length; i < l; ++i)
{
result.push(this.getIssueCheckUiMarker(errorLevels[i]));
}
var activeMarker = this.getActiveIssueCheckUiMarker();
if (activeMarker)
result.push(activeMarker);
return result;
}
},
/** @private */
doFinalize: function(/*$super*/)
{
var h = this.getPropStoreFieldValue('operHistory');
if (h)
{
h.finalize();
this.setPropStoreFieldValue('operHistory', null);
}
var b = this.getPropStoreFieldValue('objDrawBridge');
var ctx = this.getPropStoreFieldValue('operContext');
if (b && ctx)
{
b.releaseContext(ctx);
}
this.setPropStoreFieldValue('operContext', null);
var b = this.getPropStoreFieldValue('uiDrawBridge');
var ctx = this.getPropStoreFieldValue('uiContext');
if (b && ctx)
{
b.releaseContext(ctx);
}
this.setPropStoreFieldValue('uiDrawBridge', null);
this.setPropStoreFieldValue('uiContext', null);
var m = this.getPropStoreFieldValue('objRendererMap');
if (m)
m.finalize();
this.setPropStoreFieldValue('objRendererMap', null);
var e = this.getPropStoreFieldValue('issueCheckExecutor');
if (e)
e.finalize();
this.setPropStoreFieldValue('issueCheckExecutor', null);
this.tryApplySuper('doFinalize') /* $super() */;
},
/** @ignore */
elementBound: function(element)
{
this.setObserveElemResize(true);
},
/**
* Create a default editor config object.
* Descendants may override this method.
* @returns {Kekule.Editor.BaseEditorConfigs}
* @ignore
*/
createDefaultConfigs: function()
{
return new Kekule.Editor.BaseEditorConfigs();
},
/** @ignore */
doCreateRootElement: function(doc)
{
var result = doc.createElement('div');
return result;
},
/** @ignore */
doCreateSubElements: function(doc, rootElem)
{
var elem = doc.createElement('div');
elem.className = CCNS.EDITOR_CLIENT;
rootElem.appendChild(elem);
this._editClientElem = elem;
return [elem];
},
/** @ignore */
getCoreElement: function(/*$super*/)
{
return this._editClientElem || this.tryApplySuper('getCoreElement') /* $super() */;
},
/** @private */
getEditClientElem: function()
{
return this._editClientElem;
},
/** @ignore */
doGetWidgetClassName: function(/*$super*/)
{
var result = this.tryApplySuper('doGetWidgetClassName') /* $super() */ + ' ' + CCNS.EDITOR;
var additional = (this.getRenderType() === Kekule.Render.RendererType.R3D)?
CCNS.EDITOR3D: CCNS.EDITOR2D;
result += ' ' + additional;
return result;
},
/** @private */
doBindElement: function(element)
{
this.createContextParentElems();
this.createUiEventReceiverElem();
},
// override getter and setter of intialZoom property
/** @ignore */
doGetInitialZoom: function(/*$super*/)
{
var result;
var config = this.getEditorConfigs();
if (config)
result = config.getInteractionConfigs().getEditorInitialZoom();
if (!result)
result = this.tryApplySuper('doGetInitialZoom') /* $super() */;
return result;
},
/** @ignore */
doSetInitialZoom: function(/*$super, */value)
{
var config = this.getEditorConfigs();
if (config)
config.getInteractionConfigs().setEditorInitialZoom(value);
this.tryApplySuper('doSetInitialZoom', [value]) /* $super(value) */;
},
/** @ignore */
zoomTo: function(/*$super, */value, suspendRendering, zoomCenterCoord)
{
var CU = Kekule.CoordUtils;
var currZoomLevel = this.getCurrZoom();
var zoomLevel = value;
var result = this.tryApplySuper('zoomTo', [value, suspendRendering]) /* $super(value, suspendRendering) */;
// adjust zoom center
var selfElem = this.getElement();
var currScrollCoord = {'x': selfElem.scrollLeft, 'y': selfElem.scrollTop};
if (!zoomCenterCoord)
zoomCenterCoord = this.getZoomCenter();
if (!zoomCenterCoord ) // use the center of client as the zoom center
{
zoomCenterCoord = CU.add(currScrollCoord, {'x': selfElem.clientWidth / 2, 'y': selfElem.clientHeight / 2});
}
//console.log('zoom center info', this.getZoomCenter(), zoomCenterCoord);
//if (zoomCenterCoord)
{
var scrollDelta = CU.multiply(zoomCenterCoord, zoomLevel / currZoomLevel - 1);
selfElem.scrollLeft += scrollDelta.x;
selfElem.scrollTop += scrollDelta.y;
}
return result;
},
/**
* Zoom in.
*/
/*
zoomIn: function(step, zoomCenterCoord)
{
var curr = this.getCurrZoom();
var ratio = Kekule.ZoomUtils.getNextZoomInRatio(curr, step || 1);
return this.zoomTo(ratio, null, zoomCenterCoord);
},
*/
/**
* Zoom out.
*/
/*
zoomOut: function(step, zoomCenterCoord)
{
var curr = this.getCurrZoom();
var ratio = Kekule.ZoomUtils.getNextZoomOutRatio(curr, step || 1);
return this.zoomTo(ratio, null, zoomCenterCoord);
},
*/
/**
* Reset to normal size.
*/
/*
resetZoom: function(zoomCenterCoord)
{
return this.zoomTo(this.getInitialZoom() || 1, null, zoomCenterCoord);
},
*/
/**
* Change the size of client element.
* Width and height is based on px.
* @private
*/
changeClientSize: function(width, height, zoomLevel)
{
this._initialRenderTransformParams = null;
var elem = this.getCoreElement();
var style = elem.style;
if (!zoomLevel)
zoomLevel = 1;
var w = width * zoomLevel;
var h = height * zoomLevel;
if (w)
style.width = w + 'px';
if (h)
style.height = h + 'px';
var ctxes = [this.getObjContext(), this.getOperContext(), this.getUiContext()];
for (var i = 0, l = ctxes.length; i < l; ++i)
{
var ctx = ctxes[i];
if (ctx) // change ctx size also
{
this.getDrawBridge().setContextDimension(ctx, w, h);
}
}
this.repaint();
},
/**
* Returns the screen box (x1, y1, x2, y2) of current visible client area in editor.
* @returns {Hash}
*/
getVisibleClientScreenBox: function()
{
var elem = this.getEditClientElem().parentNode;
var result = Kekule.HtmlElementUtils.getElemClientDimension(elem);
var pos = this.getClientScrollPosition();
result.x1 = pos.x;
result.y1 = pos.y;
result.x2 = result.x1 + result.width;
result.y2 = result.y1 + result.height;
return result;
},
/**
* Returns the context box (x1, y1, x2, y2, in a specified coord system) of current visible client area in editor.
* @param {Int} coordSys
* @returns {Hash}
*/
getVisibleClientBoxOfSys: function(coordSys)
{
var screenBox = this.getVisibleClientScreenBox();
var coords = Kekule.BoxUtils.getMinMaxCoords(screenBox);
var c1 = this.translateCoord(coords.min, Kekule.Editor.CoordSys.SCREEN, coordSys);
var c2 = this.translateCoord(coords.max, Kekule.Editor.CoordSys.SCREEN, coordSys);
var result = Kekule.BoxUtils.createBox(c1, c2);
return result;
},
/**
* Returns the context box (x1, y1, x2, y2, in object coord system) of current visible client area in editor.
* @param {Int} coordSys
* @returns {Hash}
*/
getVisibleClientObjBox: function(coordSys)
{
return this.getVisibleClientBoxOfSys(Kekule.Editor.CoordSys.CHEM);
},
/**
* Returns whether the chem object inside editor has been modified since load.
* @returns {Bool}
*/
isDirty: function()
{
if (this.getEnableOperHistory())
return this.getOperHistory().getCurrIndex() >= 0;
else
return this._objChanged;
},
/**
* Returns srcInfo of chemObj. If editor is dirty (object been modified), srcInfo will be unavailable.
* @param {Kekule.ChemObject} chemObj
* @returns {Object}
*/
getChemObjSrcInfo: function(chemObj)
{
if (this.isDirty())
return null;
else
return chemObj.getSrcInfo? chemObj.getSrcInfo(): null;
},
/* @private */
/*
_calcPreferedTransformOptions: function()
{
var drawOptions = this.getDrawOptions();
return this.getPainter().calcPreferedTransformOptions(
this.getObjContext(), this.calcDrawBaseCoord(drawOptions), drawOptions);
},
*/
/** @private */
getActualDrawOptions: function(/*$super*/)
{
var old = this.tryApplySuper('getActualDrawOptions') /* $super() */;
if (this._initialRenderTransformParams)
{
var result = Object.extend({}, this._initialRenderTransformParams);
result = Object.extend(result, old);
//var result = Object.create(old);
//result.initialRenderTransformParams = this._initialRenderTransformParams;
//console.log('extended', this._initialRenderTransformParams, result);
return result;
}
else
return old;
},
/** @ignore */
/*
getDrawClientDimension: function()
{
},
*/
/** @ignore */
repaint: function(/*$super, */overrideOptions)
{
var ops = overrideOptions;
//console.log('repaint called', overrideOptions);
//console.log('repaint', this._initialRenderTransformParams);
/*
if (this._initialRenderTransformParams)
{
ops = Object.create(overrideOptions || {});
//console.log(this._initialRenderTransformParams);
ops = Object.extend(ops, this._initialRenderTransformParams);
}
else
{
ops = overrideOptions;
//this._initialRenderTransformParams = this._calcPreferedTransformOptions();
//console.log('init params: ', this._initialRenderTransformParams, drawOptions);
}
*/
var result = this.tryApplySuper('repaint', [ops]) /* $super(ops) */;
if (this.isRenderable())
{
// after paint the new obj the first time, save up the transform params (especially the translates)
if (!this._initialRenderTransformParams)
{
this._initialRenderTransformParams = this.getPainter().getActualInitialRenderTransformOptions(this.getObjContext());
/*
if (transParam)
{
var trans = {}
var unitLength = transParam.unitLength || 1;
if (Kekule.ObjUtils.notUnset(transParam.translateX))
trans.translateX = transParam.translateX / unitLength;
if (Kekule.ObjUtils.notUnset(transParam.translateY))
trans.translateY = transParam.translateY / unitLength;
if (Kekule.ObjUtils.notUnset(transParam.translateZ))
trans.translateZ = transParam.translateZ / unitLength;
if (transParam.center)
trans.center = transParam.center;
//var zoom = transParam.zoom || 1;
var zoom = 1;
trans.scaleX = transParam.scaleX / zoom;
trans.scaleY = transParam.scaleY / zoom;
trans.scaleZ = transParam.scaleZ / zoom;
this._initialRenderTransformParams = trans;
console.log(this._initialRenderTransformParams, this);
}
*/
}
// redraw ui markers
this.recalcUiMarkers();
}
return result;
},
/**
* Create a new object and load it in editor.
*/
newDoc: function()
{
//if (this.getEnableCreateNewDoc()) // enable property only affects UI, always could create new doc in code
this.load(this.doCreateNewDocObj());
},
/**
* Create a new object for new document.
* Descendants may override this method.
* @private
*/
doCreateNewDocObj: function()
{
return new Kekule.Molecule();
},
/**
* Returns array of classes that can be exported (saved) from editor.
* Descendants can override this method.
* @returns {Array}
*/
getExportableClasses: function()
{
var obj = this.getChemObj();
if (!obj)
return [];
else
return obj.getClass? [obj.getClass()]: [];
},
/**
* Returns exportable object for specified class.
* Descendants can override this method.
* @param {Class} objClass Set null to export default object.
* @returns {Object}
*/
exportObj: function(objClass)
{
return this.exportObjs(objClass)[0];
},
/**
* Returns all exportable objects for specified class.
* Descendants can override this method.
* @param {Class} objClass Set null to export default object.
* @returns {Array}
*/
exportObjs: function(objClass)
{
var obj = this.getChemObj();
if (!objClass)
return [obj];
else
{
return (obj && (obj instanceof objClass))? [obj]: [];
}
},
/** @private */
doLoad: function(/*$super, */chemObj)
{
// deselect all old objects first
this.deselectAll();
this._initialRenderTransformParams = null;
// clear rendererMap so that all old renderer info is removed
this.getObjRendererMap().clear();
if (this.getOperHistory())
this.getOperHistory().clear();
this.tryApplySuper('doLoad', [chemObj]) /* $super(chemObj) */;
this._objChanged = false;
// clear hovered object cache
this.setPropStoreFieldValue('hoveredBasicObjs', null);
// clear issue results
this.setIssueCheckResults(null);
this.requestAutoCheckIssuesIfNecessary();
},
/** @private */
doLoadEnd: function(/*$super, */chemObj)
{
this.tryApplySuper('doLoadEnd') /* $super() */;
//console.log('loadend: ', chemObj);
if (!chemObj)
this._initialRenderTransformParams = null;
/*
else
{
// after load the new obj the first time, save up the transform params (especially the translates)
var transParam = this.getPainter().getActualRenderTransformParams(this.getObjContext());
if (transParam)
{
var trans = {}
var unitLength = transParam.unitLength || 1;
if (Kekule.ObjUtils.notUnset(transParam.translateX))
trans.translateX = transParam.translateX / unitLength;
if (Kekule.ObjUtils.notUnset(transParam.translateY))
trans.translateY = transParam.translateY / unitLength;
if (Kekule.ObjUtils.notUnset(transParam.translateZ))
trans.translateZ = transParam.translateZ / unitLength;
this._initialRenderTransformParams = trans;
console.log(this._initialRenderTransformParams, this);
}
}
*/
},
/** @private */
doResize: function(/*$super*/)
{
//console.log('doResize');
this._initialRenderTransformParams = null; // transform should be recalculated after resize
this.tryApplySuper('doResize') /* $super() */;
},
/** @ignore */
geometryOptionChanged: function(/*$super*/)
{
var zoom = this.getDrawOptions().zoom;
this.zoomChanged(zoom);
// clear some length related caches
this._clearLengthCaches();
this.tryApplySuper('geometryOptionChanged') /* $super() */;
},
/** @private */
zoomChanged: function(zoomLevel)
{
// do nothing here
},
/** @private */
_clearLengthCaches: function()
{
this._lengthCaches = {};
},
/**
* @private
*/
chemObjChanged: function(/*$super, */newObj, oldObj)
{
this.tryApplySuper('chemObjChanged', [newObj, oldObj]) /* $super(newObj, oldObj) */;
if (newObj !== oldObj)
{
if (oldObj)
this._uninstallChemObjEventListener(oldObj);
if (newObj)
this._installChemObjEventListener(newObj);
}
},
/** @private */
_installChemObjEventListener: function(chemObj)
{
chemObj.addEventListener('change', this.reactChemObjChange, this);
},
/** @private */
_uninstallChemObjEventListener: function(chemObj)
{
chemObj.removeEventListener('change', this.reactChemObjChange, this);
},
/**
* Create a transparent div element above all other elems of editor,
* this element is used to receive all UI events.
*/
createUiEventReceiverElem: function()
{
var parent = this.getCoreElement();
if (parent)
{
var result = parent.ownerDocument.createElement('div');
result.className = CCNS.EDITOR_UIEVENT_RECEIVER;
/*
result.id = 'overlayer';
*/
/*
var style = result.style;
style.background = 'transparent';
//style.background = 'yellow';
//style.opacity = 0;
style.position = 'absolute';
style.left = 0;
style.top = 0;
style.width = '100%';
style.height = '100%';
*/
//style.zIndex = 1000;
parent.appendChild(result);
EU.addClass(result, CNS.DYN_CREATED);
this.setPropStoreFieldValue('uiEventReceiverElem', result);
return result;
}
},
/** @private */
createContextParentElems: function()
{
var parent = this.getCoreElement();
if (parent)
{
var doc = parent.ownerDocument;
this._createContextParentElem(doc, parent, 'objContextParentElem');
this._createContextParentElem(doc, parent, 'operContextParentElem');
this._createContextParentElem(doc, parent, 'uiContextParentElem');
}
},
/** @private */
_createContextParentElem: function(doc, parentElem, contextElemPropName)
{
var result = doc.createElement('div');
result.style.position = 'absolute';
result.style.width = '100%';
result.style.height = '100%';
result.className = contextElemPropName + ' ' + CNS.DYN_CREATED; // debug
this.setPropStoreFieldValue(contextElemPropName, result);
parentElem.appendChild(result);
return result;
},
/** @private */
createNewPainter: function(/*$super, */chemObj)
{
var result = this.tryApplySuper('createNewPainter', [chemObj]) /* $super(chemObj) */;
if (result)
{
result.setCanModifyTargetObj(true);
this.installPainterEventHandlers(result);
/* Moved up to class ChemObjDisplayer
// create new bound info recorder
this.createNewBoundInfoRecorder(this.getPainter());
*/
}
return result;
},
/** @private */
/* Moved up to class ChemObjDisplayer
createNewBoundInfoRecorder: function(renderer)
{
var old = this.getPropStoreFieldValue('boundInfoRecorder');
if (old)
old.finalize();
var recorder = new Kekule.Render.BoundInfoRecorder(renderer);
//recorder.setTargetContext(this.getObjContext());
this.setPropStoreFieldValue('boundInfoRecorder', recorder);
},
*/
/** @private */
getDrawContextParentElem: function()
{
return this.getObjContextParentElem();
},
/** @private */
createUiDrawBridge: function()
{
// UI marker will always be in 2D
var result = Kekule.Render.DrawBridge2DMananger.getPreferredBridgeInstance();
if (!result) // can not find suitable draw bridge
{
//Kekule.error(Kekule.$L('ErrorMsg.DRAW_BRIDGE_NOT_SUPPORTED'));
var errorMsg = Kekule.Render.DrawBridge2DMananger.getUnavailableMessage() || Kekule.error(Kekule.$L('ErrorMsg.DRAW_BRIDGE_NOT_SUPPORTED'));
if (errorMsg)
this.reportException(errorMsg, Kekule.ExceptionLevel.NOT_FATAL_ERROR);
}
return result;
},
/* @private */
/*
refitDrawContext: function($super, doNotRepaint)
{
//var dim = Kekule.HtmlElementUtils.getElemScrollDimension(this.getElement());
var dim = Kekule.HtmlElementUtils.getElemClientDimension(this.getElement());
//this._resizeContext(this.getObjDrawContext(), this.getObjDrawBridge(), dim.width, dim.height);
this._resizeContext(this.getOperContext(), this.getObjDrawBridge(), dim.width, dim.height);
this._resizeContext(this.getUiContext(), this.getUiDrawBridge(), dim.width, dim.height);
$super(doNotRepaint);
},
*/
/** @private */
changeContextDimension: function(/*$super, */newDimension)
{
var result = this.tryApplySuper('changeContextDimension', [newDimension]) /* $super(newDimension) */;
if (result)
{
this._resizeContext(this.getOperContext(), this.getObjDrawBridge(), newDimension.width, newDimension.height);
this._resizeContext(this.getUiContext(), this.getUiDrawBridge(), newDimension.width, newDimension.height);
}
return result;
},
/** @private */
_clearSpecContext: function(context, bridge)
{
if (bridge && context)
bridge.clearContext(context);
},
/** @private */
_renderSpecContext: function(context, bridge)
{
if (bridge && context)
bridge.renderContext(context);
},
/**
* Clear the main context.
* @private
*/
clearObjContext: function()
{
//console.log('clear obj context', this.getObjContext() === this.getDrawContext());
this._clearSpecContext(this.getObjContext(), this.getDrawBridge());
if (this.getBoundInfoRecorder())
this.getBoundInfoRecorder().clear(this.getObjContext());
},
/**
* Clear the operating context.
* @private
*/
clearOperContext: function()
{
this._clearSpecContext(this.getOperContext(), this.getDrawBridge());
},
/**
* Clear the UI layer context.
* @private
*/
clearUiContext: function()
{
this._clearSpecContext(this.getUiContext(), this.getUiDrawBridge());
},
/** @private */
clearContext: function()
{
this.clearObjContext();
if (this._operatingRenderers)
this.clearOperContext();
},
/**
* Repaint the operating context only (not the whole obj context).
* @private
*/
repaintOperContext: function(ignoreUiMarker)
{
if (this._operatingRenderers && this._operatingObjs)
{
this.clearOperContext();
try
{
var options = {'partialDrawObjs': this._operatingObjs, 'doNotClear': true};
this.repaint(options);
}
finally
{
this._renderSpecContext(this.getOperContext(), this.getDrawBridge()); // important, done the rendering of oper context
}
/*
var context = this.getObjContext();
//console.log(this._operatingRenderers.length);
for (var i = 0, l = this._operatingRenderers.length; i < l; ++i)
{
var renderer = this._operatingRenderers[i];
console.log('repaint oper', renderer.getClassName(), renderer.getChemObj().getId(), !!renderer.getRedirectContext(), this._operatingRenderers.length);
renderer.redraw(context);
}
if (!ignoreUiMarker)
this.recalcUiMarkers();
*/
}
},
/** @private */
getOperatingRenderers: function()
{
if (!this._operatingRenderers)
this._operatingRenderers = [];
return this._operatingRenderers;
},
/** @private */
setOperatingRenderers: function(value)
{
this._operatingRenderers = value;
},
//////////////////////////////////////////////////////////////////////
/////////////////// methods about painter ////////////////////////////
/** @private */
installPainterEventHandlers: function(painter)
{
painter.addEventListener('prepareDrawing', this.reactChemObjPrepareDrawing, this);
painter.addEventListener('clear', this.reactChemObjClear, this);
},
/** @private */
reactChemObjPrepareDrawing: function(e)
{
var ctx = e.context;
var obj = e.obj;
if (obj && ((ctx === this.getObjContext()) || (ctx === this.getOperContext())))
{
var renderer = e.target;
this.getObjRendererMap().set(obj, renderer);
//console.log('object drawn', obj, obj.getClassName(), renderer, renderer.getClassName());
// check if renderer should be redirected to oper context
if (this.getEnableOperContext())
{
var operObjs = this._operatingObjs || [];
var needRedirect = false;
for (var i = 0, l = operObjs.length; i < l; ++i)
{
if (this._isChemObjDirectlyRenderedByRenderer(this.getObjContext(), operObjs[i], renderer))
{
needRedirect = true;
break;
}
}
if (needRedirect)
{
this._setRendererToOperContext(renderer);
//console.log('do redirect', renderer.getClassName(), obj && obj.getId && obj.getId());
AU.pushUnique(this.getOperatingRenderers(), renderer);
}
/*
else
{
this._unsetRendererToOperContext(renderer);
console.log('unset redirect', renderer.getClassName(), obj && obj.getId && obj.getId());
}
*/
}
}
},
/** @private */
reactChemObjClear: function(e)
{
var ctx = e.context;
var obj = e.obj;
if (obj && ((ctx === this.getObjContext()) || (ctx === this.getOperContext())))
{
var renderer = e.target;
this.getObjRendererMap().remove(obj);
AU.remove(this.getOperatingRenderers(), renderer);
}
},
//////////////////////////////////////////////////////////////////////
/////////////////// event handlers of nested objects ///////////////////////
/**
* React to change event of loaded chemObj.
* @param {Object} e
*/
reactChemObjChange: function(e)
{
var target = e.target;
var propNames = e.changedPropNames || [];
var bypassPropNames = ['id', 'owner', 'ownedObjs']; // these properties do not affect rendering
propNames = Kekule.ArrayUtils.exclude(propNames, bypassPropNames);
if (propNames.length || !e.changedPropNames) // when changedPropNames is not set, may be change event invoked by parent when suppressing child objects
{
//console.log('chem obj change', target.getClassName(), propNames, e);
this.objectChanged(target, propNames);
}
},
/** @private */
reactOperHistoryPush: function(e)
{
this.invokeEvent('operPush', e);
},
/** @private */
reactOperHistoryPop: function(e)
{
this.invokeEvent('operPop', e);
},
/** @private */
reactOperHistoryUndo: function(e)
{
this.invokeEvent('operUndo', e);
},
/** @private */
reactOperHistoryRedo: function(e)
{
this.invokeEvent('operRedo', e);
},
reactOperHistoryClear: function(e)
{
this.invokeEvent('operHistoryClear', e);
},
reactOperHistoryChange: function(e)
{
this.invokeEvent('operChange', e);
},
/////////////////////////////////////////////////////////////////////////////
///////////// Methods about object changing notification ////////////////////
/**
* Call this method to temporarily suspend object change notification.
*/
beginUpdateObject: function()
{
if (this._objectUpdateFlag >= 0)
{
this.invokeEvent('beginUpdateObject');
}
--this._objectUpdateFlag;
},
/**
* Call this method to indicate the update process is over and objectChanged will be immediately called.
*/
endUpdateObject: function()
{
++this._objectUpdateFlag;
if (!this.isUpdatingObject())
{
if ((this._updatedObjectDetails && this._updatedObjectDetails.length))
{
this.objectsChanged(this._updatedObjectDetails);
this._updatedObjectDetails = [];
}
this._execAfterUpdateObjectProcs();
this.invokeEvent('endUpdateObject'/*, {'details': Object.extend({}, this._updatedObjectDetails)}*/);
}
},
/**
* Check if beginUpdateObject is called and should not send object change notification immediately.
*/
isUpdatingObject: function()
{
return (this._objectUpdateFlag < 0);
},
/**
* Register suspended function called right after endUpdateObject method.
* @private
*/
_registerAfterUpdateObjectProc: function(proc)
{
if (this.isUpdatingObject())
{
if (!this.endUpdateObject.suspendedProcs)
this.endUpdateObject.suspendedProcs = [];
this.endUpdateObject.suspendedProcs.push(proc);
}
else
proc.apply(this);
},
/** @private */
_execAfterUpdateObjectProcs: function()
{
var procs = this.endUpdateObject.suspendedProcs;
if (procs)
{
while (procs.length)
{
var proc = procs.shift();
if (proc)
proc.apply(this);
}
}
},
/** @private */
_mergeObjUpdatedDetails: function(dest, target)
{
for (var i = 0, l = target.length; i < l; ++i)
{
this._mergeObjUpdatedDetailItem(dest, target[i]);
}
},
/** @private */
_mergeObjUpdatedDetailItem: function(dest, targetItem)
{
for (var i = 0, l = dest.length; i < l; ++i)
{
var destItem = dest[i];
// can merge
if (destItem.obj === targetItem.obj)
{
if (!destItem.propNames)
destItem.propNames = [];
if (targetItem.propNames)
Kekule.ArrayUtils.pushUnique(destItem.propNames, targetItem.propNames);
return;
}
}
// can not merge
dest.push(targetItem);
},
/** @private */
_logUpdatedDetail: function(details)
{
var msg = '';
details.forEach(function(d){
msg += 'Obj: ' + d.obj.getId() + '[' + d.obj.getClassName() + '] ';
msg += 'Props: [' + d.propNames.join(', ') + ']';
msg += '\n';
});
console.log(msg);
},
/**
* Notify the object(s) property has been changed and need to be updated.
* @param {Variant} obj An object or a object array.
* @param {Array} changedPropNames
* @private
*/
objectChanged: function(obj, changedPropNames)
{
var data = {'obj': obj, 'propNames': changedPropNames};
//console.log('obj changed', obj.getClassName(), obj.getId(), changedPropNames);
var result = this.objectsChanged(data);
this.invokeEvent('editObjChanged', Object.extend({}, data)); // avoid change data
return result;
},
/**
* Notify the object(s) property has been changed and need to be updated.
* @param {Variant} objDetails An object detail or an object detail array.
* @private
*/
objectsChanged: function(objDetails)
{
var a = DataType.isArrayValue(objDetails)? objDetails: [objDetails];
if (this.isUpdatingObject()) // suspend notification, just push objs in cache
{
//Kekule.ArrayUtils.pushUnique(this._updatedObjectDetails, a);
this._mergeObjUpdatedDetails(this._updatedObjectDetails, a);
//console.log('updating objects, suspending...', this._updatedObjectDetails);
//this._logUpdatedDetail(this._updatedObjectDetails);
}
else
{
//console.log('object changed', objDetails);
var updateObjs = Kekule.Render.UpdateObjUtils._extractObjsOfUpdateObjDetails(a);
this.doObjectsChanged(a, updateObjs);
// IMPORTANT: must do issue check after the doObjectsChanged method (invoking repainting)
this.requestAutoCheckIssuesIfNecessary();
this.invokeEvent('editObjsUpdated', {'details': Object.extend({}, objDetails)});
}
this._objChanged = true; // mark object changed
this.invokeEvent('editObjsChanged', {'details': Object.extend({}, objDetails)});
var selectedObjs = this.getSelection();
if (selectedObjs && updateObjs)
{
var changedSelectedObjs = AU.intersect(selectedObjs, updateObjs);
if (changedSelectedObjs.length)
this.invokeEvent('selectedObjsUpdated', {'objs': changedSelectedObjs});
}
},
/**
* Do actual job of objectsChanged. Descendants should override this method.
* @private
*/
doObjectsChanged: function(objDetails, updateObjs)
{
var oDetails = Kekule.ArrayUtils.clone(objDetails);
if (!updateObjs)
updateObjs = Kekule.Render.UpdateObjUtils._extractObjsOfUpdateObjDetails(oDetails);
//console.log('origin updateObjs', updateObjs);
var additionalObjs = this._getAdditionalRenderRelatedObjs(updateObjs);
// also push related objects into changed objs list
if (additionalObjs.length)
{
var additionalDetails = Kekule.Render.UpdateObjUtils._createUpdateObjDetailsFromObjs(additionalObjs);
Kekule.ArrayUtils.pushUnique(oDetails, additionalDetails);
}
// merge updateObjs and additionalObjs
//updateObjs = updateObjs.concat(additionalObjs);
Kekule.ArrayUtils.pushUnique(updateObjs, additionalObjs);
//console.log('changed objects', updateObjs);
var operRenderers = this._operatingRenderers;
var updateOperContextOnly = operRenderers && this._isAllObjsRenderedByRenderers(this.getObjContext(), updateObjs, operRenderers);
var canDoPartialUpdate = this.canModifyPartialGraphic();
//console.log('update objs and operRenderers', updateObjs, operRenderers);
//console.log('object changed', updateOperContextOnly, canDoPartialUpdate);
if (canDoPartialUpdate) // partial update
{
//var updateObjDetails = Kekule.Render.UpdateObjUtils._createUpdateObjDetailsFromObjs(updateObjs);
this.getRootRenderer().modify(this.getObjContext(),/* updateObjDetails*/oDetails);
// always repaint UI markers
this.recalcUiMarkers();
//console.log('partial update', oDetails);
}
else // update whole context
{
if (updateOperContextOnly)
{
//console.log('repaint oper context only');
this.repaintOperContext();
}
else // need to update whole context
{
//console.log('[repaint whole]');
this.repaint();
/*
var self = this;
(function(){ self.repaint(); }).defer();
*/
}
}
},
/**
* Call this method to indicate a continuous manipulation operation is doing (e.g. moving or rotating objects).
*/
beginManipulateObject: function()
{
//console.log('[BEGIN MANIPULATE]');
//console.log('[Call begin update]', this._objectManipulateFlag);
if (this._objectManipulateFlag >= 0)
{
this.invokeEvent('beginManipulateObject');
}
--this._objectManipulateFlag;
},
/**
* Call this method to indicate the update process is over and objectChanged will be immediately called.
*/
endManipulateObject: function()
{
++this._objectManipulateFlag;
//console.log('[END MANIPULATE]');
if (!this.isManipulatingObject())
{
this._objectManipulateFlag = 0;
this.doManipulationEnd();
this.requestAutoCheckIssuesIfNecessary();
//console.log('[MANIPULATE DONE]');
//this.invokeEvent('endManipulateObject'/*, {'details': Object.extend({}, this._updatedObjectDetails)}*/);
}
},
/**
* Check if beginUpdateObject is called and should not send object change notification immediately.
*/
isManipulatingObject: function()
{
return (this._objectManipulateFlag < 0);
},
/**
* Called when endManipulateObject is called and the object manipulation is really done.
* @private
*/
doManipulationEnd: function()
{
//console.log('[MANIPULATE END]');
this.setOperationsInCurrManipulation([]);
this.invokeEvent('endManipulateObject'/*, {'details': Object.extend({}, this._updatedObjectDetails)}*/);
},
/**
* A combination of method beginUpdateObject/beginManipulateObject.
*/
beginManipulateAndUpdateObject: function()
{
this.beginManipulateObject();
this.beginUpdateObject();
},
/**
* A combination of method endUpdateObject/endManipulateObject.
*/
endManipulateAndUpdateObject: function()
{
this.endUpdateObject();
this.endManipulateObject();
},
/*
* Try apply modification to a series of objects in editor.
* @param {Variant} modificationOrName Modification object or name.
* @param {Variant} targets Target object or objects.
* @returns {Kekule.Operation} operation actually done.
*/
/*
applyModification: function(modificationOrName, targets)
{
var objs = AU.toArray(targets);
var modification = (typeof(modificationOrName) === 'string')? Kekule.Editor.ChemObjModificationManager.getModification(modificationOrName): modificationOrName;
if (objs.length && modification)
{
var opers = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
if (modification.match(objs[i], this))
{
var oper = modification.createOperation(objs[i], this);
if (oper)
opers.push(oper);
}
}
}
if (opers.length)
{
var finalOper = (opers.length === 1) ? opers[0] : new Kekule.MacroOperation(opers);
this.execOperation(finalOper);
return finalOper;
}
else
return null;
},
*/
/** @private */
_needToCanonicalizeBeforeSaving: function()
{
return true; // !!this.getStandardizeObjectsBeforeSaving();
},
/** @private */
_getAdditionalRenderRelatedObjs: function(objs)
{
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
//Kekule.ArrayUtils.pushUnique(result, obj);
var relatedObjs = obj.getCoordDeterminateObjects? obj.getCoordDeterminateObjects(): [];
//console.log('obj', obj.getClassName(), 'related', relatedObjs);
Kekule.ArrayUtils.pushUnique(result, relatedObjs);
}
return result;
},
/** @private */
_isAllObjsRenderedByRenderers: function(context, objs, renders)
{
//console.log('check objs by renderers', objs, renders);
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var isRendered = false;
for (var j = 0, k = renders.length; j < k; ++j)
{
var renderer = renders[j];
if (renderer.isChemObjRenderedBySelf(context, obj))
{
isRendered = true;
break;
}
}
if (!isRendered)
return false;
}
return true;
},
/////////////////////////////////////////////////////////////////////////////
////////////// Method about operContext rendering ///////////////////////////
/**
* Prepare to do a modification work in editor (e.g., move some atoms).
* The objs to be modified will be rendered in operContext separately (if enableOperContext is true).
* @param {Array} objs
*/
prepareOperatingObjs: function(objs)
{
// Check if already has old operating renderers. If true, just end them.
if (this._operatingRenderers && this._operatingRenderers.length)
this.endOperatingObjs(true);
if (this.getEnableOperContext())
{
// prepare operating renderers
this._prepareRenderObjsInOperContext(objs);
this._operatingObjs = objs;
//console.log('oper objs', this._operatingObjs);
//console.log('oper renderers', this._operatingRenderers);
}
// finally force repaint the whole client area, both objContext and operContext
this.repaint();
},
/**
* Modification work in editor (e.g., move some atoms) is done.
* The objs to be modified will be rendered back into objContext.
* @param {Bool} noRepaint
*/
endOperatingObjs: function(noRepaint)
{
// notify to render all objs in main context
if (this.getEnableOperContext())
{
this._endRenderObjsInOperContext();
this._operatingObjs = null;
if (!noRepaint)
{
//console.log('end operation objs');
this.repaint();
}
}
},
/** @private */
_isChemObjDirectlyRenderedByRenderer: function(context, obj, renderer)
{
var standaloneObj = obj.getStandaloneAncestor? obj.getStandaloneAncestor(): obj;
return renderer.isChemObjRenderedDirectlyBySelf(context, standaloneObj);
},
/** @private */
_getStandaloneRenderObjsInOperContext: function(objs)
{
var standAloneObjs = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj.getStandaloneAncestor)
obj = obj.getStandaloneAncestor();
Kekule.ArrayUtils.pushUnique(standAloneObjs, obj);
}
return standAloneObjs;
},
/** @private */
_prepareRenderObjsInOperContext: function(objs)
{
//console.log('redirect objs', objs);
var renderers = [];
var map = this.getObjRendererMap();
var rs = map.getValues();
var context = this.getObjContext();
var standAloneObjs = this._getStandaloneRenderObjsInOperContext(objs);
/*
if (standAloneObjs.length)
console.log(standAloneObjs[0].getId(), standAloneObjs);
else
console.log('(no standalone)');
*/
//for (var i = 0, l = objs.length; i < l; ++i)
for (var i = 0, l = standAloneObjs.length; i < l; ++i)
{
//var obj = objs[i];
var obj = standAloneObjs[i];
for (var j = 0, k = rs.length; j < k; ++j)
{
var renderer = rs[j];
//if (renderer.isChemObjRenderedBySelf(context, obj))
if (renderer.isChemObjRenderedDirectlyBySelf(context, obj))
{
//console.log('direct rendered by', obj.getClassName(), renderer.getClassName());
Kekule.ArrayUtils.pushUnique(renderers, renderer);
}
/*
if (parentFragment && renderer.isChemObjRenderedDirectlyBySelf(context, parentFragment))
Kekule.ArrayUtils.pushUnique(renderers, renderer); // when modify node or connector, mol will also be changed
*/
}
/*
var renderer = map.get(objs[i]);
if (renderer)
Kekule.ArrayUtils.pushUnique(renderers, renderer);
*/
}
//console.log('oper renderers', renderers);
if (renderers.length > 0)
{
for (var i = 0, l = renderers.length; i < l; ++i)
{
var renderer = renderers[i];
this._setRendererToOperContext(renderer);
//console.log('begin context redirect', renderer.getClassName());
//console.log(renderer.getRedirectContext());
}
this._operatingRenderers = renderers;
}
else
this._operatingRenderers = null;
//console.log('<total renderer count>', rs.length, '<redirected>', renderers.length);
/*
if (renderers.length)
console.log('redirected obj 0: ', renderers[0].getChemObj().getId());
*/
},
/** @private */
_endRenderObjsInOperContext: function()
{
var renderers = this._operatingRenderers;
if (renderers && renderers.length)
{
for (var i = 0, l = renderers.length; i < l; ++i)
{
var renderer = renderers[i];
//renderer.setRedirectContext(null);
this._unsetRendererToOperContext(renderer);
//console.log('end context redirect', renderer.getClassName());
}
this.clearOperContext();
}
this._operatingRenderers = null;
},
/** @private */
_setRendererToOperContext: function(renderer)
{
renderer.setRedirectContext(this.getOperContext());
},
/** @private */
_unsetRendererToOperContext: function(renderer)
{
renderer.setRedirectContext(null);
},
/////////////////////////////////////////////////////////////////////////////
//////////////////////// methods about bound maps ////////////////////////////
/**
* Returns bound inflation for interaction with a certain pointer device (mouse, touch, etc.)
* @param {String} pointerType
*/
getInteractionBoundInflation: function(pointerType)
{
var cache = this._lengthCaches.interactionBoundInflations;
var cacheKey = pointerType || 'default';
if (cache)
{
if (cache[cacheKey])
{
//console.log('cached!')
return cache[cacheKey];
}
}
// no cache, calculate
var iaConfigs = this.getEditorConfigs().getInteractionConfigs();
var defRatioPropName = 'objBoundTrackInflationRatio';
var typedRatio, defRatio = iaConfigs.getPropValue(defRatioPropName);
if (pointerType)
{
var sPointerType = pointerType.upperFirst();
var typedRatioPropName = defRatioPropName + sPointerType;
if (iaConfigs.hasProperty(typedRatioPropName))
typedRatio = iaConfigs.getPropValue(typedRatioPropName);
}
var actualRatio = typedRatio || defRatio;
var ratioValue = actualRatio && this.getDefBondScreenLength() * actualRatio;
var minValuePropName = 'objBoundTrackMinInflation';
var typedMinValue, defMinValue = iaConfigs.getPropValue(minValuePropName);
if (pointerType)
{
var typedMinValuePropName = minValuePropName + sPointerType;
if (iaConfigs.hasProperty(typedMinValuePropName))
typedMinValue = iaConfigs.getPropValue(typedMinValuePropName);
}
var actualMinValue = typedMinValue || defMinValue;
var actualValue = Math.max(ratioValue || 0, actualMinValue);
// stores to cache
if (!cache)
{
cache = {};
this._lengthCaches.interactionBoundInflations = cache;
}
cache[cacheKey] = actualValue;
//console.log('to cache');
return actualValue;
},
/**
* Returns all bound map item at x/y.
* Input coord is based on the screen coord system.
* @returns {Array}
* @private
*/
getBoundInfosAtCoord: function(screenCoord, filterFunc, boundInflation)
{
/*
if (!boundInflation)
throw 'boundInflation not set!';
*/
var delta = boundInflation || this.getCurrBoundInflation() || this.getEditorConfigs().getInteractionConfigs().getObjBoundTrackMinInflation();
return this.tryApplySuper('getBoundInfosAtCoord', [screenCoord, filterFunc, delta]);
/*
var boundRecorder = this.getBoundInfoRecorder();
var delta = boundInflation || this.getCurrBoundInflation() || this.getEditorConfigs().getInteractionConfigs().getObjBoundTrackMinInflation();
//var coord = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord);
var coord = this.screenCoordToContext(screenCoord);
var refCoord = (this.getRenderType() === Kekule.Render.RendererType.R3D)? {'x': 0, 'y': 0}: null;
//console.log(coord, delta);
var matchedInfos = boundRecorder.getIntersectionInfos(this.getObjContext(), coord, refCoord, delta, filterFunc);
return matchedInfos;
*/
},
/**
* returns the topmost bound map item at x/y.
* Input coord is based on the screen coord system.
* @param {Hash} screenCoord
* @param {Array} excludeObjs Objects in this array will not be returned.
* @returns {Object}
*/
getTopmostBoundInfoAtCoord: function(screenCoord, excludeObjs, boundInflation)
{
var enableTrackNearest = this.getEditorConfigs().getInteractionConfigs().getEnableTrackOnNearest();
if (!enableTrackNearest)
//return this.findTopmostBoundInfo(this.getBoundInfosAtCoord(screenCoord, null, boundInflation), excludeObjs, boundInflation);
return this.tryApplySuper('getTopmostBoundInfoAtCoord', [screenCoord, excludeObjs, boundInflation]);
// else, track on nearest
// new approach, find nearest boundInfo at coord
var SU = Kekule.Render.MetaShapeUtils;
var boundInfos = this.getBoundInfosAtCoord(screenCoord, null, boundInflation);
//var filteredBoundInfos = [];
var result, lastShapeInfo, lastDistance;
var setResult = function(boundInfo, shapeInfo, distance)
{
result = boundInfo;
lastShapeInfo = shapeInfo || boundInfo.boundInfo;
if (Kekule.ObjUtils.notUnset(distance))
lastDistance = distance;
else
lastDistance = SU.getDistance(screenCoord, lastShapeInfo);
};
for (var i = boundInfos.length - 1; i >= 0; --i)
{
var info = boundInfos[i];
if (excludeObjs && (excludeObjs.indexOf(info.obj) >= 0))
continue;
if (!result)
setResult(info);
else
{
var shapeInfo = info.boundInfo;
if (shapeInfo.shapeType < lastShapeInfo.shapeType)
setResult(info, shapeInfo);
else if (shapeInfo.shapeType === lastShapeInfo.shapeType)
{
var currDistance = SU.getDistance(screenCoord, shapeInfo);
if (currDistance < lastDistance)
{
//console.log('distanceCompare', currDistance, lastDistance);
setResult(info, shapeInfo, currDistance);
}
}
}
}
return result;
},
/**
* Returns all basic drawn object at coord (with inflation) based on screen system.
* @params {Hash} screenCoord
* @param {Number} boundInflation
* @param {Array} excludeObjs
* @param {Array} filterObjClasses If this param is set, only obj match these types will be returned
* @returns {Array}
* @private
*/
getBasicObjectsAtCoord: function(screenCoord, boundInflation, excludeObjs, filterObjClasses)
{
var boundInfos = this.getBoundInfosAtCoord(screenCoord, null, boundInflation);
var result = [];
if (boundInfos)
{
if (excludeObjs)
{
boundInfos = AU.filter(boundInfos, function(boundInfo){
var obj = boundInfos[i].obj;
if (!obj)
return false;
if (obj)
{
if (excludeObjs && excludeObjs.indexOf(obj) >= 0)
return false;
}
return true;
});
}
// the coord sticked obj should be firstly selected for unstick operation, even it is under the back layer
var _getStickLevel = function(obj){
var stickTarget = obj && obj.getCoordStickTarget && obj.getCoordStickTarget();
return stickTarget? 1: 0;
};
boundInfos.sort(function(b1, b2){
var stickLevel1 = _getStickLevel(b1.obj);
var stickLevel2 = _getStickLevel(b2.obj);
return (stickLevel1 - stickLevel2);
});
var enableTrackNearest = this.getEditorConfigs().getInteractionConfigs().getEnableTrackOnNearest();
if (enableTrackNearest) // sort by bound distances to screenCoord
{
var SU = Kekule.Render.MetaShapeUtils;
boundInfos.sort(function(b1, b2){ // the topmost boundinfo at tail
var result = 0;
var shapeInfo1 = b1.boundInfo;
var shapeInfo2 = b2.boundInfo;
result = -(shapeInfo1.shapeType - shapeInfo2.shapeType);
if (!result)
{
var d1 = SU.getDistance(screenCoord, shapeInfo1);
var d2 = SU.getDistance(screenCoord, shapeInfo2);
result = -(d1 - d2);
}
return result;
});
}
for (var i = boundInfos.length - 1; i >= 0; --i)
{
var obj = boundInfos[i].obj;
if (obj)
{
if (excludeObjs && excludeObjs.indexOf(obj) >= 0)
continue;
}
result.push(obj);
}
if (result && filterObjClasses) // filter
{
result = AU.filter(result, function(obj)
{
for (var i = 0, l = filterObjClasses.length; i < l; ++i)
{
if (obj instanceof filterObjClasses[i])
return true;
}
return false;
});
}
}
return result;
},
/**
* Returns the topmost basic drawn object at coord based on screen system.
* @params {Hash} screenCoord
* @param {Number} boundInflation
* @param {Array} filterObjClasses If this param is set, only obj match these types will be returned
* @returns {Object}
* @private
*/
getTopmostBasicObjectAtCoord: function(screenCoord, boundInflation, filterObjClasses)
{
/*
var boundItem = this.getTopmostBoundInfoAtCoord(screenCoord, null, boundInflation);
return boundItem? boundItem.obj: null;
*/
var objs = this.getBasicObjectsAtCoord(screenCoord, boundInflation, null, filterObjClasses);
return objs && objs[0];
},
/**
* Returns geometry bounds of a obj in editor.
* @param {Kekule.ChemObject} obj
* @param {Number} boundInflation
* @returns {Array}
*/
getChemObjBounds: function(obj, boundInflation)
{
var bounds = [];
var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj);
if (infos && infos.length)
{
for (var j = 0, k = infos.length; j < k; ++j)
{
var info = infos[j];
var bound = info.boundInfo;
if (bound)
{
// inflate
bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, boundInflation);
bounds.push(bound);
}
}
}
return bounds;
},
//////////////////// methods about UI markers ///////////////////////////////
/**
* Returns the ui markers at screen coord.
* @param {Hash} screenCoord
* @param {Float} boundInflation
* @param {Array} filterClasses
* @returns {Array}
*/
getUiMarkersAtCoord: function(screenCoord, boundInflation, filterClasses)
{
var markers = this.getUiMarkers();
var filterFunc = (filterClasses && filterClasses.length)? function(marker) {
for (var i = 0, l = filterClasses.length; i < l; ++i)
{
if (marker instanceof filterClasses[i])
return true;
}
return false;
}: null;
var SU = Kekule.Render.MetaShapeUtils;
var result = [];
for (var i = markers.getMarkerCount() - 1; i >= 0; --i)
{
var marker = markers.getMarkerAt(i);
if (marker.getVisible())
{
if (!filterFunc || filterFunc(marker))
{
var shapeInfo = marker.shapeInfo;
if (SU.isCoordInside(screenCoord, shapeInfo, boundInflation))
result.push(marker);
}
}
}
return result;
},
/**
* Notify that currently is modifing UI markers and the editor need not to repaint them.
*/
beginUpdateUiMarkers: function()
{
--this._uiMarkerUpdateFlag;
},
/**
* Call this method to indicate the UI marker update process is over and should be immediately updated.
*/
endUpdateUiMarkers: function()
{
++this._uiMarkerUpdateFlag;
if (!this.isUpdatingUiMarkers())
this.repaintUiMarker();
},
/** Check if the editor is under continuous UI marker update. */
isUpdatingUiMarkers: function()
{
return (this._uiMarkerUpdateFlag < 0);
},
/**
* Called when transform has been made to objects and UI markers need to be modified according to it.
* The UI markers will also be repainted.
* @private
*/
recalcUiMarkers: function()
{
//this.setHotTrackedObj(null);
if (this.getUiDrawBridge())
{
this.beginUpdateUiMarkers();
try
{
this.recalcHotTrackMarker();
this.recalcSelectionAreaMarker();
this.recalcIssueCheckUiMarkers();
} finally
{
this.endUpdateUiMarkers();
}
}
},
/** @private */
repaintUiMarker: function()
{
if (this.isUpdatingUiMarkers())
return;
if (this.getUiDrawBridge() && this.getUiContext())
{
this.clearUiContext();
var drawParams = this.calcDrawParams();
this.getUiPainter().draw(this.getUiContext(), drawParams.baseCoord, drawParams.drawOptions);
}
},
/**
* Create a new marker based on shapeInfo.
* @private
*/
createShapeBasedMarker: function(markerPropName, shapeInfo, drawStyles, updateRenderer)
{
var marker = new Kekule.ChemWidget.MetaShapeUIMarker();
if (shapeInfo)
marker.setShapeInfo(shapeInfo);
if (drawStyles)
marker.setDrawStyles(drawStyles);
this.setPropStoreFieldValue(markerPropName, marker);
this.getUiMarkers().addMarker(marker);
if (updateRenderer)
{
//var updateType = Kekule.Render.ObjectUpdateType.ADD;
//this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, updateType);
this.repaintUiMarker();
}
return marker;
},
/**
* Change the shape info of a meta shape based marker, or create a new marker based on shape info.
* @private
*/
modifyShapeBasedMarker: function(marker, newShapeInfo, drawStyles, updateRenderer)
{
var updateType = Kekule.Render.ObjectUpdateType.MODIFY;
if (newShapeInfo)
marker.setShapeInfo(newShapeInfo);
if (drawStyles)
marker.setDrawStyles(drawStyles);
// notify change and update renderer
if (updateRenderer)
{
//this.getUiPainter().redraw();
//this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, updateType);
this.repaintUiMarker();
}
},
/**
* Hide a UI marker.
* @param marker
*/
hideUiMarker: function(marker, updateRenderer)
{
marker.setVisible(false);
// notify change and update renderer
if (updateRenderer)
{
//this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, Kekule.Render.ObjectUpdateType.MODIFY);
this.repaintUiMarker();
}
},
/**
* Show an UI marker.
* @param marker
* @param updateRenderer
*/
showUiMarker: function(marker, updateRenderer)
{
marker.setVisible(true);
if (updateRenderer)
{
//this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, Kekule.Render.ObjectUpdateType.MODIFY);
this.repaintUiMarker();
}
},
/**
* Remove a marker from collection.
* @private
*/
removeUiMarker: function(marker)
{
if (marker)
{
this.getUiMarkers().removeMarker(marker);
//this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, Kekule.Render.ObjectUpdateType.REMOVE);
this.repaintUiMarker();
}
},
/**
* Clear all UI markers.
* @private
*/
clearUiMarkers: function()
{
this.getUiMarkers().clearMarkers();
//this.getUiRenderer().redraw(this.getUiContext());
//this.redraw();
this.repaintUiMarker();
},
/**
* Modify hot track marker to bind to newBoundInfos.
* @private
*/
changeHotTrackMarkerBounds: function(newBoundInfos)
{
var infos = Kekule.ArrayUtils.toArray(newBoundInfos);
//var updateType = Kekule.Render.ObjectUpdateType.MODIFY;
var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs();
var drawStyles = {
'color': styleConfigs.getHotTrackerColor(),
'opacity': styleConfigs.getHotTrackerOpacity()
};
var inflation = this.getCurrBoundInflation() || this.getEditorConfigs().getInteractionConfigs().getObjBoundTrackMinInflation();
var bounds = [];
for (var i = 0, l = infos.length; i < l; ++i)
{
var boundInfo = infos[i];
var bound = inflation? Kekule.Render.MetaShapeUtils.inflateShape(boundInfo, inflation): boundInfo;
//console.log('inflate', bound);
if (bound)
bounds.push(bound);
}
var tracker = this.getUiHotTrackMarker();
//console.log('change hot track', bound, drawStyles);
tracker.setVisible(true);
this.modifyShapeBasedMarker(tracker, bounds, drawStyles, true);
return this;
},
/**
* Hide hot track marker.
* @private
*/
hideHotTrackMarker: function()
{
var tracker = this.getUiHotTrackMarker();
if (tracker)
{
this.hideUiMarker(tracker, true);
}
return this;
},
/**
* Show hot track marker.
* @private
*/
showHotTrackMarker: function()
{
var tracker = this.getUiHotTrackMarker();
if (tracker)
{
this.showUiMarker(tracker, true);
}
return this;
},
/////////////////////////////////////////////////////////////////////////////
// methods about hot track marker
/**
* Try hot track object on coord.
* @param {Hash} screenCoord Coord based on screen system.
*/
hotTrackOnCoord: function(screenCoord)
{
if (this.getEditorConfigs().getInteractionConfigs().getEnableHotTrack())
{
/*
var boundItem = this.getTopmostBoundInfoAtCoord(screenCoord);
if (boundItem) // mouse move into object
{
var obj = boundItem.obj;
if (obj)
this.setHotTrackedObj(obj);
//this.changeHotTrackMarkerBound(boundItem.boundInfo);
}
else // mouse move out from object
{
this.setHotTrackedObj(null);
}
*/
//console.log('hot track here');
this.setHotTrackedObj(this.getTopmostBasicObjectAtCoord(screenCoord, this.getCurrBoundInflation()));
}
return this;
},
/**
* Hot try on a basic drawn object.
* @param {Object} obj
*/
hotTrackOnObj: function(obj)
{
this.setHotTrackedObj(obj);
return this;
},
/**
* Remove all hot track markers.
* @param {Bool} doNotClearHotTrackedObjs If false, the hotTrackedObjs property will also be set to empty.
*/
hideHotTrack: function(doNotClearHotTrackedObjs)
{
this.hideHotTrackMarker();
if (!doNotClearHotTrackedObjs)
this.clearHotTrackedObjs();
return this;
},
/**
* Set hot tracked objects to empty.
*/
clearHotTrackedObjs: function()
{
this.setHotTrackedObjs([]);
},
/**
* Add a obj to hot tracked objects.
* @param {Object} obj
*/
addHotTrackedObj: function(obj)
{
var olds = this.getHotTrackedObjs() || [];
Kekule.ArrayUtils.pushUnique(olds, obj);
this.setHotTrackedObjs(olds);
return this;
},
/** @private */
recalcHotTrackMarker: function()
{
this.setHotTrackedObjs(this.getHotTrackedObjs());
},
// method about chem object hint
/**
* Update the hint of chem object.
* This method may be called when hovering on some basic objects
* @param {String} hint
* @private
*/
updateHintForChemObject: function(hint)
{
var elem = this.getEditClientElem();
if (elem)
{
var sHint = hint || '';
if (sHint && this.updateHintForChemObject._cache == sHint) // same as last non-empty hint, must explicitly change hint a little, otherwise the hint may not be displayed in client area
{
sHint += '\f'; // add a hidden char
}
elem.title = sHint;
if (sHint)
this.updateHintForChemObject._cache = sHint;
}
},
/**
* Returns the hint value from a chem object.
* Descendants may override this method.
* @param {Kekule.ChemObject} obj
* @returns {String}
*/
getChemObjHint: function(obj)
{
return null;
},
/**
* Returns the hint value from a set of chem objects.
* Descendants may override this method.
* @param {Kekule.ChemObject} obj
* @returns {String}
*/
getChemObjsHint: function(objs)
{
var hints = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var hint = this.getChemObjHint(objs[i]);
if (hint)
{
// hints.push(hint);
AU.pushUnique(hints, hint); // avoid show duplicated hint texts
}
}
// issue hints
var issueHints = this._getChemObjsRelatedIssuesHints(objs);
if (issueHints.length)
{
//hints = hints.concat(issueHints);
AU.pushUnique(hints, issueHints); // avoid show duplicated hint texts
}
return hints.length? hints.join('\n'): null;
},
/** @private */
_getChemObjsRelatedIssuesHints: function(objs)
{
var result = [];
if (this.getEnableIssueMarkerHint() && this.getEnableIssueCheck())
{
var issueItems = this.getObjectsRelatedIssueItems(objs, true) || [];
for (var i = 0, l = issueItems.length; i < l; ++i)
{
var msg = issueItems[i].getMessage();
AU.pushUnique(result, msg); // avoid show duplicated hint texts
}
}
return result;
},
// methods about issue markers
/** @private */
issueCheckResultsChanged: function()
{
this.recalcIssueCheckUiMarkers();
var activeIssueResult = this.getActiveIssueCheckResult();
if (activeIssueResult && this.getEnableAutoScrollToActiveIssue()) // need to auto scroll to active issue objects?
{
var targets = activeIssueResult.getTargets();
if (targets && targets.length)
{
var objs = this._getExposedSelfOrParentObjs(targets);
if (objs && objs.length)
{
var interState = this.getObjectsBoxAndClientBoxRelation(objs);
if (interState !== Kekule.IntersectionState.CONTAINED)
this.scrollClientToObject(objs);
}
}
}
},
/** @private */
_needShowInactiveIssueMarkers: function()
{
var result = this.getEnableIssueCheck() && this.getShowAllIssueMarkers();
return result;
},
/** @private */
recalcIssueCheckUiMarkers: function()
{
if (!this.getChemObjLoaded()) // if no content in editor, just bypass
return;
this.beginUpdateUiMarkers();
try
{
var checkResults = this.getIssueCheckResults() || [];
if (!checkResults.length || !this.getEnableIssueCheck())
this.hideIssueCheckUiMarkers();
else
{
var showAll = this._needShowInactiveIssueMarkers();
var activeResult = this.getActiveIssueCheckResult();
// hide or show active marker
this.getActiveIssueCheckUiMarker().setVisible(!!activeResult);
var issueObjGroup = this._groupUpIssueObjects(checkResults, activeResult, true); // only returns exposed objs in editor
//var boundGroup = {};
var inflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerInflation();
// TODO: the inflation of issue markers are now borrowed from selection markers
var levels = Kekule.ErrorLevel.getAllLevels();
var groupKeys = levels.concat('active'); // Kekule.ObjUtils.getOwnedFieldNames(issueObjGroup);
for (var i = 0, ii = groupKeys.length; i < ii; ++i)
{
var currBounds = [];
var key = groupKeys[i];
var group = issueObjGroup[key];
var errorLevel = group? group.level: key;
if (group)
{
var isActive = key === 'active';
if (isActive || showAll) // when showAll is not true, bypass all inactive issue markers
{
var objs = group.objs;
for (var j = 0, jj = objs.length; j < jj; ++j)
{
var obj = objs[j];
var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj);
for (var k = 0, kk = infos.length; k < kk; ++k)
{
var info = infos[k];
var bound = info.boundInfo;
if (bound)
{
// inflate
bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, inflation);
currBounds.push(bound);
}
}
}
}
}
this.changeIssueCheckUiMarkerBound(errorLevel, currBounds, isActive);
}
}
}
finally
{
this.endUpdateUiMarkers();
}
},
/** @private */
changeIssueCheckUiMarkerBound: function(issueLevel, bounds, isActive)
{
var marker = isActive? this.getActiveIssueCheckUiMarker(): this.getIssueCheckUiMarker(issueLevel);
if (marker)
{
//console.log(issueLevel, marker, bounds.length);
if (bounds && bounds.length)
{
var levelName = Kekule.ErrorLevel.levelToString(issueLevel);
var configs = this.getEditorConfigs().getUiMarkerConfigs();
var styleConfigs = configs.getIssueCheckMarkerColors()[levelName];
var drawStyles = {
'strokeColor': isActive ? styleConfigs.activeStrokeColor : styleConfigs.strokeColor,
'strokeWidth': isActive ? configs.getIssueCheckActiveMarkerStrokeWidth() : configs.getIssueCheckMarkerStrokeWidth(),
'fillColor': isActive ? styleConfigs.activeFillColor : styleConfigs.fillColor,
'opacity': isActive ? configs.getIssueCheckActiveMarkerOpacity() : configs.getIssueCheckMarkerOpacity()
};
//console.log(drawStyles);
marker.setVisible(true);
this.modifyShapeBasedMarker(marker, bounds, drawStyles, true);
}
else
marker.setVisible(false);
}
return this;
},
/** @private */
_getExposedSelfOrParentObjs: function(objs)
{
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (!obj.isExposed || obj.isExposed())
result.push(obj);
else if (obj.getExposedAncestor)
{
var ancestor = obj.getExposedAncestor();
if (ancestor)
result.push(ancestor);
}
}
return result;
},
/** @private */
_groupUpIssueObjects: function(checkResults, activeResult, requireExposing)
{
var result = {};
for (var i = 0, l = checkResults.length; i < l; ++i)
{
var r = checkResults[i];
var objs = r.getTargets();
var level = r.getLevel();
if (activeResult && r === activeResult)
{
result['active'] = {
'level': level,
'objs': requireExposing? this._getExposedSelfOrParentObjs(objs): objs
};
}
else
{
if (!result[level])
result[level] = {'level': level, 'objs': []};
result[level].objs = result[level].objs.concat(requireExposing ? this._getExposedSelfOrParentObjs(objs) : objs);
}
}
// different error levels have different priorities, a object in higher level need not to be marked in lower level
var EL = Kekule.ErrorLevel;
var priorities = [EL.LOG, EL.NOTE, EL.WARNING, EL.ERROR, 'active'];
for (var i = 0, l = priorities.length; i < l; ++i)
{
var currPriotyObjs = result[i] && result[i].objs;
if (currPriotyObjs)
{
for (var j = i + 1, k = priorities.length; j < k; ++j)
{
var highPriotyObjs = result[j] && result[j].objs;
if (highPriotyObjs)
{
var filteredObjs = AU.exclude(currPriotyObjs, highPriotyObjs);
result[i].objs = filteredObjs;
}
}
}
}
return result;
},
/** @private */
hideIssueCheckUiMarkers: function()
{
var markers = this.getAllIssueCheckUiMarkers() || [];
for (var i = 0, l = markers.length; i < l; ++i)
this.hideUiMarker(markers[i]);
},
/**
* Check if obj (or its ancestor) is (one of) the targets of issueResult.
* @param {Kekule.ChemObject} obj
* @param {Kekule.IssueCheck.CheckResult} issueResult
* @param {Bool} checkAncestors
* @returns {Bool}
*/
isObjectRelatedToIssue: function(obj, issueResult, checkAncestors)
{
var targets = issueResult.getTargets() || [];
if (targets.indexOf(obj) >= 0)
return true;
else if (checkAncestors)
{
var parent = obj.getParent();
return parent? this.isObjectRelatedToIssue(parent, issueResult, checkAncestors): false;
}
},
/**
* Returns the issue items related to obj.
* @param {Kekule.ChemObject} obj
* @param {Bool} checkAncestors
* @returns {Array}
*/
getObjectIssueItems: function(obj, checkAncestors)
{
var checkResults = this.getIssueCheckResults() || [];
if (!checkResults.length || !this.getEnableIssueCheck())
return [];
else
{
var result = [];
for (var i = 0, l = checkResults.length; i < l; ++i)
{
var item = checkResults[i];
if (this.isObjectRelatedToIssue(obj, item, checkAncestors))
result.push(item);
}
return result;
}
},
/**
* Returns the issue items related to a series of objects.
* @param {Array} objs
* @param {Bool} checkAncestors
* @returns {Array}
*/
getObjectsRelatedIssueItems: function(objs, checkAncestors)
{
var checkResults = this.getIssueCheckResults() || [];
if (!checkResults.length || !this.getEnableIssueCheck())
return [];
var result = [];
// build the while object set that need to check issue items
var totalObjs = [].concat(objs);
if (checkAncestors)
{
for (var i = 0, l = objs.length; i < l; ++i)
{
AU.pushUnique(totalObjs, objs[i].getParentList());
}
}
for (var i = 0, l = totalObjs.length; i < l; ++i)
{
var issueItems = this.getObjectIssueItems(totalObjs[i], false);
AU.pushUnique(result, issueItems);
}
return result;
},
// methods about selecting marker
/**
* Modify hot track marker to bind to newBoundInfo.
* @private
*/
changeSelectionAreaMarkerBound: function(newBoundInfo, drawStyles)
{
var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs();
if (!drawStyles)
drawStyles = {
'strokeColor': styleConfigs.getSelectionMarkerStrokeColor(),
'strokeWidth': styleConfigs.getSelectionMarkerStrokeWidth(),
'fillColor': styleConfigs.getSelectionMarkerFillColor(),
'opacity': styleConfigs.getSelectionMarkerOpacity()
};
//console.log(drawStyles);
var marker = this.getUiSelectionAreaMarker();
if (marker)
{
marker.setVisible(true);
this.modifyShapeBasedMarker(marker, newBoundInfo, drawStyles, true);
}
return this;
},
/** @private */
hideSelectionAreaMarker: function()
{
var marker = this.getUiSelectionAreaMarker();
if (marker)
{
this.hideUiMarker(marker, true);
}
},
/** @private */
showSelectionAreaMarker: function()
{
var marker = this.getUiSelectionAreaMarker();
if (marker)
{
this.showUiMarker(marker, true);
}
},
/**
* Recalculate and repaint selection marker.
* @private
*/
recalcSelectionAreaMarker: function(doRepaint)
{
this.beginUpdateUiMarkers();
try
{
// debug
var selection = this.getSelection();
var count = selection.length;
if (count <= 0)
this.hideSelectionAreaMarker();
else
{
var bounds = [];
var containerBox = null;
var inflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerInflation();
for (var i = 0; i < count; ++i)
{
var obj = selection[i];
var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj);
if (infos && infos.length)
{
for (var j = 0, k = infos.length; j < k; ++j)
{
var info = infos[j];
var bound = info.boundInfo;
if (bound)
{
// inflate
bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, inflation);
bounds.push(bound);
var box = Kekule.Render.MetaShapeUtils.getContainerBox(bound);
containerBox = containerBox? Kekule.BoxUtils.getContainerBox(containerBox, box): box;
}
}
}
}
//var containerBox = this.getSelectionContainerBox(inflation);
this.setUiSelectionAreaContainerBox(containerBox);
// container box
if (containerBox)
{
var containerShape = Kekule.Render.MetaShapeUtils.createShapeInfo(
Kekule.Render.MetaShapeType.RECT,
[{'x': containerBox.x1, 'y': containerBox.y1}, {'x': containerBox.x2, 'y': containerBox.y2}]
);
bounds.push(containerShape);
}
else // containerBox disappear, may be a node or connector merge, hide selection area
this.hideSelectionAreaMarker();
//console.log(bounds.length, bounds);
if (bounds.length)
this.changeSelectionAreaMarkerBound(bounds);
}
}
finally
{
this.endUpdateUiMarkers();
}
},
/** @private */
_highlightSelectionAreaMarker: function()
{
var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs();
var highlightStyles = {
'strokeColor': styleConfigs.getSelectionMarkerStrokeColor(),
'strokeWidth': styleConfigs.getSelectionMarkerStrokeWidth(),
'fillColor': styleConfigs.getSelectionMarkerFillColor(),
'opacity': styleConfigs.getSelectionMarkerEmphasisOpacity()
};
this.changeSelectionAreaMarkerBound(null, highlightStyles); // change draw styles without the modification of bound
},
/** @private */
_restoreSelectionAreaMarker: function()
{
var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs();
var highlightStyles = {
'strokeColor': styleConfigs.getSelectionMarkerStrokeColor(),
'strokeWidth': styleConfigs.getSelectionMarkerStrokeWidth(),
'fillColor': styleConfigs.getSelectionMarkerFillColor(),
'opacity': styleConfigs.getSelectionMarkerOpacity()
};
this.changeSelectionAreaMarkerBound(null, highlightStyles); // change draw styles without the modification of bound
},
/**
* Pulse selection marker several times to get the attention of user.
* @param {Int} duration Duration of the whole process, in ms.
* @param {Int} pulseCount The times of highlighting marker.
*/
pulseSelectionAreaMarker: function(duration, pulseCount)
{
if (this.getUiSelectionAreaMarker())
{
if (!duration)
duration = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerDefPulseDuration() || 0;
if (!pulseCount)
pulseCount = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerDefPulseCount() || 1;
if (!duration)
return;
var interval = duration / pulseCount;
this.doPulseSelectionAreaMarker(interval, pulseCount);
}
return this;
},
/** @private */
doPulseSelectionAreaMarker: function(interval, pulseCount)
{
this._highlightSelectionAreaMarker();
//if (pulseCount <= 1)
setTimeout(this._restoreSelectionAreaMarker.bind(this), interval);
if (pulseCount > 1)
setTimeout(this.doPulseSelectionAreaMarker.bind(this, interval, pulseCount - 1), interval * 2);
},
///////////////////////// Methods about selecting region ////////////////////////////////////
/**
* Start a selecting operation from coord.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the selecting region will toggle selecting state inside it rather than select them directly.
*/
startSelecting: function(screenCoord, toggleFlag)
{
if (toggleFlag === undefined)
toggleFlag = this.getIsToggleSelectOn();
if (!toggleFlag)
this.deselectAll();
var M = Kekule.Editor.SelectMode;
var mode = this.getSelectMode();
this._currSelectMode = mode;
return (mode === M.POLYLINE || mode === M.POLYGON)?
this.startSelectingCurveDrag(screenCoord, toggleFlag):
this.startSelectingBoxDrag(screenCoord, toggleFlag);
},
/**
* Add a new anchor coord of selecting region.
* This method is called when pointer device moving in selecting.
* @param {Hash} screenCoord
*/
addSelectingAnchorCoord: function(screenCoord)
{
var M = Kekule.Editor.SelectMode;
var mode = this._currSelectMode;
return (mode === M.POLYLINE || mode === M.POLYGON)?
this.dragSelectingCurveToCoord(screenCoord):
this.dragSelectingBoxToCoord(screenCoord);
},
/**
* Selecting operation end.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the selecting region will toggle selecting state inside it rather than select them directly.
*/
endSelecting: function(screenCoord, toggleFlag)
{
if (toggleFlag === undefined)
toggleFlag = this.getIsToggleSelectOn();
var M = Kekule.Editor.SelectMode;
var mode = this._currSelectMode;
var enablePartial = this.getEditorConfigs().getInteractionConfigs().getEnablePartialAreaSelecting();
var objs;
if (mode === M.POLYLINE || mode === M.POLYGON)
{
var polygonCoords = this._selectingCurveCoords;
// simplify the polygon first
var threshold = this.getEditorConfigs().getInteractionConfigs().getSelectingCurveSimplificationDistanceThreshold();
var simpilfiedCoords = Kekule.GeometryUtils.simplifyCurveToLineSegments(polygonCoords, threshold);
//console.log('simplify selection', polygonCoords.length, simpilfiedCoords.length);
this.endSelectingCurveDrag(screenCoord, toggleFlag);
if (mode === M.POLYLINE)
{
var lineWidth = this.getEditorConfigs().getInteractionConfigs().getSelectingBrushWidth();
objs = this.getObjectsIntersetExtendedPolyline(simpilfiedCoords, lineWidth);
}
else // if (mode === M.POLYGON)
{
objs = this.getObjectsInPolygon(simpilfiedCoords, enablePartial);
this.endSelectingCurveDrag(screenCoord, toggleFlag);
}
}
else // M.RECT or M.ANCESTOR
{
var startCoord = this._selectingBoxStartCoord;
var box = Kekule.BoxUtils.createBox(startCoord, screenCoord);
objs = this.getObjectsInScreenBox(box, enablePartial);
this.endSelectingBoxDrag(screenCoord, toggleFlag);
}
/*
if (objs && objs.length)
{
if (this._isInAncestorSelectMode()) // need to change to select standalone ancestors
{
objs = this._getAllStandaloneAncestorObjs(objs); // get standalone ancestors (e.g. molecule)
//objs = this._getAllCoordDependantObjs(objs); // but select there coord dependant children (e.g. atoms and bonds)
}
if (toggleFlag)
this.toggleSelectingState(objs);
else
this.select(objs);
}
*/
objs = this._getActualSelectedObjsInSelecting(objs);
if (toggleFlag)
this.toggleSelectingState(objs);
else
this.select(objs);
this.hideSelectingMarker();
},
/**
* Cancel current selecting operation.
*/
cancelSelecting: function()
{
this.hideSelectingMarker();
},
/** @private */
_getActualSelectedObjsInSelecting: function(objs)
{
if (objs && objs.length)
{
if (this._isInAncestorSelectMode()) // need to change to select standalone ancestors
{
objs = this._getAllStandaloneAncestorObjs(objs); // get standalone ancestors (e.g. molecule)
//objs = this._getAllCoordDependantObjs(objs); // but select there coord dependant children (e.g. atoms and bonds)
}
return objs;
}
else
return [];
},
/** @private */
_isInAncestorSelectMode: function()
{
return this.getSelectMode() === Kekule.Editor.SelectMode.ANCESTOR;
},
/** @private */
_getAllStandaloneAncestorObjs: function(objs)
{
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj && obj.getStandaloneAncestor)
obj = obj.getStandaloneAncestor();
AU.pushUnique(result, obj);
}
return result;
},
/* @private */
/*
_getAllCoordDependantObjs: function(objs)
{
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj && obj.getCoordDependentObjects)
AU.pushUnique(result, obj.getCoordDependentObjects());
}
return result;
},
*/
/**
* Start to drag a selecting box from coord.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly.
*/
startSelectingBoxDrag: function(screenCoord, toggleFlag)
{
//this.setInteractionStartCoord(screenCoord);
this._selectingBoxStartCoord = screenCoord;
/*
if (!toggleFlag)
this.deselectAll();
*/
//this.setEditorState(Kekule.Editor.EditorState.SELECTING);
},
/**
* Drag selecting box to a new coord.
* @param {Hash} screenCoord
*/
dragSelectingBoxToCoord: function(screenCoord)
{
//var startCoord = this.getInteractionStartCoord();
var startCoord = this._selectingBoxStartCoord;
var endCoord = screenCoord;
this.changeSelectingMarkerBox(startCoord, endCoord);
},
/**
* Selecting box drag end.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly.
*/
endSelectingBoxDrag: function(screenCoord, toggleFlag)
{
//var startCoord = this.getInteractionStartCoord();
var startCoord = this._selectingBoxStartCoord;
//this.setInteractionEndCoord(coord);
this._selectingBoxEndCoord = screenCoord;
/*
var box = Kekule.BoxUtils.createBox(startCoord, screenCoord);
var enablePartial = this.getEditorConfigs().getInteractionConfigs().getEnablePartialAreaSelecting();
if (toggleFlag)
this.toggleSelectingStateOfObjectsInScreenBox(box, enablePartial);
else
this.selectObjectsInScreenBox(box, enablePartial);
this.hideSelectingMarker();
*/
},
/**
* Start to drag a selecting curve from coord.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly.
*/
startSelectingCurveDrag: function(screenCoord, toggleFlag)
{
//this.setInteractionStartCoord(screenCoord);
this._selectingCurveCoords = [screenCoord];
//this.setEditorState(Kekule.Editor.EditorState.SELECTING);
},
/**
* Drag selecting curve to a new coord.
* @param {Hash} screenCoord
*/
dragSelectingCurveToCoord: function(screenCoord)
{
//var startCoord = this.getInteractionStartCoord();
this._selectingCurveCoords.push(screenCoord);
this.changeSelectingMarkerCurve(this._selectingCurveCoords, this._currSelectMode === Kekule.Editor.SelectMode.POLYGON);
},
/**
* Selecting curve drag end.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly.
*/
endSelectingCurveDrag: function(screenCoord, toggleFlag)
{
this._selectingCurveCoords.push(screenCoord);
/*
var box = Kekule.BoxUtils.createBox(startCoord, screenCoord);
var enablePartial = this.getEditorConfigs().getInteractionConfigs().getEnablePartialAreaSelecting();
if (toggleFlag)
this.toggleSelectingStateOfObjectsInScreenBox(box, enablePartial);
else
this.selectObjectsInScreenBox(box, enablePartial);
this.hideSelectingMarker();
*/
},
/**
* Try select a object on coord directly.
* @param {Hash} coord
* @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly.
*/
selectOnCoord: function(coord, toggleFlag)
{
if (toggleFlag === undefined)
toggleFlag = this.getIsToggleSelectOn();
//console.log('select on coord');
var obj = this.getTopmostBasicObjectAtCoord(coord, this.getCurrBoundInflation());
if (obj)
{
var objs = this._getActualSelectedObjsInSelecting([obj]);
if (objs)
{
if (toggleFlag)
this.toggleSelectingState(objs);
else
this.select(objs);
}
}
},
// about selection area marker
/**
* Modify hot track marker to bind to newBoundInfo.
* @private
*/
changeSelectingMarkerBound: function(newBoundInfo, drawStyles)
{
var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs();
if (!drawStyles) // use the default one
drawStyles = {
'strokeColor': styleConfigs.getSelectingMarkerStrokeColor(),
'strokeWidth': styleConfigs.getSelectingMarkerStrokeWidth(),
'strokeDash': styleConfigs.getSelectingMarkerStrokeDash(),
'fillColor': styleConfigs.getSelectingMarkerFillColor(),
'opacity': styleConfigs.getSelectingMarkerOpacity()
};
var marker = this.getUiSelectingMarker();
marker.setVisible(true);
//console.log('change hot track', bound, drawStyles);
this.modifyShapeBasedMarker(marker, newBoundInfo, drawStyles, true);
return this;
},
changeSelectingMarkerCurve: function(screenCoords, isPolygon)
{
var ctxCoords = [];
for (var i = 0, l = screenCoords.length - 1; i < l; ++i)
{
ctxCoords.push(this.screenCoordToContext(screenCoords[i]));
}
var shapeInfo = Kekule.Render.MetaShapeUtils.createShapeInfo(
isPolygon? Kekule.Render.MetaShapeType.POLYGON: Kekule.Render.MetaShapeType.POLYLINE,
ctxCoords
);
var drawStyle;
if (!isPolygon)
{
var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs();
drawStyle = {
'strokeColor': styleConfigs.getSelectingBrushMarkerStrokeColor(),
'strokeWidth': this.getEditorConfigs().getInteractionConfigs().getSelectingBrushWidth(),
'strokeDash': styleConfigs.getSelectingBrushMarkerStrokeDash(),
//'fillColor': styleConfigs.getSelectingMarkerFillColor(),
'lineCap': styleConfigs.getSelectingBrushMarkerStrokeLineCap(),
'lineJoin': styleConfigs.getSelectingBrushMarkerStrokeLineJoin(),
'opacity': styleConfigs.getSelectingBrushMarkerOpacity()
};
}
return this.changeSelectingMarkerBound(shapeInfo, drawStyle);
},
/**
* Change the rect box of selection marker.
* Coord is based on screen system.
* @private
*/
changeSelectingMarkerBox: function(screenCoord1, screenCoord2)
{
//var coord1 = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord1);
//var coord2 = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord2);
var coord1 = this.screenCoordToContext(screenCoord1);
var coord2 = this.screenCoordToContext(screenCoord2);
var shapeInfo = Kekule.Render.MetaShapeUtils.createShapeInfo(
Kekule.Render.MetaShapeType.RECT,
[{'x': Math.min(coord1.x, coord2.x), 'y': Math.min(coord1.y, coord2.y)},
{'x': Math.max(coord1.x, coord2.x), 'y': Math.max(coord1.y, coord2.y)}]
);
return this.changeSelectingMarkerBound(shapeInfo);
},
/** @private */
hideSelectingMarker: function()
{
var marker = this.getUiSelectingMarker();
if (marker)
{
this.hideUiMarker(marker, true);
}
},
/** @private */
showSelectingMarker: function()
{
var marker = this.getUiSelectingMarker();
if (marker)
{
this.showUiMarker(marker, true);
}
},
// methods about selection marker
/**
* Returns the region of screenCoord relative to selection marker.
* @private
*/
getCoordRegionInSelectionMarker: function(screenCoord, edgeInflation)
{
var R = Kekule.Editor.BoxRegion;
var CU = Kekule.CoordUtils;
var coord = this.screenCoordToContext(screenCoord);
var marker = this.getUiSelectionAreaMarker();
if (marker && marker.getVisible())
{
var box = this.getUiSelectionAreaContainerBox();
if (Kekule.ObjUtils.isUnset(edgeInflation))
edgeInflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerEdgeInflation();
var halfInf = (edgeInflation / 2) || 0;
var coord1 = CU.substract({'x': box.x1, 'y': box.y1}, {'x': halfInf, 'y': halfInf});
var coord2 = CU.add({'x': box.x2, 'y': box.y2}, {'x': halfInf, 'y': halfInf});
if ((coord.x < coord1.x) || (coord.y < coord1.y) || (coord.x > coord2.x) || (coord.y > coord2.y))
return R.OUTSIDE;
//coord2 = CU.substract(coord2, coord1);
var delta1 = CU.substract(coord, coord1);
var delta2 = CU.substract(coord2, coord);
var dx1 = delta1.x;
var dx2 = delta2.x;
var dy1 = delta1.y;
var dy2 = delta2.y;
if (dy1 < dy2) // on top half
{
if (dx1 < dx2) // on left part
{
if (dy1 <= edgeInflation)
return (dx1 <= edgeInflation)? R.CORNER_TL: R.EDGE_TOP;
else if (dx1 <= edgeInflation)
return R.EDGE_LEFT;
else
return R.INSIDE;
}
else // on right part
{
if (dy1 <= edgeInflation)
return (dx2 <= edgeInflation)? R.CORNER_TR: R.EDGE_TOP;
else if (dx2 <= edgeInflation)
return R.EDGE_RIGHT;
else
return R.INSIDE;
}
}
else // on bottom half
{
if (dx1 < dx2) // on left part
{
if (dy2 <= edgeInflation)
return (dx1 <= edgeInflation)? R.CORNER_BL: R.EDGE_BOTTOM;
else if (dx1 <= edgeInflation)
return R.EDGE_LEFT;
else
return R.INSIDE;
}
else // on right part
{
if (dy2 <= edgeInflation)
return (dx2 <= edgeInflation)? R.CORNER_BR: R.EDGE_BOTTOM;
else if (dx2 <= edgeInflation)
return R.EDGE_RIGHT;
else
return R.INSIDE;
}
}
}
return R.OUTSIDE;
},
/**
* Check if a point coord based on screen inside selection marker.
* @private
*/
isCoordInSelectionMarkerBound: function(screenCoord)
{
/*
//var coord = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord);
var coord = this.screenCoordToContext(screenCoord);
var marker = this.getUiSelectionAreaMarker();
if (marker && marker.getVisible())
{
var shapeInfo = marker.getShapeInfo();
return shapeInfo? Kekule.Render.MetaShapeUtils.isCoordInside(coord, shapeInfo): false;
}
else
return false;
*/
return (this.getCoordRegionInSelectionMarker(screenCoord) !== Kekule.Editor.BoxRegion.OUTSIDE);
},
//////////////////////////////////////////////////////////////////////////////
/////////////////////// methods about selection ////////////////////////////
/**
* Returns override render options that need to be applied to each selected objects.
* Descendants should override this method.
* @returns {Hash}
* @private
*/
getObjSelectedRenderOptions: function()
{
// debug
/*
if (!this._selectedRenderOptions)
this._selectedRenderOptions = {'color': '#000055', 'strokeWidth': 2, 'atomRadius': 5};
*/
return this._selectedRenderOptions;
},
/**
* Returns method to add render option override item of chemObj.
* In 2D render mode, this method should returns chemObj.addOverrideRenderOptionItem,
* in 3D render mode, this method should returns chemObj.addOverrideRender3DOptionItem.
* @private
*/
_getObjRenderOptionItemAppendMethod: function(chemObj)
{
return (this.getRenderType() === Kekule.Render.RendererType.R3D)?
chemObj.addOverrideRender3DOptionItem:
chemObj.addOverrideRenderOptionItem;
},
/**
* Returns method to remove render option override item of chemObj.
* In 2D render mode, this method should returns chemObj.removeOverrideRenderOptionItem,
* in 3D render mode, this method should returns chemObj.removeOverrideRender3DOptionItem.
* @private
*/
_getObjRenderOptionItemRemoveMethod: function(chemObj)
{
return (this.getRenderType() === Kekule.Render.RendererType.R3D )?
chemObj.removeOverrideRender3DOptionItem:
chemObj.removeOverrideRenderOptionItem;
},
/** @private */
_addSelectRenderOptions: function(chemObj)
{
var selOps = this.getObjSelectedRenderOptions();
if (selOps)
{
//console.log('_addSelectRenderOptions', chemObj, selOps);
var method = this._getObjRenderOptionItemAppendMethod(chemObj);
//if (!method)
//console.log(chemObj.getClassName());
return method.apply(chemObj, [selOps]);
}
else
return null;
},
/** @private */
_removeSelectRenderOptions: function(chemObj)
{
var selOps = this.getObjSelectedRenderOptions();
if (selOps)
{
//console.log('_removeSelectRenderOptions', chemObj);
var method = this._getObjRenderOptionItemRemoveMethod(chemObj);
return method.apply(chemObj, [this.getObjSelectedRenderOptions()]);
}
else
return null;
},
/** Notify that a continuous selection update is underway. UI need not to be changed. */
beginUpdateSelection: function()
{
this.beginUpdateObject();
--this._objSelectFlag;
},
/** Notify that a continuous selection update is done. UI need to be changed. */
endUpdateSelection: function()
{
++this._objSelectFlag;
if (this._objSelectFlag >= 0)
{
this.selectionChanged();
}
this.endUpdateObject();
},
/** Check if the editor is under continuous selection update. */
isUpdatingSelection: function()
{
return (this._objSelectFlag < 0);
},
/**
* Notify selection is changed or object in selection has changed.
* @private
*/
selectionChanged: function()
{
/*
var selection = this.getSelection();
if (selection && selection.length) // at least one selected object
{
var obj, boundItem, bound, box;
var containBox;
// calc out bound box to contain all selected objects
for (var i = 0, l = selection.length; i < l; ++i)
{
obj = selection[i];
boundItem = this.findBoundMapItem(obj);
if (boundItem)
{
bound = boundItem.boundInfo;
if (bound)
{
box = Kekule.Render.MetaShapeUtils.getContainerBox(bound);
if (box)
{
if (!containBox)
containBox = box;
else
containBox = Kekule.BoxUtils.getContainerBox(containBox, box);
}
}
}
}
if (containBox)
{
var inflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerInflation() || 0;
if (inflation)
containBox = Kekule.BoxUtils.inflateBox(containBox, inflation);
this.changeSelectionMarkerBox(containBox);
}
else // no selected
this.removeSelectionMarker();
}
else // no selected
{
this.removeSelectionMarker();
}
*/
if (!this.isUpdatingSelection())
{
this.notifyPropSet('selection', this.getSelection());
this.invokeEvent('selectionChange');
return this.doSelectionChanged();
}
},
/**
* Do actual work of method selectionChanged.
* Descendants may override this method.
*/
doSelectionChanged: function()
{
this.recalcSelectionAreaMarker();
},
/**
* Check if an object is in selection.
* @param {Kekule.ChemObject} obj
* @returns {Bool}
*/
isInSelection: function(obj)
{
if (!obj)
return false;
return this.getSelection().indexOf(obj) >= 0;
},
/**
* Add an object to selection.
* Descendants can override this method.
* @param {Kekule.ChemObject} obj
*/
addObjToSelection: function(obj)
{
if (!obj)
return this;
var selection = this.getSelection();
Kekule.ArrayUtils.pushUnique(selection, obj.getNearestSelectableObject());
this._addSelectRenderOptions(obj);
this.selectionChanged();
return this;
},
/**
* Remove an object (and all its child objects) from selection.
* Descendants can override this method.
* @param {Kekule.ChemObject} obj
*/
removeObjFromSelection: function(obj, doNotNotifySelectionChange)
{
if (!obj)
return this;
var selection = this.getSelection();
var relObj = obj.getNearestSelectableObject && obj.getNearestSelectableObject();
if (relObj === obj)
relObj === null;
Kekule.ArrayUtils.remove(selection, obj);
this._removeSelectRenderOptions(obj);
if (relObj)
{
Kekule.ArrayUtils.remove(selection, relObj);
this._removeSelectRenderOptions(relObj);
}
// remove possible child objects
for (var i = selection.length - 1; i >= 0; --i)
{
var remainObj = selection[i];
if (remainObj.isChildOf && (remainObj.isChildOf(obj) || (relObj && remainObj.isChildOf(relObj))))
this.removeObjFromSelection(remainObj, true);
}
if (!doNotNotifySelectionChange)
this.selectionChanged();
return this;
},
/**
* Select all first-level objects in editor.
*/
selectAll: function()
{
var selection = [];
var obj = this.getChemObj();
if (obj)
{
var children = obj.getChildren() || [];
if (children.length)
selection = children;
else
selection = [obj];
}
return this.select(selection);
},
/**
* Deselect all objects in selection
*/
deselectAll: function()
{
var selection = this.getSelection();
return this.removeFromSelection(selection);
},
/**
* Make a obj or set of objs be selected.
* @param {Variant} objs A object or an array of objects.
*/
select: function(objs)
{
this.beginUpdateSelection();
try
{
this.deselectAll();
this.addToSelection(objs);
}
finally
{
//console.log(this.getPainter().getRenderer().getClassName(), this.getPainter().getRenderer().getRenderCache(this.getDrawContext()));
this.endUpdateSelection();
}
return this;
},
/**
* Add object or an array of objects to selection.
* @param {Variant} param A object or an array of objects.
*/
addToSelection: function(param)
{
if (!param)
return;
var objs = DataType.isArrayValue(param)? param: [param];
this.beginUpdateSelection();
try
{
for (var i = 0, l = objs.length; i < l; ++i)
{
this.addObjToSelection(objs[i]);
}
}
finally
{
this.endUpdateSelection();
}
return this;
},
/**
* Remove object or an array of objects from selection.
* @param {Variant} param A object or an array of objects.
*/
removeFromSelection: function(param)
{
if (!param || !param.length)
return;
var objs = DataType.isArrayValue(param)? param: [param];
this.beginUpdateSelection();
try
{
for (var i = objs.length - 1; i >= 0; --i)
{
this.removeObjFromSelection(objs[i]);
}
}
finally
{
this.endUpdateSelection();
}
return this;
},
/**
* Toggle selection state of object or an array of objects.
* @param {Variant} param A object or an array of objects.
*/
toggleSelectingState: function(param)
{
if (!param)
return;
var objs = DataType.isArrayValue(param)? param: [param];
this.beginUpdateSelection();
try
{
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var relObj = obj.getNearestSelectableObject && obj.getNearestSelectableObject();
if (this.isInSelection(obj))
this.removeObjFromSelection(obj);
else if (relObj && this.isInSelection(relObj))
this.removeObjFromSelection(relObj);
else
this.addObjToSelection(obj);
}
}
finally
{
this.endUpdateSelection();
}
return this;
},
/**
* Check if there is objects selected currently.
* @returns {Bool}
*/
hasSelection: function()
{
return !!this.getSelection().length;
},
/**
* Delete and free all selected objects.
*/
deleteSelectedObjs: function()
{
// TODO: unfinished
},
/** @private */
requestAutoCheckIssuesIfNecessary: function()
{
if (this.getEnableAutoIssueCheck())
this._tryCheckIssueOnIdle();
},
/**
* Check issues when not updating/manipulating objects in editor.
* @private
*/
_tryCheckIssueOnIdle: function()
{
//console.log('try check', this.isUpdatingObject(), this.isManipulatingObject());
if (!this.isUpdatingObject() && !this.isManipulatingObject())
{
return this.checkIssues();
}
else
return null;
},
/**
* Create a default issue check executor instance.
* Descendants may override this method.
* @returns {Kekule.IssueCheck.Executor}
* @private
*/
createIssueCheckExecutor: function()
{
return new Kekule.IssueCheck.ExecutorForEditor(this);
},
/**
* Check potential issues for objects in editor.
* @param {Kekule.ChemObject} rootObj Root object to check. If this param is ommited, all objects in editor will be checked.
* @returns {Array} Array of error check report result.
*/
checkIssues: function(rootObj)
{
var result = null;
var root = rootObj || this.getChemObj();
if (root && this.getEnableIssueCheck())
{
var checkExecutor = this.getIssueCheckExecutor(true);
result = checkExecutor.execute(root);
}
return result;
},
/**
* Get all objects interset a polyline defined by a set of screen coords.
* Here Object partial in the polyline width range will also be put in result.
* @param {Array} polylineScreenCoords
* @param {Number} lineWidth
* @returns {Array} All interseting objects.
*/
getObjectsIntersetExtendedPolyline: function(polylineScreenCoords, lineWidth)
{
var ctxCoords = [];
for (var i = 0, l = polylineScreenCoords.length; i < l; ++i)
{
ctxCoords.push(this.screenCoordToContext(polylineScreenCoords[i]));
}
var objs = [];
var boundInfos = this.getBoundInfoRecorder().getAllRecordedInfoOfContext(this.getObjContext());
var compareFunc = Kekule.Render.MetaShapeUtils.isIntersectingPolyline;
for (var i = 0, l = boundInfos.length; i < l; ++i)
{
var boundInfo = boundInfos[i];
var shapeInfo = boundInfo.boundInfo;
/*
if (!shapeInfo)
console.log(boundInfo);
*/
if (shapeInfo)
if (compareFunc(shapeInfo, ctxCoords, lineWidth))
objs.push(boundInfo.obj);
}
//console.log('selected', objs);
return objs;
},
/**
* Get all objects inside a polygon defined by a set of screen coords.
* @param {Array} polygonScreenCoords
* @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected.
* @returns {Array} All inside objects.
*/
getObjectsInPolygon: function(polygonScreenCoords, allowPartialAreaSelecting)
{
var ctxCoords = [];
for (var i = 0, l = polygonScreenCoords.length; i < l; ++i)
{
ctxCoords.push(this.screenCoordToContext(polygonScreenCoords[i]));
}
var objs = [];
var boundInfos = this.getBoundInfoRecorder().getAllRecordedInfoOfContext(this.getObjContext());
var compareFunc = allowPartialAreaSelecting? Kekule.Render.MetaShapeUtils.isIntersectingPolygon: Kekule.Render.MetaShapeUtils.isInsidePolygon;
for (var i = 0, l = boundInfos.length; i < l; ++i)
{
var boundInfo = boundInfos[i];
var shapeInfo = boundInfo.boundInfo;
/*
if (!shapeInfo)
console.log(boundInfo);
*/
if (shapeInfo)
if (compareFunc(shapeInfo, ctxCoords))
objs.push(boundInfo.obj);
}
//console.log('selected', objs);
return objs;
},
/**
* Get all objects inside a screen box.
* @param {Hash} screenBox
* @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected.
* @returns {Array} All inside objects.
*/
getObjectsInScreenBox: function(screenBox, allowPartialAreaSelecting)
{
var box = this.screenBoxToContext(screenBox);
var objs = [];
var boundInfos = this.getBoundInfoRecorder().getAllRecordedInfoOfContext(this.getObjContext());
var compareFunc = allowPartialAreaSelecting? Kekule.Render.MetaShapeUtils.isIntersectingBox: Kekule.Render.MetaShapeUtils.isInsideBox;
for (var i = 0, l = boundInfos.length; i < l; ++i)
{
var boundInfo = boundInfos[i];
var shapeInfo = boundInfo.boundInfo;
/*
if (!shapeInfo)
console.log(boundInfo);
*/
if (shapeInfo)
if (compareFunc(shapeInfo, box))
objs.push(boundInfo.obj);
}
//console.log('selected', objs);
return objs;
},
/**
* Select all objects inside a screen box.
* @param {Hash} box
* @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected.
* @returns {Array} All inside objects.
*/
selectObjectsInScreenBox: function(screenBox, allowPartialAreaSelecting)
{
var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting);
if (objs && objs.length)
this.select(objs);
return objs;
},
/**
* Add objects inside a screen box to selection.
* @param {Hash} box
* @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected.
* @returns {Array} All inside objects.
*/
addObjectsInScreenBoxToSelection: function(screenBox, allowPartialAreaSelecting)
{
var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting);
if (objs && objs.length)
this.addToSelection(objs);
return objs;
},
/**
* Remove objects inside a screen box from selection.
* @param {Hash} box
* @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be deselected.
* @returns {Array} All inside objects.
*/
removeObjectsInScreenBoxFromSelection: function(screenBox, allowPartialAreaSelecting)
{
var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting);
if (objs && objs.length)
this.removeFromSelection(objs);
return objs;
},
/**
* Toggle selection state of objects inside a screen box.
* @param {Hash} box
* @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be toggled.
* @returns {Array} All inside objects.
*/
toggleSelectingStateOfObjectsInScreenBox: function(screenBox, allowPartialAreaSelecting)
{
var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting);
if (objs && objs.length)
this.toggleSelectingState(objs);
return objs;
},
/**
* Returns a minimal box (in screen coord system) containing all objects' bounds in editor.
* @param {Array} objects
* @param {Float} objBoundInflation Inflation of each object's bound.
* @returns {Hash}
*/
getObjectsContainerBox: function(objects, objBoundInflation)
{
var objs = Kekule.ArrayUtils.toArray(objects);
var inf = objBoundInflation || 0;
var bounds = [];
var containerBox = null;
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj);
if (infos && infos.length)
{
for (var j = 0, k = infos.length; j < k; ++j)
{
var info = infos[j];
var bound = info.boundInfo;
if (bound)
{
// inflate
if (inf)
bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, inf);
var box = Kekule.Render.MetaShapeUtils.getContainerBox(bound);
containerBox = containerBox? Kekule.BoxUtils.getContainerBox(containerBox, box): box;
}
}
}
}
return containerBox;
},
/**
* Returns the intersection state of object container box and editor client box.
* @param {Array} objs
* @returns {Int} Value from {@link Kekule.IntersectionState}
*/
getObjectsBoxAndClientBoxRelation: function(objs)
{
var containerBox = this.getObjectsContainerBox(objs);
if (containerBox)
{
var editorBox = this.getVisibleClientScreenBox();
return Kekule.BoxUtils.getIntersectionState(containerBox, editorBox);
}
},
/**
* Returns container box (in screen coord system) that contains all objects in selection.
* @param {Number} objBoundInflation
* @returns {Hash}
*/
getSelectionContainerBox: function(objBoundInflation)
{
return this.getObjectsContainerBox(this.getSelection(), objBoundInflation);
},
/**
* Returns whether current selected objects can be seen from screen (not all of them
* are in hidden scroll area).
*/
isSelectionVisible: function()
{
var selectionBox = this.getSelectionContainerBox();
if (selectionBox)
{
/*
var editorDim = this.getClientDimension();
var editorOffset = this.getClientScrollPosition();
var editorBox = {
'x1': editorOffset.x, 'y1': editorOffset.y,
'x2': editorOffset.x + editorDim.width, 'y2': editorOffset.y + editorDim.height
};
*/
var editorBox = this.getVisibleClientScreenBox();
//console.log(selectionBox, editorBox, Kekule.BoxUtils.getIntersection(selectionBox, editorBox));
return Kekule.BoxUtils.hasIntersection(selectionBox, editorBox);
}
else
return false;
},
/////////// methods about object manipulations /////////////////////////////
/**
* Returns width and height info of obj.
* @param {Object} obj
* @returns {Hash}
*/
getObjSize: function(obj)
{
return this.doGetObjSize(obj);
},
/**
* Do actual job of getObjSize. Descendants may override this method.
* @param {Object} obj
* @returns {Hash}
*/
doGetObjSize: function(obj)
{
var coordMode = this.getCoordMode();
//var allowCoordBorrow = this.getAllowCoordBorrow();
return obj.getSizeOfMode? obj.getSizeOfMode(coordMode):
null;
},
/**
* Set dimension of obj.
* @param {Object} obj
* @param {Hash} size
*/
setObjSize: function(obj, size)
{
this.doSetObjSize(obj, size);
this.objectChanged(obj);
},
/**
* Do actual work of setObjSize.
* @param {Object} obj
* @param {Hash} size
*/
doSetObjSize: function(obj, dimension)
{
if (obj.setSizeOfMode)
obj.setSizeOfMode(dimension, this.getCoordMode());
},
/**
* Returns own coord of obj.
* @param {Object} obj
* @param {Int} coordPos Value from {@link Kekule.Render.CoordPos}, relative position of coord in object.
* @returns {Hash}
*/
getObjCoord: function(obj, coordPos)
{
return this.doGetObjCoord(obj, coordPos);
},
/**
* Do actual job of getObjCoord. Descendants may override this method.
* @private
*/
doGetObjCoord: function(obj, coordPos)
{
if (!obj)
return null;
var coordMode = this.getCoordMode();
var allowCoordBorrow = this.getAllowCoordBorrow();
var result = obj.getAbsBaseCoord? obj.getAbsBaseCoord(coordMode, allowCoordBorrow):
obj.getAbsCoordOfMode? obj.getAbsCoordOfMode(coordMode, allowCoordBorrow):
obj.getCoordOfMode? obj.getCoordOfMode(coordMode, allowCoordBorrow):
null;
if (coordMode === Kekule.CoordMode.COORD2D && Kekule.ObjUtils.notUnset(coordPos)) // appoint coord pos, need further calculation
{
var baseCoordPos = Kekule.Render.CoordPos.DEFAULT;
if (coordPos !== baseCoordPos)
{
var allowCoordBorrow = this.getAllowCoordBorrow();
var box = obj.getExposedContainerBox? obj.getExposedContainerBox(coordMode, allowCoordBorrow):
obj.getContainerBox? obj.getContainerBox(coordMode, allowCoordBorrow): null;
//console.log(obj.getClassName(), coordPos, objBasePos, box);
if (box)
{
if (coordPos === Kekule.Render.CoordPos.CORNER_TL)
{
var delta = {x: (box.x2 - box.x1) / 2, y: (box.y2 - box.y1) / 2};
result.x = result.x - delta.x;
result.y = result.y + delta.y;
}
}
}
}
return result;
/*
return obj.getAbsBaseCoord2D? obj.getAbsBaseCoord2D(allowCoordBorrow):
obj.getAbsCoord2D? obj.getAbsCoord2D(allowCoordBorrow):
obj.getCoord2D? obj.getCoord2D(allowCoordBorrow):
null;
*/
},
/**
* Set own coord of obj.
* @param {Object} obj
* @param {Hash} coord
* @param {Int} coordPos Value from {@link Kekule.Render.CoordPos}, relative position of coord in object.
*/
setObjCoord: function(obj, coord, coordPos)
{
this.doSetObjCoord(obj, coord, coordPos);
this.objectChanged(obj);
},
/**
* Do actual job of setObjCoord. Descendants can override this method.
* @private
*/
doSetObjCoord: function(obj, coord, coordPos)
{
var newCoord = Object.create(coord);
var coordMode = this.getCoordMode();
//console.log(obj.setAbsBaseCoord, obj.setAbsCoordOfMode, obj.setAbsCoordOfMode);
if (coordMode === Kekule.CoordMode.COORD2D && Kekule.ObjUtils.notUnset(coordPos)) // appoint coord pos, need further calculation
{
//var baseCoordPos = obj.getCoordPos? obj.getCoordPos(coordMode): Kekule.Render.CoordPos.DEFAULT;
var baseCoordPos = Kekule.Render.CoordPos.DEFAULT;
if (coordPos !== baseCoordPos)
{
var allowCoordBorrow = this.getAllowCoordBorrow();
var box = obj.getExposedContainerBox? obj.getExposedContainerBox(coordMode, allowCoordBorrow):
obj.getContainerBox? obj.getContainerBox(coordMode, allowCoordBorrow): null;
//console.log(obj.getClassName(), coordPos, objBasePos, box);
if (box)
{
var delta = {x: (box.x2 - box.x1) / 2, y: (box.y2 - box.y1) / 2};
if (coordPos === Kekule.Render.CoordPos.CORNER_TL)
// base coord on center and set coord as top left
{
newCoord.x = coord.x + delta.x;
newCoord.y = coord.y - delta.y;
}
}
}
}
if (obj.setAbsBaseCoord)
{
obj.setAbsBaseCoord(newCoord, coordMode);
}
else if (obj.setAbsCoordOfMode)
{
obj.setAbsCoordOfMode(newCoord, coordMode);
}
else if (obj.setAbsCoordOfMode)
{
obj.setCoordOfMode(newCoord, coordMode);
}
},
/**
* Get object's coord on context.
* @param {Object} obj
* @returns {Hash}
*/
getObjectContextCoord: function(obj, coordPos)
{
var coord = this.getObjCoord(obj, coordPos);
return this.objCoordToContext(coord);
},
/**
* Change object's coord on context.
* @param {Object} obj
* @param {Hash} contextCoord
*/
setObjectContextCoord: function(obj, contextCoord, coordPos)
{
var coord = this.contextCoordToObj(contextCoord);
if (coord)
this.setObjCoord(obj, coord, coordPos);
},
/**
* Get object's coord on screen.
* @param {Object} obj
* @returns {Hash}
*/
getObjectScreenCoord: function(obj, coordPos)
{
var coord = this.getObjCoord(obj, coordPos);
return this.objCoordToScreen(coord);
},
/**
* Change object's coord on screen.
* @param {Object} obj
* @param {Hash} contextCoord
*/
setObjectScreenCoord: function(obj, screenCoord, coordPos)
{
var coord = this.screenCoordToObj(screenCoord);
if (coord)
this.setObjCoord(obj, coord, coordPos);
},
/**
* Get coord of obj.
* @param {Object} obj
* @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here.
* @returns {Hash}
*/
getCoord: function(obj, coordSys, coordPos)
{
/*
if (coordSys === Kekule.Render.CoordSystem.CONTEXT)
return this.getObjectContextCoord(obj);
else
return this.getObjCoord(obj);
*/
var objCoord = this.getObjCoord(obj, coordPos);
return this.translateCoord(objCoord, Kekule.Editor.CoordSys.OBJ, coordSys);
},
/**
* Set coord of obj.
* @param {Object} obj
* @param {Hash} value
* @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here.
*/
setCoord: function(obj, value, coordSys, coordPos)
{
/*
if (coordSys === Kekule.Render.CoordSystem.CONTEXT)
this.setObjectContextCoord(obj, value);
else
this.setObjCoord(obj, value);
*/
var objCoord = this.translateCoord(value, coordSys, Kekule.Editor.CoordSys.OBJ);
this.setObjCoord(obj, objCoord, coordPos);
},
/**
* Get size of obj.
* @param {Object} obj
* @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here.
* @returns {Hash}
*/
getSize: function(obj, coordSys)
{
var objSize = this.getObjSize(obj);
return this.translateCoord(objSize, Kekule.Editor.CoordSys.OBJ, coordSys);
},
/**
* Set size of obj.
* @param {Object} obj
* @param {Hash} value
* @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here.
*/
setSize: function(obj, value, coordSys)
{
var objSize = this.translateCoord(value, coordSys, Kekule.Editor.CoordSys.OBJ);
this.setObjSize(obj, objSize);
},
// Coord translate methods
/*
* Translate coord to value of another coord system.
* @param {Hash} coord
* @param {Int} fromSys
* @param {Int} toSys
*/
/*
translateCoord: function(coord, fromSys, toSys)
{
if (!coord)
return null;
var S = Kekule.Editor.CoordSys;
if (fromSys === S.SCREEN)
{
if (toSys === S.SCREEN)
return coord;
else if (toSys === S.CONTEXT)
return this.getObjDrawBridge()? this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), coord): coord;
else // S.OBJ
{
var contextCoord = this.getObjDrawBridge()? this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), coord): coord;
return this.getObjContext()? this.getRootRenderer().transformCoordToObj(this.getObjContext(), this.getChemObj(), contextCoord): coord;
}
}
else if (fromSys === S.CONTEXT)
{
if (toSys === S.SCREEN)
return this.getObjDrawBridge()? this.getObjDrawBridge().transformContextCoordToScreen(this.getObjContext(), coord): coord;
else if (toSys === S.CONTEXT)
return coord;
else // S.OBJ
return this.getObjContext()? this.getRootRenderer().transformCoordToObj(this.getObjContext(), this.getChemObj(), coord): coord;
}
else // fromSys === S.OBJ
{
if (toSys === S.SCREEN)
{
var contextCoord = this.getRootRenderer().transformCoordToContext(this.getObjContext(), this.getChemObj(), coord);
return this.getObjDrawBridge()? this.getObjDrawBridge().transformContextCoordToScreen(this.getObjContext(), contextCoord): coord;
}
else if (toSys === S.CONTEXT)
return this.getObjContext()? this.getRootRenderer().transformCoordToContext(this.getObjContext(), this.getChemObj(), coord): coord;
else // S.OBJ
return coord;
}
},
*/
/*
* Translate a distance value to a distance in another coord system.
* @param {Hash} coord
* @param {Int} fromSys
* @param {Int} toSys
*/
/*
translateDistance: function(distance, fromSys, toSys)
{
var coord0 = {'x': 0, 'y': 0, 'z': 0};
var coord1 = {'x': distance, 'y': 0, 'z': 0};
var transCoord0 = this.translateCoord(coord0, fromSys, toSys);
var transCoord1 = this.translateCoord(coord1, fromSys, toSys);
return Kekule.CoordUtils.getDistance(transCoord0, transCoord1);
},
*/
/**
* Transform sizes and coords of objects based on coord sys of current editor.
* @param {Array} objects
* @param {Hash} transformParams
* @private
*/
transformCoordAndSizeOfObjects: function(objects, transformParams)
{
var coordMode = this.getCoordMode();
var allowCoordBorrow = this.getAllowCoordBorrow();
var matrix = (coordMode === Kekule.CoordMode.COORD3D)?
Kekule.CoordUtils.calcTransform3DMatrix(transformParams):
Kekule.CoordUtils.calcTransform2DMatrix(transformParams);
var childTransformParams = Object.extend({}, transformParams);
childTransformParams = Object.extend(childTransformParams, {
'translateX': 0,
'translateY': 0,
'translateZ': 0,
'center': {'x': 0, 'y': 0, 'z': 0}
});
var childMatrix = (coordMode === Kekule.CoordMode.COORD3D)?
Kekule.CoordUtils.calcTransform3DMatrix(childTransformParams):
Kekule.CoordUtils.calcTransform2DMatrix(childTransformParams);
for (var i = 0, l = objects.length; i < l; ++i)
{
var obj = objects[i];
obj.transformAbsCoordByMatrix(matrix, childMatrix, coordMode, true, allowCoordBorrow);
obj.scaleSize(transformParams.scale, coordMode, true, allowCoordBorrow);
}
},
/*
* Turn obj coord to context one.
* @param {Hash} objCoord
* @returns {Hash}
*/
/*
objCoordToContext: function(objCoord)
{
var S = Kekule.Editor.CoordSys;
return this.translateCoord(objCoord, S.OBJ, S.CONTEXT);
},
*/
/*
* Turn context coord to obj one.
* @param {Hash} contextCoord
* @returns {Hash}
*/
/*
contextCoordToObj: function(contextCoord)
{
var S = Kekule.Editor.CoordSys;
return this.translateCoord(contextCoord, S.CONTEXT, S.OBJ);
},
*/
/*
* Turn obj coord to screen one.
* @param {Hash} objCoord
* @returns {Hash}
*/
/*
objCoordToScreen: function(objCoord)
{
var S = Kekule.Editor.CoordSys;
return this.translateCoord(objCoord, S.OBJ, S.SCREEN);
},
*/
/*
* Turn screen coord to obj one.
* @param {Hash} contextCoord
* @returns {Hash}
*/
/*
screenCoordToObj: function(screenCoord)
{
var S = Kekule.Editor.CoordSys;
return this.translateCoord(screenCoord, S.SCREEN, S.OBJ);
},
*/
/*
* Turn screen based coord to context one.
* @param {Hash} screenCoord
* @returns {Hash}
*/
/*
screenCoordToContext: function(screenCoord)
{
var S = Kekule.Editor.CoordSys;
return this.translateCoord(screenCoord, S.SCREEN, S.CONTEXT);
},
*/
/*
* Turn context based coord to screen one.
* @param {Hash} screenCoord
* @returns {Hash}
*/
/*
contextCoordToScreen: function(screenCoord)
{
var S = Kekule.Editor.CoordSys;
return this.translateCoord(screenCoord, S.CONTEXT, S.SCREEN);
},
*/
/*
* Turn box coords based on screen system to context one.
* @param {Hash} screenCoord
* @returns {Hash}
*/
/*
screenBoxToContext: function(screenBox)
{
var coord1 = this.screenCoordToContext({'x': screenBox.x1, 'y': screenBox.y1});
var coord2 = this.screenCoordToContext({'x': screenBox.x2, 'y': screenBox.y2});
return {'x1': coord1.x, 'y1': coord1.y, 'x2': coord2.x, 'y2': coord2.y};
},
*/
///////////////////////////////////////////////////////
/**
* Create a default node at coord and append it to parent.
* @param {Hash} coord
* @param {Int} coordType Value from {@link Kekule.Editor.CoordType}
* @param {Kekule.StructureFragment} parent
* @returns {Kekule.ChemStructureNode}
* @private
*/
createDefaultNode: function(coord, coordType, parent)
{
var isoId = this.getEditorConfigs().getStructureConfigs().getDefIsotopeId();
var atom = new Kekule.Atom();
atom.setIsotopeId(isoId);
if (parent)
parent.appendNode(atom);
this.setCoord(atom, coord, coordType);
return atom;
},
/////////////////////////////////////////////////////////////////////////////
// methods about undo/redo and operation histories
/**
* Called after a operation is executed or reversed. Notify object has changed.
* @param {Object} operation
*/
operationDone: function(operation)
{
this.doOperationDone(operation);
},
/**
* Do actual job of {@link Kekule.Editor.AbstractEditor#operationDone}. Descendants should override this method.
* @private
*/
doOperationDone: function(operation)
{
// do nothing here
},
/**
* Pop all operations and empty history list.
*/
clearOperHistory: function()
{
var h = this.getOperHistory();
if (h)
h.clear();
},
/**
* Manually append an operation to the tail of operation history.
* @param {Kekule.Operation} operation
* @param {Bool} autoExec Whether execute the operation after pushing it.
*/
pushOperation: function(operation, autoExec)
{
// console.log('push operation');
if (operation)
{
var h = this.getOperHistory();
if (h)
{
h.push(operation);
}
this.getOperationsInCurrManipulation().push(operation);
if (autoExec)
{
this.beginUpdateObject();
try
{
operation.execute();
}
finally
{
this.endUpdateObject();
}
}
}
},
/**
* Manually pop an operation from the tail of operation history.
* @param {Bool} autoReverse Whether undo the operation after popping it.
* @returns {Kekule.Operation} Operation popped.
*/
popOperation: function(autoReverse)
{
var r;
var h = this.getOperHistory();
if (h)
{
r = h.pop();
if (autoReverse)
{
this.beginUpdateObject();
try
{
r.reverse();
}
finally
{
this.endUpdateObject();
}
}
// if r in operationsInCurrManipulation, removes it
var currOpers = this.getOperationsInCurrManipulation();
var index = currOpers.indexOf(r);
if (index >= 0)
currOpers.splice(index, 1);
return r;
}
else
return null;
},
/**
* Execute an operation in editor.
* @param {Kekule.Operation} operation A single operation, or an array of operations.
*/
execOperation: function(operation)
{
//this.beginUpdateObject();
var opers = AU.toArray(operation);
this.beginManipulateAndUpdateObject();
try
{
for (var i = 0, l = opers.length; i < l; ++i)
{
var o = opers[i];
o.execute();
if (this.getEnableOperHistory())
this.pushOperation(o, false); // push but not execute
}
//operation.execute();
}
finally
{
//this.endUpdateObject();
this.endManipulateAndUpdateObject();
}
/*
if (this.getEnableOperHistory())
this.pushOperation(operation, false); // push but not execute
*/
return this;
},
/**
* Execute a series of operations in editor.
* @param {Array} operations
*/
execOperations: function(opers)
{
if (opers.length === 1)
return this.execOperation(opers[0]);
else
{
var oper = new Kekule.MacroOperation(opers);
return this.execOperation(oper);
}
},
/**
* Replace an operation in operation history.
* @param {Kekule.Operation} oldOperation
* @param {Kekule.Operation} newOperation
* @returns {Kekule.Operation} The replaced old operation object.
*/
replaceOperationInHistory: function(oldOperation, newOperation)
{
var h = this.getOperHistory();
return h && h.replaceOperation(oldOperation, newOperation);
},
/**
* Undo last operation.
*/
undo: function()
{
var o;
var h = this.getOperHistory();
if (h)
{
this.beginUpdateObject();
try
{
o = h.undo();
}
finally
{
this.endUpdateObject();
if (o)
this.operationDone(o);
}
}
return o;
},
/**
* Redo last operation.
*/
redo: function()
{
var o;
var h = this.getOperHistory();
if (h)
{
this.beginUpdateObject();
try
{
o = h.redo();
}
finally
{
this.endUpdateObject();
if (o)
this.operationDone(o)
}
}
return o;
},
/**
* Undo all operations.
*/
undoAll: function()
{
var o;
var h = this.getOperHistory();
if (h)
{
this.beginUpdateObject();
try
{
o = h.undoAll();
}
finally
{
this.endUpdateObject();
}
}
return o;
},
/**
* Check if an undo action can be taken.
* @returns {Bool}
*/
canUndo: function()
{
var h = this.getOperHistory();
return h? h.canUndo(): false;
},
/**
* Check if an undo action can be taken.
* @returns {Bool}
*/
canRedo: function()
{
var h = this.getOperHistory();
return h? h.canRedo(): false;
},
/**
* Modify properties of objects in editor.
* @param {Variant} objOrObjs A object or an array of objects.
* @param {Hash} modifiedPropInfos A hash of property: value pairs.
* @param {Bool} putInOperHistory If set to true, the modification will be put into history and can be undone.
*/
modifyObjects: function(objOrObjs, modifiedPropInfos, putInOperHistory)
{
var objs = Kekule.ArrayUtils.toArray(objOrObjs);
try
{
var macro = new Kekule.MacroOperation();
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var oper = new Kekule.ChemObjOperation.Modify(obj, modifiedPropInfos, this);
macro.add(oper);
}
macro.execute();
}
finally
{
if (putInOperHistory && this.getEnableOperHistory() && macro.getChildCount())
this.pushOperation(macro);
}
return this;
},
/**
* Modify render options of objects in editor.
* @param {Variant} objOrObjs A object or an array of objects.
* @param {Hash} modifiedValues A hash of name: value pairs.
* @param {Bool} is3DOption Change renderOptions or render3DOptions.
* @param {Bool} putInOperHistory If set to true, the modification will be put into history and can be undone.
*/
modifyObjectsRenderOptions: function(objOrObjs, modifiedValues, is3DOption, putInOperHistory)
{
var objs = Kekule.ArrayUtils.toArray(objOrObjs);
var renderPropName = is3DOption? 'render3DOptions': 'renderOptions';
var getterName = is3DOption? 'getRender3DOptions': 'getRenderOptions';
try
{
var macro = new Kekule.MacroOperation();
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj[getterName])
{
var old = obj[getterName]();
var newOps = Object.extend({}, old);
newOps = Object.extend(newOps, modifiedValues);
var hash = {};
hash[renderPropName] = newOps;
var oper = new Kekule.ChemObjOperation.Modify(obj, hash, this);
//oper.execute();
macro.add(oper);
}
}
this.beginManipulateAndUpdateObject();
macro.execute();
}
finally
{
if (putInOperHistory && this.getEnableOperHistory() && macro.getChildCount())
this.pushOperation(macro);
this.endManipulateAndUpdateObject();
}
return this;
},
/**
* Returns the dimension of current visible client area of editor.
*/
getClientDimension: function()
{
var elem = this.getElement();
return {
'width': elem.clientWidth,
'height': elem.clientHeight
};
},
/**
* Returns current scroll position of edit client element.
* @returns {Hash} {x, y}
*/
getClientScrollPosition: function()
{
var elem = this.getEditClientElem().parentNode;
return elem? {
'x': elem.scrollLeft,
'y': elem.scrollTop
}: null;
},
/**
* Returns the top left corner coord of client in coordSys.
* @param {Int} coordSys
* @returns {Hash}
*/
getClientScrollCoord: function(coordSys)
{
var screenCoord = this.getClientScrollPosition();
if (OU.isUnset(coordSys) || coordSys === Kekule.Editor.CoordSys.SCREEN)
return screenCoord;
else
return this.translateCoord(screenCoord, Kekule.Editor.CoordSys.SCREEN, coordSys);
},
/**
* Returns the screen rect/box of editor client element.
* @returns {Hash} {x1, y1, x2, y2, left, top, width, height}
*/
getClientVisibleRect: function()
{
var result = this.getClientDimension();
var p = this.getClientScrollPosition();
result.x1 = result.left = p.x;
result.y1 = result.top = p.y;
result.x2 = result.x1 + result.width;
result.y2 = result.y1 + result.height;
return result;
},
/**
* Scroll edit client to a position.
* @param {Int} yPosition, in px.
* @param {Int} xPosition, in px.
*/
scrollClientTo: function(yPosition, xPosition)
{
/*
var elem = this.getEditClientElem().parentNode;
if (Kekule.ObjUtils.notUnset(yPosition))
elem.scrollTop = yPosition;
if (Kekule.ObjUtils.notUnset(xPosition))
elem.scrollLeft = xPosition;
return this;
*/
return this.scrollClientToCoord({'y': yPosition, 'x': xPosition});
},
/**
* Scroll edit client to top.
*/
scrollClientToTop: function()
{
return this.scrollClientTo(0, null);
},
/**
* Scroll edit client to bottom.
*/
scrollClientToBottom: function()
{
var elem = this.getEditClientElem();
var dim = Kekule.HtmlElementUtils.getElemClientDimension(elem);
return this.scrollClientTo(dim.height, null);
},
/**
* Scroll edit client to coord (based on coordSys).
* @param {Hash} coord
* @param {Int} coordSys If not set, screen coord system will be used.
* @param {Hash} options A hash object that contains the options of scrolling.
* Currently it may has one field: scrollToCenter. If scrollToCenter is true,
* the coord will be at the center of edit area rather than top-left.
*/
scrollClientToCoord: function(coord, coordSys, options)
{
var scrollX = OU.notUnset(coord.x);
var scrollY = OU.notUnset(coord.y);
var scrollToCenter = options && options.scrollToCenter;
var screenCoord;
if (OU.isUnset(coordSys))
screenCoord = coord;
else
screenCoord = this.translateCoord(coord, coordSys, Kekule.Editor.CoordSys.SCREEN);
if (scrollToCenter)
{
var visibleClientBox = this.getVisibleClientScreenBox();
var delta = {'x': visibleClientBox.width / 2, 'y': visibleClientBox.height / 2};
screenCoord = Kekule.CoordUtils.substract(screenCoord, delta);
}
var elem = this.getEditClientElem().parentNode;
if (scrollY)
elem.scrollTop = screenCoord.y;
if (scrollX)
elem.scrollLeft = screenCoord.x;
return this;
},
/**
* Scroll edit client to target object or objects in editor.
* @param {Variant} targetObjOrObjs Target object or objects array.
* @param {Hash} options Scroll options, can including two fields: scrollToCenter, coverMostObjs.
* The default value of both of those options are true.
*/
scrollClientToObject: function(targetObjOrObjs, options)
{
var BU = Kekule.BoxUtils;
if (!targetObjOrObjs)
return this;
var rootObj = this.getChemObj();
if (!rootObj)
return this;
var objs = AU.toArray(targetObjOrObjs);
/*
var containerBoxes = [];
var totalContainerBox = null;
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj.getExposedContainerBox && obj.isChildOf && obj.isChildOf(rootObj))
{
var box = obj.getExposedContainerBox(this.getCoordMode());
if (box)
{
containerBoxes.push(box);
if (!totalContainerBox)
totalContainerBox = box;
else
totalContainerBox = BU.getContainerBox(totalContainerBox, box);
}
}
}
*/
var boxInfo = this._getTargetObjsExposedContainerBoxInfo(objs, rootObj);
var totalContainerBox = boxInfo.totalBox;
var containerBoxes = boxInfo.boxes;
if (totalContainerBox)
{
var ops = Object.extend({scrollToCenter: true, coverMostObjs: true}, options || {});
/*
var actualBox;
// if scroll to centerCoord and none of the obj can be seen in current state, we need another approach
var visibleBox = this.getVisibleClientBoxOfSys(Kekule.Editor.CoordSys.CHEM);
if (((totalContainerBox.x2 - totalContainerBox.x1 > visibleBox.x2 - visibleBox.x1)
|| (totalContainerBox.y2 - totalContainerBox.y1 > visibleBox.y2 - visibleBox.y1))
&& ops.coverMostObjs)
{
actualBox = this._getMostIntersectedContainerBox(visibleBox.x2 - visibleBox.x1, visibleBox.y2 - visibleBox.y1, containerBoxes, totalContainerBox);
}
else
actualBox = totalContainerBox;
var scrollCoord = ops.scrollToCenter? BU.getCenterCoord(actualBox): {x: actualBox.x1, y: actualBox.y2};
return this.scrollClientToCoord(scrollCoord, Kekule.Editor.CoordSys.CHEM, ops);
*/
return this._scrollClientToContainerBox(totalContainerBox, containerBoxes, ops);
}
else
return this;
},
/** @private */
_scrollClientToContainerBox: function(totalContainerBox, allContainerBoxes, options)
{
var BU = Kekule.BoxUtils;
var actualBox;
// if scroll to centerCoord and none of the obj can be seen in current state, we need another approach
var visibleBox = this.getVisibleClientBoxOfSys(Kekule.Editor.CoordSys.CHEM);
if (((totalContainerBox.x2 - totalContainerBox.x1 > visibleBox.x2 - visibleBox.x1)
|| (totalContainerBox.y2 - totalContainerBox.y1 > visibleBox.y2 - visibleBox.y1))
&& options.coverMostObjs)
{
actualBox = this._getMostIntersectedContainerBox(visibleBox.x2 - visibleBox.x1, visibleBox.y2 - visibleBox.y1, allContainerBoxes, totalContainerBox);
}
else
actualBox = totalContainerBox;
var scrollCoord = options.scrollToCenter? BU.getCenterCoord(actualBox): {x: actualBox.x1, y: actualBox.y2};
return this.scrollClientToCoord(scrollCoord, Kekule.Editor.CoordSys.CHEM, options);
},
/**
* Returns the exposed container box of each object and the total container box.
* @param {Array} objs
* @returns {Hash}
* @private
*/
_getTargetObjsExposedContainerBoxInfo: function(objs, rootObj)
{
var BU = Kekule.BoxUtils;
if (!rootObj)
rootObj = this.getChemObj();
if (rootObj)
{
var totalContainerBox = null;
var containerBoxes = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj.getExposedContainerBox && obj.isChildOf && obj.isChildOf(rootObj))
{
var box = obj.getExposedContainerBox(this.getCoordMode());
if (box)
{
containerBoxes.push(box);
if (!totalContainerBox)
totalContainerBox = box;
else
totalContainerBox = BU.getContainerBox(totalContainerBox, box);
}
}
}
}
return {'totalBox': totalContainerBox, 'boxes': containerBoxes};
},
/** @private */
_getMostIntersectedContainerBox: function(width, height, boxes, totalContainerBox)
{
var BU = Kekule.BoxUtils;
var generateTestBox = function(startingCoord, directions)
{
var endingCoord = CU.add(startingCoord, {'x': width * directions.x, 'y': height * directions.y});
if (endingCoord.x < totalContainerBox.x1)
endingCoord.x = totalContainerBox.x1;
else if (endingCoord.x > totalContainerBox.x2)
endingCoord.x = totalContainerBox.x2;
if (endingCoord.y < totalContainerBox.y1)
endingCoord.y = totalContainerBox.y1;
else if (endingCoord.y > totalContainerBox.y2)
endingCoord.y = totalContainerBox.y2;
var actualStartingCoord = CU.add(endingCoord, {'x': -width * directions.x, 'y': -height * directions.y});
var result = BU.createBox(actualStartingCoord, endingCoord);
return result;
};
var getIntersectedBoxCount = function(testBox, boxes)
{
var result = 0;
for (var i = 0, l = boxes.length; i < l; ++i)
{
var box = boxes[i];
if (BU.hasIntersection(box, testBox))
++result;
}
return result;
};
var maxIntersectCount = 0;
var currContainerBox;
for (var i = 0, l = boxes.length; i < l; ++i)
{
var corners = BU.getCornerCoords(boxes[i]);
var testBoxes = [
generateTestBox(corners[0], {x: 1, y: 1}),
generateTestBox(corners[1], {x: 1, y: -1}),
generateTestBox(corners[2], {x: -1, y: 1}),
generateTestBox(corners[3], {x: -1, y: -1}),
];
for (var j = 0, k = testBoxes.length; j < k; ++j)
{
var count = getIntersectedBoxCount(testBoxes[j], boxes);
if (count > maxIntersectCount)
{
maxIntersectCount = count;
currContainerBox = testBoxes[j];
}
}
}
return currContainerBox;
},
/////// Event handle //////////////////////
/** @ignore */
doBeforeDispatchUiEvent: function(/*$super, */e)
{
// get pointer type information here
var evType = e.getType();
if (['pointerdown', 'pointermove', 'pointerup'].indexOf(evType) >= 0)
{
this.setCurrPointerType(e.pointerType);
if (evType === 'pointermove' && this.isRenderable())
{
var coord = this._getEventMouseCoord(e, this.getCoreElement()); // coord based on editor client element
var hoveredObjs = this.getBasicObjectsAtCoord(coord, this.getCurrBoundInflation()) || [];
var oldHoveredObjs = this.getHoveredBasicObjs();
this.setPropStoreFieldValue('hoveredBasicObjs', hoveredObjs);
// if there are differences between oldHoveredObjs and hoveredObjs
if (!oldHoveredObjs || hoveredObjs.length !== oldHoveredObjs.length || AU.intersect(oldHoveredObjs, hoveredObjs).length !== hoveredObjs.length)
{
this.notifyHoverOnObjs(hoveredObjs);
}
}
}
return this.tryApplySuper('doBeforeDispatchUiEvent', [e]) /* $super(e) */;
},
/**
* Called when the pointer hover on/off objects.
* @param {Array} hoveredObjs An empty array means move out off objects.
* @private
*/
notifyHoverOnObjs: function(hoveredObjs)
{
// when hovering on objects, update the chem object hint of editor
var hint = this.getChemObjsHint(hoveredObjs);
this.updateHintForChemObject(hint);
this.invokeEvent('hoverOnObjs', {'objs': hoveredObjs});
},
/**
* React to a HTML event to find if it is a registered hotkey, then react to it when necessary.
* @param {HTMLEvent} e
* @returns {Bool} Returns true if a hot key is found and handled.
* @private
*/
reactHotKeys: function(e)
{
var editor = this;
// react to hotkeys
if (this.getEditorConfigs().getInteractionConfigs().getEnableHotKey())
{
var hotKeys = this.getEditorConfigs().getHotKeyConfigs().getHotKeys();
var srcParams = Kekule.Widget.KeyboardUtils.getKeyParamsFromEvent(e);
var done = false;
var pendingOperations = [];
for (var i = hotKeys.length - 1; i >= 0; --i)
{
var keyParams = Kekule.Widget.KeyboardUtils.shortcutLabelToKeyParams(hotKeys[i].key, null, false);
keyParams.repeat = hotKeys[i].repeat;
if (Kekule.Widget.KeyboardUtils.matchKeyParams(srcParams, keyParams, false)) // not strict match
{
var actionId = hotKeys[i].action;
if (actionId)
{
var action = editor.getChildAction(actionId, true);
if (action)
{
if (action instanceof Kekule.Editor.ActionOperationCreate.Base) // operation creation actions, handles differently
{
var opers = action.createOperations(editor);
done = !!(opers && opers.length) || done;
if (done)
pendingOperations = pendingOperations.concat(opers);
}
else
done = action.execute(editor, e) || done;
}
}
}
}
if (pendingOperations.length)
editor.execOperations(pendingOperations);
if (done)
{
e.stopPropagation();
e.preventDefault();
return true; // already do the modification, returns a flag
}
}
},
/** @ignore */
react_keydown: function(e)
{
var handled = this.tryApplySuper('react_keydown', [e]);
if (!handled)
return this.reactHotKeys(e);
}
});
/**
* A special class to give a setting facade for BaseEditor.
* Do not use this class alone.
* @class
* @augments Kekule.ChemWidget.ChemObjDisplayer.Settings
* @ignore
*/
Kekule.Editor.BaseEditor.Settings = Class.create(Kekule.ChemWidget.ChemObjDisplayer.Settings,
/** @lends Kekule.Editor.BaseEditor.Settings# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.BaseEditor.Settings',
/** @private */
initProperties: function()
{
this.defineProp('enableCreateNewDoc', {'dataType': DataType.BOOL, 'serializable': false,
'getter': function() { return this.getEditor().getEnableCreateNewDoc(); },
'setter': function(value) { this.getEditor().setEnableCreateNewDoc(value); }
});
this.defineProp('initOnNewDoc', {'dataType': DataType.BOOL, 'serializable': false,
'getter': function() { return this.getEditor().getInitOnNewDoc(); },
'setter': function(value) { this.getEditor().setInitOnNewDoc(value); }
});
this.defineProp('enableOperHistory', {'dataType': DataType.BOOL, 'serializable': false,
'getter': function() { return this.getEditor().getEnableOperHistory(); },
'setter': function(value) { this.getEditor().setEnableOperHistory(value); }
});
this.defineProp('enableIssueCheck', {'dataType': DataType.BOOL, 'serializable': false,
'getter': function() { return this.getEditor().getEnableIssueCheck(); },
'setter': function(value) { this.getEditor().setEnableIssueCheck(value); }
});
},
/** @private */
getEditor: function()
{
return this.getDisplayer();
}
});
/**
* A class to register all available IA controllers for editor.
* @class
*/
Kekule.Editor.IaControllerManager = {
/** @private */
_controllerMap: new Kekule.MapEx(true),
/**
* Register a controller, the controller can be used in targetEditorClass or its descendants.
* @param {Class} controllerClass
* @param {Class} targetEditorClass
*/
register: function(controllerClass, targetEditorClass)
{
ICM._controllerMap.set(controllerClass, targetEditorClass);
},
/**
* Unregister a controller.
* @param {Class} controllerClass
*/
unregister: function(controllerClass)
{
ICM._controllerMap.remove(controllerClass);
},
/**
* Returns all registered controller classes.
* @returns {Array}
*/
getAllControllerClasses: function()
{
return ICM._controllerMap.getKeys();
},
/**
* Returns controller classes can be used for editorClass.
* @param {Class} editorClass
* @returns {Array}
*/
getAvailableControllerClasses: function(editorClass)
{
var result = [];
var controllerClasses = ICM.getAllControllerClasses();
for (var i = 0, l = controllerClasses.length; i < l; ++i)
{
var cc = controllerClasses[i];
var ec = ICM._controllerMap.get(cc);
if (!ec || ClassEx.isOrIsDescendantOf(editorClass, ec))
result.push(cc);
}
return result;
}
};
var ICM = Kekule.Editor.IaControllerManager;
/**
* Base controller class for BaseEditor.
* This is a base class and should not be used directly.
* @class
* @augments Kekule.Widget.InteractionController
*
* @param {Kekule.Editor.BaseEditor} editor Editor of current object being installed to.
*/
Kekule.Editor.BaseEditorBaseIaController = Class.create(Kekule.Widget.InteractionController,
/** @lends Kekule.Editor.BaseEditorBaseIaController# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.BaseEditorIaController',
/** @constructs */
initialize: function(/*$super, */editor)
{
this.tryApplySuper('initialize', [editor]) /* $super(editor) */;
},
/** @private */
_defineEditorConfigBasedProperty: function(propName, configPath, options)
{
var defOps = {
'dataType': DataType.VARIANT,
'serializable': false,
/*
'setter': function(value)
{
var configs = this.getEditorConfigs();
configs.setCascadePropValue(configPath, value);
}
*/
'setter': null
};
if (options && options.overwrite)
{
defOps.getter = function ()
{
var v = this.getPropStoreFieldValue(propName);
var configs = this.getEditorConfigs();
return v && configs.getCascadePropValue(configPath);
};
defOps.setter = function(value)
{
this.setPropStoreFieldValue(propName, value);
}
}
else
{
defOps.getter = function () {
var configs = this.getEditorConfigs();
return configs.getCascadePropValue(configPath);
};
}
var ops = Object.extend(defOps, options || {});
this.defineProp(propName, ops);
},
/**
* Returns the preferred id for this controller.
*/
getDefId: function()
{
return Kekule.ClassUtils.getLastClassName(this.getClassName());
},
/**
* Return associated editor.
* @returns {Kekule.ChemWidget.BaseEditor}
*/
getEditor: function()
{
return this.getWidget();
},
/**
* Set associated editor.
* @param {Kekule.ChemWidget.BaseEditor} editor
*/
setEditor: function(editor)
{
return this.setWidget(editor);
},
/**
* Get config object of editor.
* @returns {Object}
*/
getEditorConfigs: function()
{
var editor = this.getEditor();
return editor? editor.getEditorConfigs(): null;
}
});
/**
* Base Controller class for editor.
* @class
* @augments Kekule.Editor.BaseEditorBaseIaController
*
* @param {Kekule.Editor.BaseEditor} editor Editor of current object being installed to.
*
* @property {Bool} manuallyHotTrack If set to false, hot track will be auto shown in mousemove event listener.
*/
Kekule.Editor.BaseEditorIaController = Class.create(Kekule.Editor.BaseEditorBaseIaController,
/** @lends Kekule.Editor.BaseEditorIaController# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.BaseEditorIaController',
/** @constructs */
initialize: function(/*$super, */editor)
{
this.tryApplySuper('initialize', [editor]) /* $super(editor) */;
},
initProperties: function()
{
this.defineProp('manuallyHotTrack', {'dataType': DataType.BOOL, 'serializable': false});
// in mouse or touch interaction, we may have different bound inflation
this.defineProp('currBoundInflation', {'dataType': DataType.NUMBER, 'serializable': false,
'getter': function() { return this.getEditor().getCurrBoundInflation(); },
'setter': null // function(value) { return this.getEditor().setCurrBoundInflation(value); }
});
this.defineProp('activePointerType', {'dataType': DataType.BOOL, 'serializable': false,
'getter': function()
{
var editor = this.getEditor();
return (editor && editor.getCurrPointerType()) || this.getPropStoreFieldValue('activePointerType');
},
'setter': function(value)
{
var editor = this.getEditor();
if (editor)
editor.setCurrPointerType(value);
else
this.setStoreFieldValue('activePointerType', value);
}
}); // private
},
/**
* Call the beginManipulateObjects method of editor.
* @private
*/
notifyEditorBeginManipulateObjects: function()
{
var editor = this.getEditor();
editor.beginManipulateObject();
},
/**
* Call the endManipulateObjects method of editor.
* @private
*/
notifyEditorEndManipulateObjects: function()
{
var editor = this.getEditor();
editor.endManipulateObject();
},
/** @private */
getInteractionBoundInflation: function(pointerType)
{
return this.getEditor().getInteractionBoundInflation(pointerType);
},
/** @ignore */
handleUiEvent: function(/*$super, */e)
{
var handle = false;
var targetElem = (e.getTarget && e.getTarget()) || e.target; // hammer event does not have getTarget method
var uiElem = this.getEditor().getUiEventReceiverElem();
if (uiElem)
{
// only handles event on event receiver element
// otherwise scrollbar on editor may cause problem
if ((targetElem === uiElem) || Kekule.DomUtils.isDescendantOf(targetElem, uiElem))
handle = true;
}
else
handle = true;
if (handle)
this.tryApplySuper('handleUiEvent', [e]) /* $super(e) */;
},
/**
* Returns if this IaController can interact with obj.
* If true, when mouse moving over obj, a hot track marker will be drawn.
* Descendants should override this method.
* @param {Object} obj
* @return {Bool}
* @private
*/
canInteractWithObj: function(obj)
{
return !!obj;
},
/**
* Returns all interactable object classes for this IA controller in editor.
* If can interact will all objects, simply returns null.
* Descendants may override this method.
* @private
*/
getInteractableTargetClasses: function()
{
return null;
},
/* @private */
getAllInteractableObjsAtScreenCoord: function(coord)
{
return this.getEditor().getBasicObjectsAtCoord(coord, this.getCurrBoundInflation(), null, this.getInteractableTargetClasses());
},
/** @private */
getTopmostInteractableObjAtScreenCoord: function(coord)
{
var objs = this.getAllInteractableObjsAtScreenCoord(coord);
if (objs)
{
for (var i = 0, l = objs.length; i < l; ++i)
{
if (this.canInteractWithObj(objs[i]))
return objs[i];
}
}
return null;
},
/** @private */
getTopmostInteractableObjAtCurrPointerPos: function()
{
var objs = this.getEditor().getHoveredBasicObjs();
if (objs)
{
for (var i = 0, l = objs.length; i < l; ++i)
{
if (this.canInteractWithObj(objs[i]))
return objs[i];
}
}
return null;
},
/**
* Show a hot track marker on obj in editor.
* @param {Kekule.ChemObject} obj
*/
hotTrackOnObj: function(obj)
{
this.getEditor().hotTrackOnObj(obj);
},
// zoom functions
/** @private */
zoomEditor: function(zoomLevel, zoomCenterCoord)
{
if (zoomLevel > 0)
this.getEditor().zoomIn(zoomLevel, zoomCenterCoord);
else if (zoomLevel < 0)
this.getEditor().zoomOut(-zoomLevel, zoomCenterCoord);
},
/** @private */
/*
updateCurrBoundInflation: function(evt)
{
*/
/*
var editor = this.getEditor();
var pointerType = evt && evt.pointerType;
var iaConfigs = this.getEditorConfigs().getInteractionConfigs();
var defRatio = iaConfigs.getObjBoundTrackInflationRatio();
var currRatio, ratioValue;
if (pointerType === 'mouse')
currRatio = iaConfigs.getObjBoundTrackInflationRatioMouse();
else if (pointerType === 'pen')
currRatio = iaConfigs.getObjBoundTrackInflationRatioPen();
else if (pointerType === 'touch')
currRatio = iaConfigs.getObjBoundTrackInflationRatioTouch();
currRatio = currRatio || defRatio;
if (currRatio)
{
var bondScreenLength = editor.getDefBondScreenLength();
ratioValue = bondScreenLength * currRatio;
}
var defMinValue = iaConfigs.getObjBoundTrackMinInflation();
var currMinValue;
if (pointerType === 'mouse')
currMinValue = iaConfigs.getObjBoundTrackMinInflationMouse();
else if (pointerType === 'pen')
currMinValue = iaConfigs.getObjBoundTrackMinInflationPen();
else if (pointerType === 'touch')
currMinValue = iaConfigs.getObjBoundTrackMinInflationTouch();
currMinValue = currMinValue || defMinValue;
var actualValue = Math.max(ratioValue || 0, currMinValue);
*/
/*
//this.setCurrBoundInflation(actualValue);
var value = this.getEditor().getInteractionBoundInflation(evt && evt.pointerType);
this.setCurrBoundInflation(value);
//console.log('update bound inflation', pointerType, this.getCurrBoundInflation());
},
*/
/** @private */
_filterBasicObjectsInEditor: function(objs)
{
var editor = this.getEditor();
var rootObj = editor.getChemObj();
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj.isChildOf(rootObj))
result.push(obj);
}
return result;
},
/**
* Notify the manipulation is done and objs are inserted into or modified in editor.
* This method should be called by descendants at the end of their manipulation.
* Objs will be automatically selected if autoSelectNewlyInsertedObjects option is true.
* @param {Array} objs
* @private
*/
doneInsertOrModifyBasicObjects: function(objs)
{
if (this.needAutoSelectNewlyInsertedObjects())
{
var filteredObjs = this._filterBasicObjectsInEditor(objs);
this.getEditor().select(filteredObjs);
}
},
/** @private */
needAutoSelectNewlyInsertedObjects: function()
{
var pointerType = this.getActivePointerType();
var ic = this.getEditorConfigs().getInteractionConfigs();
return (ic.getAutoSelectNewlyInsertedObjectsOnTouch() && pointerType === 'touch')
|| ic.getAutoSelectNewlyInsertedObjects();
},
/** @private */
react_pointerdown: function(e)
{
//this.updateCurrBoundInflation(e);
//this.getEditor().setCurrPointerType(e.pointerType);
this.setActivePointerType(e.pointerType);
e.preventDefault();
return true;
},
/** @private */
react_pointermove: function(e)
{
//if (!this.getCurrBoundInflation())
//this.updateCurrBoundInflation(e);
//this.getEditor().setCurrPointerType(e.pointerType);
//console.log(e.getTarget().id);
/*
var coord = this._getEventMouseCoord(e);
var obj = this.getTopmostInteractableObjAtScreenCoord(coord);
*/
var obj = this.getTopmostInteractableObjAtCurrPointerPos(); // read the hovered obj directly from the editor's cached property
if (!this.getManuallyHotTrack())
{
/*
if (obj)
console.log('point to', obj.getClassName(), obj.getId());
*/
if (obj /* && this.canInteractWithObj(obj)*/) // canInteractWithObj check now already done in getTopmostInteractableObjAtScreenCoord
{
this.hotTrackOnObj(obj);
}
else
{
this.hotTrackOnObj(null);
}
//e.preventDefault();
}
e.preventDefault();
return true;
},
/** @private */
react_mousewheel: function(e)
{
if (e.getCtrlKey())
{
var currScreenCoord = this._getEventMouseCoord(e);
//this.getEditor().setZoomCenter(currScreenCoord);
try
{
var delta = e.wheelDeltaY || e.wheelDelta;
if (delta)
delta /= 120;
//console.log('zoom', this.getEditor().getZoomCenter())
this.zoomEditor(delta, currScreenCoord);
}
finally
{
//this.getEditor().setZoomCenter(null);
}
e.preventDefault();
return true;
}
},
/** @private */
_getEventMouseCoord: function(/*$super, */e, clientElem)
{
var elem = clientElem || this.getWidget().getCoreElement(); // defaultly base on client element, not widget element
return this.tryApplySuper('_getEventMouseCoord', [e, elem]) /* $super(e, elem) */;
}
});
/**
* Controller for drag and scroll (by mouse, touch...) client element in editor.
* @class
* @augments Kekule.Widget.BaseEditorIaController
*
* @param {Kekule.Editor.BaseEditor} widget Editor of current object being installed to.
*/
Kekule.Editor.ClientDragScrollIaController = Class.create(Kekule.Editor.BaseEditorIaController,
/** @lends Kekule.Editor.ClientDragScrollIaController# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.ClientDragScrollIaController',
/** @constructs */
initialize: function(/*$super, */widget)
{
this.tryApplySuper('initialize', [widget]) /* $super(widget) */;
this._isExecuting = false;
},
/** @ignore */
canInteractWithObj: function(obj)
{
return false; // do not interact directly with objects in editor
},
/** @ignore */
doTestMouseCursor: function(coord, e)
{
//console.log(this.isExecuting(), coord);
return this.isExecuting()?
['grabbing', '-webkit-grabbing', '-moz-grabbing', 'move']:
['grab', '-webkit-grab', '-moz-grab', 'pointer'];
//return this.isExecuting()? '-webkit-grabbing': '-webkit-grab';
},
/** @private */
isExecuting: function()
{
return this._isExecuting;
},
/** @private */
startScroll: function(screenCoord)
{
this._startCoord = screenCoord;
this._originalScrollPos = this.getEditor().getClientScrollPosition();
this._isExecuting = true;
},
/** @private */
endScroll: function()
{
this._isExecuting = false;
this._startCoord = null;
this._originalScrollPos = null;
},
/** @private */
scrollTo: function(screenCoord)
{
if (this.isExecuting())
{
var startCoord = this._startCoord;
var delta = Kekule.CoordUtils.substract(startCoord, screenCoord);
var newScrollPos = Kekule.CoordUtils.add(this._originalScrollPos, delta);
this.getEditor().scrollClientTo(newScrollPos.y, newScrollPos.x); // note the params of this method is y, x
}
},
/** @private */
react_pointerdown: function(e)
{
this.setActivePointerType(e.pointerType);
if (e.getButton() === Kekule.X.Event.MouseButton.LEFT) // begin scroll
{
if (!this.isExecuting())
{
var coord = {x: e.getScreenX(), y: e.getScreenY()};
this.startScroll(coord);
e.preventDefault();
}
}
else if (e.getButton() === Kekule.X.Event.MouseButton.RIGHT)
{
if (this.isExecuting())
{
this.endScroll();
e.preventDefault();
}
}
},
/** @private */
react_pointerup: function(e)
{
if (e.getButton() === Kekule.X.Event.MouseButton.LEFT)
{
if (this.isExecuting())
{
this.endScroll();
e.preventDefault();
}
}
},
/** @private */
react_pointermove: function(/*$super, */e)
{
this.tryApplySuper('react_pointermove', [e]) /* $super(e) */;
if (this.isExecuting())
{
var coord = {x: e.getScreenX(), y: e.getScreenY()};
this.scrollTo(coord);
e.preventDefault();
}
return true;
}
});
/** @ignore */
Kekule.Editor.IaControllerManager.register(Kekule.Editor.ClientDragScrollIaController, Kekule.Editor.BaseEditor);
/**
* Controller for deleting objects in editor.
* @class
* @augments Kekule.Widget.BaseEditorIaController
*
* @param {Kekule.Editor.BaseEditor} widget Editor of current object being installed to.
*/
Kekule.Editor.BasicEraserIaController = Class.create(Kekule.Editor.BaseEditorIaController,
/** @lends Kekule.Editor.BasicEraserIaController# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.BasicEraserIaController',
/** @constructs */
initialize: function(/*$super, */widget)
{
this.tryApplySuper('initialize', [widget]) /* $super(widget) */;
this._isExecuting = false;
},
/** @ignore */
canInteractWithObj: function(obj)
{
return !!obj; // every thing can be deleted
},
//methods about remove
/** @private */
removeObjs: function(objs)
{
if (objs && objs.length)
{
var editor = this.getEditor();
editor.beginUpdateObject();
try
{
var actualObjs = this.doGetActualRemovedObjs(objs);
this.doRemoveObjs(actualObjs);
}
finally
{
editor.endUpdateObject();
}
}
},
/** @private */
doRemoveObjs: function(objs)
{
// do actual remove job
},
doGetActualRemovedObjs: function(objs)
{
return objs;
},
/**
* Remove selected objects in editor.
*/
removeSelection: function()
{
var editor = this.getEditor();
this.removeObjs(editor.getSelection());
// the selection is currently empty
editor.deselectAll();
},
/**
* Remove object on screen coord.
* @param {Hash} coord
*/
removeOnScreenCoord: function(coord)
{
var obj = this.getEditor().getTopmostBasicObjectAtCoord(coord);
if (obj)
{
this.removeObjs([obj]);
return true;
}
else
return false;
},
/** @private */
startRemove: function()
{
this._isExecuting = true;
},
/** @private */
endRemove: function()
{
this._isExecuting = false;
},
/** @private */
isRemoving: function()
{
return this._isExecuting;
},
/** @ignore */
reactUiEvent: function(/*$super, */e)
{
var result = this.tryApplySuper('reactUiEvent', [e]) /* $super(e) */;
var evType = e.getType();
// prevent default touch action (may change UI) in mobile browsers
if (['touchstart', 'touchend', 'touchcancel', 'touchmove'].indexOf(evType) >= 0)
e.preventDefault();
return result;
},
/** @private */
react_pointerdown: function(e)
{
this.setActivePointerType(e.pointerType);
if (e.getButton() === Kekule.X.Event.MOUSE_BTN_LEFT)
{
this.startRemove();
var coord = this._getEventMouseCoord(e);
this.removeOnScreenCoord(coord);
e.preventDefault();
}
else if (e.getButton() === Kekule.X.Event.MOUSE_BTN_RIGHT)
{
this.endRemove();
e.preventDefault();
}
},
/** @private */
react_pointerup: function(e)
{
if (e.getButton() === Kekule.X.Event.MOUSE_BTN_LEFT)
{
this.endRemove();
e.preventDefault();
}
},
/** @private */
react_pointermove: function(/*$super, */e)
{
this.tryApplySuper('react_pointermove', [e]) /* $super(e) */;
if (this.isRemoving())
{
var coord = this._getEventMouseCoord(e);
this.removeOnScreenCoord(coord);
e.preventDefault();
}
return true;
}
});
/** @ignore */
Kekule.Editor.IaControllerManager.register(Kekule.Editor.BasicEraserIaController, Kekule.Editor.BaseEditor);
/**
* Controller for selecting, moving or rotating objects in editor.
* @class
* @augments Kekule.Widget.BaseEditorIaController
*
* @param {Kekule.Editor.BaseEditor} widget Editor of current object being installed to.
*
* @property {Int} selectMode Set the selectMode property of editor.
* @property {Bool} enableSelect Whether select function is enabled.
* @property {Bool} enableMove Whether move function is enabled.
* //@property {Bool} enableRemove Whether remove function is enabled.
* @property {Bool} enableResize Whether resize of selection is allowed.
* @property {Bool} enableRotate Whether rotate of selection is allowed.
* @property {Bool} enableGestureManipulation Whether rotate and resize by touch gestures are allowed.
*/
Kekule.Editor.BasicManipulationIaController = Class.create(Kekule.Editor.BaseEditorIaController,
/** @lends Kekule.Editor.BasicManipulationIaController# */
{
/** @private */
CLASS_NAME: 'Kekule.Editor.BasicManipulationIaController',
/** @constructs */
initialize: function(/*$super, */widget)
{
this.tryApplySuper('initialize', [widget]) /* $super(widget) */;
this.setState(Kekule.Editor.BasicManipulationIaController.State.NORMAL);
/*
this.setEnableSelect(false);
this.setEnableGestureManipulation(false);
this.setEnableMove(true);
this.setEnableResize(true);
this.setEnableAspectRatioLockedResize(true);
this.setEnableRotate(true);
*/
this._suppressConstrainedResize = false;
this._manipulationStepBuffer = {};
this._suspendedOperations = null;
this.execManipulationStepBind = this.execManipulationStep.bind(this);
},
/** @private */
initProperties: function()
{
this.defineProp('selectMode', {'dataType': DataType.INT, 'serializable': false});
this.defineProp('enableSelect', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('enableMove', {'dataType': DataType.BOOL, 'serializable': false});
//this.defineProp('enableRemove', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('enableResize', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('enableRotate', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('enableGestureManipulation', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('state', {'dataType': DataType.INT, 'serializable': false});
// the screen coord that start this manipulation, since startCoord may be changed during rotation, use this
// to get the inital coord of mouse down
this.defineProp('baseCoord', {'dataType': DataType.HASH, 'serializable': false});
this.defineProp('startCoord', {'dataType': DataType.HASH, 'serializable': false/*,
'setter': function(value)
{
console.log('set startCoord', value);
console.log(arguments.callee.caller.caller.caller.toString());
this.setPropStoreFieldValue('startCoord', value);
}*/
});
this.defineProp('endCoord', {'dataType': DataType.HASH, 'serializable': false});
this.defineProp('startBox', {'dataType': DataType.HASH, 'serializable': false});
this.defineProp('endBox', {'dataType': DataType.HASH, 'serializable': false});
this.defineProp('lastRotateAngle', {'dataType': DataType.FLOAT, 'serializable': false}); // private
// private, such as {x: 1, y: 0}, plays as the initial base direction of rotation
this.defineProp('rotateRefCoord', {'dataType': DataType.HASH, 'serializable': false});
this.defineProp('rotateCenter', {'dataType': DataType.HASH, 'serializable': false,
'getter': function()
{
var result = this.getPropStoreFieldValue('rotateCenter');
if (!result)
{
/*
var box = this.getStartBox();
result = box? {'x': (box.x1 + box.x2) / 2, 'y': (box.y1 + box.y2) / 2}: null;
*/
var centerCoord = this._getManipulateObjsCenterCoord();
result = this.getEditor().objCoordToScreen(centerCoord);
this.setPropStoreFieldValue('rotateCenter', result);
//console.log(result, result2);
}
return result;
}
});
this.defineProp('resizeStartingRegion', {'dataType': DataType.INT, 'serializable': false}); // private
this.defineProp('enableAspectRatioLockedResize', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('rotateStartingRegion', {'dataType': DataType.INT, 'serializable': false}); // private
this.defineProp('manipulateOriginObjs', {'dataType': DataType.ARRAY, 'serializable': false}); // private, the direct object user act on
this.defineProp('manipulateObjs', {'dataType': DataType.ARRAY, 'serializable': false, // actual manipulated objects
'setter': function(value)
{
this.setPropStoreFieldValue('manipulateObjs', value);
//console.log('set manipulate', value);
if (!value)
this.getEditor().endOperatingObjs();
else
this.getEditor().prepareOperatingObjs(value);
}
});
this.defineProp('manipulateObjInfoMap', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('manipulateObjInfoMap');
if (!result)
{
result = new Kekule.MapEx(true);
this.setPropStoreFieldValue('manipulateObjInfoMap', result);
}
return result;
}
});
this.defineProp('manipulateObjCurrInfoMap', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null,
'getter': function()
{
var result = this.getPropStoreFieldValue('manipulateObjCurrInfoMap');
if (!result)
{
result = new Kekule.MapEx(true);
this.setPropStoreFieldValue('manipulateObjCurrInfoMap', result);
}
return result;
}
});
this.defineProp('manipulationType', {'dataType': DataType.INT, 'serializable': false}); // private
this.defineProp('isManipulatingSelection', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('isOffsetManipulating', {'dataType': DataType.BOOL, 'serializable': false});
this.defineProp('manipulationPointerType', {'dataType': DataType.BOOL, 'serializable': false,
'getter': function() { return this.getActivePointerType(); },
'setter': function(value) { this.setActivePointerType(value); }
}); // private, alias of property activePointerType
this.defineProp('activePointerId', {'dataType': DataType.INT, 'serializable': false}); // private, the pointer id currently activated in editpr
//this.defineProp('manipulateOperation', {'dataType': 'Kekule.MacroOperation', 'serializable': false}); // store operation of moving
//this.defineProp('activeOperation', {'dataType': 'Kekule.MacroOperation', 'serializable': false}); // store operation that should be add to history
this.defineProp('moveOperations', {'dataType': DataType.ARRAY, 'serializable': false}); // store operations of moving
//this.defineProp('mergeOperations', {'dataType': DataType.ARRAY, 'serializable': false}); // store operations of merging
this.defineProp('moveWrapperOperation', {'dataType': DataType.OBJECT, 'serializable': false}); // private
this.defineProp('objOperationMap', {'dataType': 'Kekule.MapEx', 'serializable': false,
'getter': function()
{
var result = this.getPropStoreFieldValue('objOperationMap');
if (!result)
{
result = new Kekule.MapEx(true);
this.setPropStoreFieldValue('objOperationMap', result);
}
return result;
}
}); // store operation on each object
},
/** @ignore */
initPropValues: function()
{
this.tryApplySuper('initPropValues');
this.setEnableSelect(false); // turn off select for most of IA controllers derived from this class
this.setEnableGestureManipulation(false); // turn off gesture for most of IA controllers derived from this class
/*
this.setEnableGestureManipulation(false);
this.setEnableMove(true);
this.setEnableResize(true);
this.setEnableAspectRatioLockedResize(true);
this.setEnableRotate(true);
*/
var options = Kekule.globalOptions.get('chemWidget.editor') || {};
var oneOf = Kekule.oneOf;
this.setEnableMove(oneOf(options.enableMove, true));
this.setEnableResize(oneOf(options.enableResize, true));
this.setEnableAspectRatioLockedResize(oneOf(options.enableAspectRatioLockedResize, true));
this.setEnableRotate(oneOf(options.enableRotate, true));
},
/** @private */
doFinalize: function(/*$super*/)
{
var map = this.getPropStoreFieldValue('manipulateObjInfoMap');
if (map)
map.clear();
map = this.getPropStoreFieldValue('objOperationMap');
if (map)
map.clear();
this.tryApplySuper('doFinalize') /* $super() */;
},
/* @ignore */
/*
activated: function($super, widget)
{
$super(widget);
//console.log('activated', this.getSelectMode());
// set select mode when be activated
if (this.getEnableSelect())
this.getEditor().setSelectMode(this.getSelectMode());
},
*/
/** @ignore */
hotTrackOnObj: function(/*$super, */obj)
{
// override parent method, is selectMode is ANCESTOR, hot track the whole ancestor object
if (this.getEnableSelect() && this.getSelectMode() === Kekule.Editor.SelectMode.ANCESTOR)
{
var concreteObj = this.getStandaloneAncestor(obj); (obj && obj.getStandaloneAncestor) ? obj.getStandaloneAncestor() : obj;
return this.tryApplySuper('hotTrackOnObj', [concreteObj]) /* $super(concreteObj) */;
}
else
return this.tryApplySuper('hotTrackOnObj', [obj]) /* $super(obj) */;
},
/** @private */
getStandaloneAncestor: function(obj)
{
return (obj && obj.getStandaloneAncestor) ? obj.getStandaloneAncestor() : obj;
},
/** @private */
isInAncestorSelectMode: function()
{
return this.getEnableSelect() && (this.getSelectMode() === Kekule.Editor.SelectMode.ANCESTOR);
},
/** @private */
isAspectRatioLockedResize: function()
{
return this.getEnableAspectRatioLockedResize() && (!this._suppressConstrainedResize);
},
/**
* Check if screenCoord is on near-outside of selection bound and returns which corner is the neraest.
* @param {Hash} screenCoord
* @returns {Variant} If on rotation region, a nearest corner flag (from @link Kekule.Editor.BoxRegion} will be returned,
* else false will be returned.
*/
getCoordOnSelectionRotationRegion: function(screenCoord)
{
var R = Kekule.Editor.BoxRegion;
var editor = this.getEditor();
var region = editor.getCoordRegionInSelectionMarker(screenCoord);
if (region !== R.OUTSIDE)
return false;
var r = editor.getEditorConfigs().getInteractionConfigs().getRotationRegionInflation();
var box = editor.getUiSelectionAreaContainerBox();
if (box && editor.hasSelection())
{
var corners = [R.CORNER_TL, R.CORNER_TR, R.CORNER_BR, R.CORNER_BL];
var points = [
{'x': box.x1, 'y': box.y1},
{'x': box.x2, 'y': box.y1},
{'x': box.x2, 'y': box.y2},
{'x': box.x1, 'y': box.y2}
];
var result = false;
var minDis = r;
for (var i = 0, l = corners.length; i < l; ++i)
{
var corner = corners[i];
var point = points[i];
var dis = Kekule.CoordUtils.getDistance(point, screenCoord);
if (dis <= minDis)
{
result = corner;
minDis = dis;
}
}
return result;
}
else
return false;
},
/**
* Create a coord change operation to add to operation history of editor.
* The operation is a macro one with sub operations on each obj.
* @private
*/
createManipulateOperation: function()
{
return this.doCreateManipulateMoveAndResizeOperation();
},
/** @private */
doCreateManipulateMoveAndResizeOperation: function()
{
//var oper = new Kekule.MacroOperation();
var opers = [];
this.setMoveOperations(opers);
var objs = this.getManipulateObjs();
var map = this.getManipulateObjInfoMap();
var operMap = this.getObjOperationMap();
operMap.clear();
var objsMoveInfo = [];
var totalOperation = new Kekule.ChemObjOperation.MoveAndResizeObjs([], objsMoveInfo, this.getEditor().getCoordMode(), true, this.getEditor());
totalOperation.setDisableIndirectCoord(true);
//console.log('init operations');
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var item = map.get(obj);
//var sub = new Kekule.EditorOperation.OpSetObjCoord(this.getEditor(), obj, null, item.objCoord, Kekule.Editor.CoordSys.OBJ);
//var sub = new Kekule.ChemObjOperation.MoveTo(obj, null, this.getEditor().getCoordMode());
var sub = new Kekule.ChemObjOperation.MoveAndResize(obj, null, null, this.getEditor().getCoordMode(), true, this.getEditor()); // use abs coord
sub.setAllowCoordBorrow(this.getEditor().getAllowCoordBorrow());
sub.setOldCoord(item.objCoord);
sub.setOldDimension(item.size);
//oper.add(sub);
//operMap.set(obj, sub);
opers.push(sub);
/*
objsMoveInfo.push({
'obj': obj,
'oldCoord': item.objCoord,
'oldDimension': item.size
});
*/
totalOperation.getChildOperations().push(sub);
this.setMoveWrapperOperation(totalOperation);
}
//this.setManipulateOperation(oper);
//this.setActiveOperation(oper);
//return oper;
//return opers;
return [totalOperation];
},
/* @private */
/*
_ensureObjOperationToMove: function(obj)
{
var map = this.getObjOperationMap();
var oper = map.get(obj);
if (oper && !(oper instanceof Kekule.ChemObjOperation.MoveAndResize))
{
//console.log('_ensureObjOperationToMove reverse');
//oper.reverse();
oper.finalize();
oper = new Kekule.ChemObjOperation.MoveAndResize(obj, null, null, this.getEditor().getCoordMode(), true); // use abs coord
map.set(obj, oper);
}
return oper;
},
*/
/**
* Update new coord info of sub operations.
* @private
*/
updateChildMoveOperation: function(objIndex, obj, newObjCoord)
{
//console.log('update move', newObjCoord);
//var oper = this.getManipulateOperation().getChildAt(objIndex);
//var oper = this._ensureObjOperationToMove(obj);
var oper = this.getMoveOperations()[objIndex];
//oper.setCoord(newObjCoord);
oper.setNewCoord(newObjCoord);
},
/** @private */
updateChildResizeOperation: function(objIndex, obj, newDimension)
{
//var oper = this.getManipulateOperation().getChildAt(objIndex);
//var oper = this._ensureObjOperationToMove(obj);
var oper = this.getMoveOperations()[objIndex];
oper.setNewDimension(newDimension);
},
/** @private */
getAllObjOperations: function(isTheFinalOperationToEditor)
{
//var opers = this.getObjOperationMap().getValues();
var op = this.getMoveOperations();
var opers = op? Kekule.ArrayUtils.clone(op): [];
if (opers.length)
{
var wrapper = this.getMoveWrapperOperation();
wrapper.setChildOperations(opers);
//return opers;
return [wrapper];
}
else
return [];
},
/** @private */
getActiveOperation: function(isTheFinalOperationToEditor)
{
//console.log('get active operation', isTheFinalOperationToEditor);
var opers = this.getAllObjOperations(isTheFinalOperationToEditor);
opers = Kekule.ArrayUtils.toUnique(opers);
if (opers.length <= 0)
return null;
else if (opers.length === 1)
return opers[0];
else
{
var macro = new Kekule.MacroOperation(opers);
return macro;
}
},
/** @private */
reverseActiveOperation: function()
{
var oper = this.getActiveOperation();
return oper.reverse();
},
/* @private */
/*
clearActiveOperation: function()
{
//this.getObjOperationMap().clear();
},
*/
/** @private */
addOperationToEditor: function()
{
var editor = this.getEditor();
if (editor && editor.getEnableOperHistory())
{
//console.log('add oper to editor', this.getClassName(), this.getActiveOperation());
//editor.pushOperation(this.getActiveOperation());
/*
var opers = this.getAllObjOperations();
var macro = new Kekule.MacroOperation(opers);
editor.pushOperation(macro);
*/
var op = this.getActiveOperation(true);
if (op)
editor.pushOperation(op);
}
},
// methods about object move / resize
/** @private */
getCurrAvailableManipulationTypes: function()
{
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var box = this.getEditor().getSelectionContainerBox();
if (!box)
{
return [];
}
else
{
var result = [];
if (this.getEnableMove())
result.push(T.MOVE);
// if box is a single point, can not resize or rotate
if (!Kekule.NumUtils.isFloatEqual(box.x1, box.x2, 1e-10) || !Kekule.NumUtils.isFloatEqual(box.y1, box.y2, 1e-10))
{
if (this.getEnableResize())
result.push(T.RESIZE);
if (this.getEnableRotate())
result.push(T.ROTATE);
if (this.getEnableResize() || this.getEnableRotate())
result.push(T.TRANSFORM);
}
return result;
}
},
/** @private */
getActualManipulatingObjects: function(objs)
{
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var actualObjs = obj.getCoordDependentObjects? obj.getCoordDependentObjects(): [obj];
Kekule.ArrayUtils.pushUnique(result, actualObjs);
}
return result;
},
/*
* Prepare to resize resizingObjs.
* Note that resizingObjs may differ from actual resized objects (for instance, resize a bond actually move its connected atoms).
* @param {Hash} startContextCoord Mouse position when starting to move objects. This coord is based on context.
* @param {Array} resizingObjs Objects about to be resized.
* @private
*/
/*
prepareResizing: function(startScreenCoord, startBox, movingObjs)
{
var actualObjs = this.getActualResizingObject(movingObjs);
this.setManipulateObjs(actualObjs);
var map = this.getManipulateObjInfoMap();
map.clear();
var editor = this.getEditor();
// store original objs coords info into map
for (var i = 0, l = actualObjs.length; i < l; ++i)
{
var obj = actualObjs[i];
var info = this.createManipulateObjInfo(obj, startScreenCoord);
map.set(obj, info);
}
this.setStartBox(startBox);
},
*/
/** @private */
doPrepareManipulatingObjects: function(manipulatingObjs, startScreenCoord)
{
var actualObjs = this.getActualManipulatingObjects(manipulatingObjs);
//console.log(manipulatingObjs, actualObjs);
this.setManipulateOriginObjs(manipulatingObjs);
this.setManipulateObjs(actualObjs);
var map = this.getManipulateObjInfoMap();
map.clear();
//this.getManipulateObjCurrInfoMap().clear();
var editor = this.getEditor();
// store original objs coords info into map
for (var i = 0, l = actualObjs.length; i < l; ++i)
{
var obj = actualObjs[i];
var info = this.createManipulateObjInfo(obj, i, startScreenCoord);
map.set(obj, info);
/*
// disable indirect coord during coord move
if (info.enableIndirectCoord)
obj.setEnableIndirectCoord(false);
*/
}
},
/** @private */
doPrepareManipulatingStartingCoords: function(startScreenCoord, startBox, rotateCenter, rotateRefCoord)
{
this.setStartBox(startBox);
this.setRotateCenter(rotateCenter);
this.setRotateRefCoord(rotateRefCoord);
this.setLastRotateAngle(null);
},
/**
* Prepare to move movingObjs.
* Note that movingObjs may differ from actual moved objects (for instance, move a bond actually move its connected atoms).
* @param {Hash} startContextCoord Mouse position when starting to move objects. This coord is based on context.
* @param {Array} manipulatingObjs Objects about to be moved or resized.
* @param {Hash} startBox
* @param {Hash} rotateCenter
* @private
*/
prepareManipulating: function(manipulationType, manipulatingObjs, startScreenCoord, startBox, rotateCenter, rotateRefCoord)
{
this.setManipulationType(manipulationType);
this.doPrepareManipulatingObjects(manipulatingObjs, startScreenCoord);
this.doPrepareManipulatingStartingCoords(startScreenCoord, startBox, rotateCenter, rotateRefCoord);
this.createManipulateOperation();
this._cachedTransformCompareThresholds = null; // clear cache
this._runManipulationStepId = Kekule.window.requestAnimationFrame(this.execManipulationStepBind);
//this.setManuallyHotTrack(true); // manully set hot track point when manipulating
},
/**
* Cancel the moving process and set objects to its original position.
* @private
*/
cancelManipulate: function()
{
var editor = this.getEditor();
var objs = this.getManipulateObjs();
//editor.beginUpdateObject();
//this.getActiveOperation().reverse();
this.reverseActiveOperation();
this.notifyCoordChangeOfObjects(this.getManipulateObjs());
//editor.endUpdateObject();
//this.setActiveOperation(null);
//this.clearActiveOperation();
//this.setManuallyHotTrack(false);
this.manipulateEnd();
},
/**
* Returns center coord of manipulate objs.
* @private
*/
_getManipulateObjsCenterCoord: function()
{
var objs = this.getManipulateObjs();
if (!objs || !objs.length)
return null;
var coordMode = this.getEditor().getCoordMode();
var allowCoordBorrow = this.getEditor().getAllowCoordBorrow();
var sum = {'x': 0, 'y': 0, 'z': 0};
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var objCoord = obj.getAbsBaseCoord? obj.getAbsBaseCoord(coordMode, allowCoordBorrow):
obj.getAbsCoord? obj.getAbsCoord(coordMode, allowCoordBorrow):
obj.getCoordOfMode? obj.getCoordOfMode(coordMode, allowCoordBorrow):
null;
if (objCoord)
sum = Kekule.CoordUtils.add(sum, objCoord);
}
return Kekule.CoordUtils.divide(sum, objs.length);
},
/**
* Called when a phrase of rotate/resize/move function ends.
*/
_maniplateObjsFrameEnd: function(objs)
{
// do nothing here
},
/** @private */
_addManipultingObjNewInfo: function(obj, newInfo)
{
var newInfoMap = this.getManipulateObjCurrInfoMap();
var info = newInfoMap.get(obj) || {};
info = Object.extend(info, newInfo);
newInfoMap.set(obj, info);
},
/** @private */
applyManipulatingObjsInfo: function(endScreenCoord)
{
//this._moveResizeOperExecPending = false;
var objs = this.getManipulateObjs();
var newInfoMap = this.getManipulateObjCurrInfoMap();
var indirectCoordObjs = this._getIndirectCoordObjs(objs);
this._setEnableIndirectCoordOfObjs(indirectCoordObjs, false); // important, disable indirect coord first, avoid calculating during moving and position error
try
{
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
var newInfo = newInfoMap.get(obj);
this.applySingleManipulatingObjInfo(i, obj, newInfo, endScreenCoord);
}
/*
if (this._moveResizeOperExecPending)
this.getMoveWrapperOperation().execute();
*/
}
finally
{
this._setEnableIndirectCoordOfObjs(indirectCoordObjs, true);
}
},
/** @private */
_getIndirectCoordObjs: function(objs)
{
var result = [];
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
if (obj.getEnableIndirectCoord && obj.getEnableIndirectCoord())
result.push(obj);
}
return result;
},
/** @private */
_setEnableIndirectCoordOfObjs: function(objs, enabled)
{
if (!objs)
return;
for (var i = 0, l = objs.length; i < l; ++i)
{
objs[i].setEnableIndirectCoord(enabled);
}
},
/** @private */
applySingleManipulatingObjInfo: function(objIndex, obj, newInfo, endScreenCoord)
{
if (newInfo)
{
if (newInfo.screenCoord)
this.doMoveManipulatedObj(objIndex, obj, newInfo.screenCoord, endScreenCoord);
if (newInfo.size)
this.doResizeManipulatedObj(objIndex, obj, newInfo.size);
}
},
/** @private */
_calcRotateAngle: function(endScreenCoord)
{
var C = Kekule.CoordUtils;
var angle;
var angleCalculated = false;
var rotateCenter = this.getRotateCenter();
var startCoord = this.getRotateRefCoord() || this.getStartCoord();
// ensure startCoord large than threshold
var threshold = this.getEditorConfigs().getInteractionConfigs().getRotationLocationPointDistanceThreshold();
if (threshold)
{
var startDistance = C.getDistance(startCoord, rotateCenter);
if (startDistance < threshold)
{
angle = 0; // do not rotate
angleCalculated = true;
// and use endScreen coord as new start coord
this.setStartCoord(endScreenCoord);
return false;
}
var endDistance = C.getDistance(endScreenCoord, rotateCenter);
if (endDistance < threshold)
{
angle = 0; // do not rotate
angleCalculated = true;
return false;
}
}
if (!angleCalculated)
{
var vector = C.substract(endScreenCoord, rotateCenter);
var endAngle = Math.atan2(vector.y, vector.x);
vector = C.substract(startCoord, rotateCenter);
var startAngle = Math.atan2(vector.y, vector.x);
angle = endAngle - startAngle;
}
return {'angle': angle, 'startAngle': startAngle, 'endAngle': endAngle};
},
/** @private */
_calcActualRotateAngle: function(objs, newDeltaAngle, oldAbsAngle, newAbsAngle)
{
return newDeltaAngle;
},
/** @private */
_calcManipulateObjsRotationParams: function(manipulatingObjs, endScreenCoord)
{
if (!this.getEnableRotate())
return false;
var rotateCenter = this.getRotateCenter();
var angleInfo = this._calcRotateAngle(endScreenCoord);
if (!angleInfo) // need not to rotate
return false;
// get actual rotation angle
var angle = this._calcActualRotateAngle(manipulatingObjs, angleInfo.angle, angleInfo.startAngle, angleInfo.endAngle);
var lastAngle = this.getLastRotateAngle();
if (Kekule.ObjUtils.notUnset(lastAngle) && Kekule.NumUtils.isFloatEqual(angle, lastAngle, 0.0175)) // ignore angle change under 1 degree
{
return false; // no angle change, do not rotate
}
//console.log('rotateAngle', angle, lastAngle);
this.setLastRotateAngle(angle);
return {'center': rotateCenter, 'rotateAngle': angle};
},
/* @private */
/*
doRotateManipulatedObjs: function(endScreenCoord, transformParams)
{
var byPassRotate = !this._calcManipulateObjsTransformInfo(this.getManipulateObjs(), transformParams);
if (byPassRotate) // need not to rotate
{
//console.log('bypass rotate');
return;
}
//console.log('rotate');
var objNewInfo = this.getManipulateObjCurrInfoMap();
var editor = this.getEditor();
editor.beginUpdateObject();
try
{
var objs = this.getManipulateObjs();
this.applyManipulatingObjsInfo(endScreenCoord);
this._maniplateObjsFrameEnd(objs);
this.notifyCoordChangeOfObjects(objs);
}
finally
{
editor.endUpdateObject();
this.manipulateStepDone();
}
},
*/
/*
* Rotate manupulatedObjs according to endScreenCoord.
* @private
*/
/*
rotateManipulatedObjs: function(endScreenCoord)
{
var R = Kekule.Editor.BoxRegion;
var C = Kekule.CoordUtils;
//var editor = this.getEditor();
var changedObjs = [];
//console.log('rotate', this.getRotateCenter(), endScreenCoord);
var rotateParams = this._calcManipulateObjsRotationParams(this.getManipulateObjs(), endScreenCoord);
if (!rotateParams)
return;
this.doRotateManipulatedObjs(endScreenCoord, rotateParams);
},
*/
/** @private */
_calcActualResizeScales: function(objs, newScales)
{
return newScales;
},
/** @private */
_calcManipulateObjsResizeParams: function(manipulatingObjs, startingRegion, endScreenCoord)
{
if (!this.getEnableResize())
return false;
var R = Kekule.Editor.BoxRegion;
var C = Kekule.CoordUtils;
var box = this.getStartBox();
var coordDelta = C.substract(endScreenCoord, this.getStartCoord());
var scaleCenter;
var doConstraint, doConstraintOnX, doConstraintOnY;
if (startingRegion === R.EDGE_TOP)
{
coordDelta.x = 0;
scaleCenter = {'x': (box.x1 + box.x2) / 2, 'y': box.y2};
}
else if (startingRegion === R.EDGE_BOTTOM)
{
coordDelta.x = 0;
scaleCenter = {'x': (box.x1 + box.x2) / 2, 'y': box.y1};
}
else if (startingRegion === R.EDGE_LEFT)
{
coordDelta.y = 0;
scaleCenter = {'x': box.x2, 'y': (box.y1 + box.y2) / 2};
}
else if (startingRegion === R.EDGE_RIGHT)
{
coordDelta.y = 0;
scaleCenter = {'x': box.x1, 'y': (box.y1 + box.y2) / 2};
}
else // resize from corner
{
if (this.isAspectRatioLockedResize())
{
doConstraint = true;
/*
var widthHeightRatio = (box.x2 - box.x1) / (box.y2 - box.y1);
var currRatio = coordDelta.x / coordDelta.y;
if (Math.abs(currRatio) > widthHeightRatio)
//coordDelta.x = coordDelta.y * widthHeightRatio * (Math.sign(currRatio) || 1);
doConstraintOnY = true;
else
//coordDelta.y = coordDelta.x / widthHeightRatio * (Math.sign(currRatio) || 1);
doConstraintOnX = true;
*/
}
scaleCenter = (startingRegion === R.CORNER_TL)? {'x': box.x2, 'y': box.y2}:
(startingRegion === R.CORNER_TR)? {'x': box.x1, 'y': box.y2}:
(startingRegion === R.CORNER_BL)? {'x': box.x2, 'y': box.y1}:
{'x': box.x1, 'y': box.y1};
}
var reversedX = (startingRegion === R.CORNER_TL) || (startingRegion === R.CORNER_BL) || (startingRegion === R.EDGE_LEFT);
var reversedY = (startingRegion === R.CORNER_TL) || (startingRegion === R.CORNER_TR) || (startingRegion === R.EDGE_TOP);
// calc transform matrix
var scaleX, scaleY;
if (Kekule.NumUtils.isFloatEqual(box.x1, box.x2, 1e-10)) // box has no x size, can not scale on x
scaleX = 1;
else
scaleX = 1 + coordDelta.x / (box.x2 - box.x1) * (reversedX? -1: 1);
if (Kekule.NumUtils.isFloatEqual(box.y1, box.y2, 1e-10)) // box has no y size, can not scale on y
scaleY = 1;
else
scaleY = 1 + coordDelta.y / (box.y2 - box.y1) * (reversedY? -1: 1);
if (doConstraint)
{
var absX = Math.abs(scaleX), absY = Math.abs(scaleY);
if (absX >= absY)
scaleY = (Math.sign(scaleY) || 1) * absX; // avoid sign = 0
else
scaleX = (Math.sign(scaleX) || 1) * absY;
}
//console.log('before actual scale', coordDelta, {'scaleX': scaleX, 'scaleY': scaleY});
var actualScales = this._calcActualResizeScales(manipulatingObjs, {'scaleX': scaleX, 'scaleY': scaleY});
var transformParams = {'center': scaleCenter, 'scaleX': actualScales.scaleX, 'scaleY': actualScales.scaleY};
//console.log(this.isAspectRatioLockedResize(), scaleX, scaleY);
//console.log('startBox', box);
//console.log('transformParams', transformParams);
return transformParams;
},
/* @private */
/*
_calcManipulateObjsResizeInfo: function(manipulatingObjs, startingRegion, endScreenCoord)
{
var R = Kekule.Editor.BoxRegion;
var C = Kekule.CoordUtils;
var transformOps = this._calcManipulateObjsResizeParams(manipulatingObjs, startingRegion, endScreenCoord);
//console.log(scaleX, scaleY);
this._calcManipulateObjsTransformInfo(manipulatingObjs, transformOps);
return true;
},
*/
/** @private */
_calcManipulateObjsTransformInfo: function(manipulatingObjs, transformParams)
{
var C = Kekule.CoordUtils;
// since we transform screen coord, it will always be in 2D mode
// and now the editor only supports 2D
var is3D = false; // this.getEditor().getCoordMode() === Kekule.CoordMode.COORD3D;
var transformMatrix = is3D? C.calcTransform3DMatrix(transformParams): C.calcTransform2DMatrix(transformParams);
var scaleX = transformParams.scaleX || transformParams.scale;
var scaleY = transformParams.scaleY || transformParams.scale;
var isMovingOneStickNode = this._isManipulatingSingleStickedObj(manipulatingObjs);
for (var i = 0, l = manipulatingObjs.length; i < l; ++i)
{
var obj = manipulatingObjs[i];
var info = this.getManipulateObjInfoMap().get(obj);
var newInfo = {};
if (!info.hasNoCoord) // this object has coord property and can be rotated
{
var oldCoord = info.screenCoord;
if (!info.stickTarget || isMovingOneStickNode)
{
var newCoord = C.transform2DByMatrix(oldCoord, transformMatrix);
newInfo.screenCoord = newCoord;
}
else
newInfo.screenCoord = oldCoord;
//this._addManipultingObjNewInfo(obj, {'screenCoord': newCoord});
}
// TODO: may need change dimension also
if (info.size && (scaleX || scaleY))
{
var newSize = {'x': info.size.x * Math.abs(scaleX || 1), 'y': info.size.y * Math.abs(scaleY || 1)};
newInfo.size = newSize;
}
this._addManipultingObjNewInfo(obj, newInfo);
}
return true;
},
/**
* Whether an object is sticking to another one.
* @private
*/
_isStickedObj: function(obj)
{
return obj && obj.getCoordStickTarget && obj.getCoordStickTarget();
},
/** @private */
_isManipulatingSingleStickedObj: function(manipulatingObjs)
{
var result = false;
if (manipulatingObjs.length === 1)
{
var oneObj = manipulatingObjs[0];
var info = this.getManipulateObjInfoMap().get(oneObj);
result = !!info.stickTarget;
}
return result;
},
/*
* Resize manupulatedObjs according to endScreenCoord.
* @private
*/
/*
doResizeManipulatedObjs: function(endScreenCoord)
{
var editor = this.getEditor();
var objs = this.getManipulateObjs();
//var changedObjs = [];
this._calcManipulateObjsResizeInfo(objs, this.getResizeStartingRegion(), endScreenCoord);
editor.beginUpdateObject();
var newInfoMap = this.getManipulateObjCurrInfoMap();
try
{
this.applyManipulatingObjsInfo(endScreenCoord);
this._maniplateObjsFrameEnd(objs);
this.notifyCoordChangeOfObjects(objs);
}
finally
{
editor.endUpdateObject();
this.manipulateStepDone();
}
},
*/
/**
* Transform manupulatedObjs according to manipulateType(rotate/resize) endScreenCoord.
* @private
*/
doTransformManipulatedObjs: function(manipulateType, endScreenCoord, explicitTransformParams)
{
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var editor = this.getEditor();
var objs = this.getManipulateObjs();
//var changedObjs = [];
var transformParams = explicitTransformParams;
if (!transformParams)
{
if (manipulateType === T.RESIZE)
transformParams = this._calcManipulateObjsResizeParams(objs, this.getResizeStartingRegion(), endScreenCoord);
else if (manipulateType === T.ROTATE)
transformParams = this._calcManipulateObjsRotationParams(objs, endScreenCoord);
}
if (this._lastTransformParams && this._isSameTransformParams(this._lastTransformParams, transformParams, null, editor.getCoordMode())) // not a significant change, do not transform
{
//console.log('bypass transform');
return;
}
//console.log('do transform', transformParams);
var doConcreteTransform = transformParams && this._calcManipulateObjsTransformInfo(objs, transformParams);
if (!doConcreteTransform)
return;
this._lastTransformParams = transformParams;
editor.beginUpdateObject();
var newInfoMap = this.getManipulateObjCurrInfoMap();
try
{
this.applyManipulatingObjsInfo(endScreenCoord);
this._maniplateObjsFrameEnd(objs);
this.notifyCoordChangeOfObjects(objs);
}
finally
{
editor.endUpdateObject();
this.manipulateStepDone();
}
},
/** @private */
_isSameTransformParams: function(p1, p2, thresholds, coordMode)
{
if (!thresholds)
{
thresholds = this._cachedTransformCompareThresholds;
}
if (!thresholds)
{
thresholds = this._getTransformCompareThresholds(); // 0.1
this._cachedTransformCompareThresholds = thresholds; // cache the threshold to reduce calculation
}
/*
if (coordMode === Kekule.CoordMode.COORD2D)
return CU.isSameTransform2DOptions(p1, p2, {'translate': threshold, 'scale': threshold, 'rotate': threshold});
else
return CU.isSameTransform3DOptions(p1, p2, {'translate': threshold, 'scale': threshold, 'rotate': threshold});
*/
if (coordMode === Kekule.CoordMode.COORD2D)
return CU.isSameTransform2DOptions(p1, p2, {'translate': thresholds.translate, 'scale': thresholds.scale, 'rotate': thresholds.rotate});
else
return CU.isSameTransform3DOptions(p1, p2, {'translate': thresholds.translate, 'scale': thresholds.scale, 'rotate': thresholds.rotate});
},
/** @private */
_getTransformCompareThresholds: function(coordMode)
{
return {
translate: 0.1,
scale: 0.1,
rotate: 0.1
}
},
/* @private */
_calcActualMovedScreenCoord: function(obj, info, newScreenCoord)
{
return newScreenCoord;
},
/** @private */
_calcManipulateObjsMoveInfo: function(manipulatingObjs, endScreenCoord)
{
var C = Kekule.CoordUtils;
var newInfoMap = this.getManipulateObjCurrInfoMap();
var editor = this.getEditor();
var isMovingOneStickNode = this._isManipulatingSingleStickedObj(manipulatingObjs);
var isDirectManipulateSingleObj = this.isDirectManipulating() && (manipulatingObjs.length === 1);
var manipulatingObjHasSize = isDirectManipulateSingleObj?
(manipulatingObjs[0] && manipulatingObjs[0].getSizeOfMode && manipulatingObjs[0].getSizeOfMode(editor.getCoordMode(), editor.getAllowCoordBorrow())):
true;
var followPointerCoord = isDirectManipulateSingleObj && !manipulatingObjHasSize // when the object has size, it can not follow the pointer coord
&& this.getEditorConfigs().getInteractionConfigs().getFollowPointerCoordOnDirectManipulatingSingleObj();
if (followPointerCoord)
{
var startCoord = this.getStartCoord();
var moveDistance = C.getDistance(endScreenCoord, startCoord);
if (moveDistance <= this.getEditorConfigs().getInteractionConfigs().getFollowPointerCoordOnDirectManipulatingSingleObjDistanceThreshold())
{
followPointerCoord = false;
}
}
for (var i = 0, l = manipulatingObjs.length; i < l; ++i)
{
var obj = manipulatingObjs[i];
var info = this.getManipulateObjInfoMap().get(obj);
if (info.hasNoCoord) // this object has no coord property and can not be moved
continue;
if (info.stickTarget && !isMovingOneStickNode)
continue;
var newScreenCoord;
if (followPointerCoord)
newScreenCoord = endScreenCoord;
else
newScreenCoord = C.add(endScreenCoord, info.screenCoordOffset);
newScreenCoord = this._calcActualMovedScreenCoord(obj, info, newScreenCoord);
this._addManipultingObjNewInfo(obj, {'screenCoord': newScreenCoord});
}
},
/**
* Move objects in manipulateObjs array to new position. New coord is determinated by endContextCoord
* and each object's offset.
* @private
*/
moveManipulatedObjs: function(endScreenCoord)
{
var C = Kekule.CoordUtils;
var editor = this.getEditor();
var objs = this.getManipulateObjs();
var changedObjs = [];
this._calcManipulateObjsMoveInfo(objs, endScreenCoord);
editor.beginUpdateObject();
var newInfoMap = this.getManipulateObjCurrInfoMap();
try
{
this.applyManipulatingObjsInfo(endScreenCoord);
this._maniplateObjsFrameEnd(objs);
// notify
this.notifyCoordChangeOfObjects(objs);
}
finally
{
editor.endUpdateObject();
this.manipulateStepDone();
}
},
/**
* Move a single object to newScreenCoord. MoverScreenCoord is the actual coord of mouse.
* Note that not only move operation will call this method, rotate and resize may also affect
* objects' coord so this method will also be called.
* @private
*/
doMoveManipulatedObj: function(objIndex, obj, newScreenCoord, moverScreenCoord)
{
var editor = this.getEditor();
this.updateChildMoveOperation(objIndex, obj, editor.screenCoordToObj(newScreenCoord));
editor.setObjectScreenCoord(obj, newScreenCoord);
//this._moveResizeOperExecPending = true;
},
/**
* Resize a single object to newDimension.
* @private
*/
doResizeManipulatedObj: function(objIndex, obj, newSize)
{
this.updateChildResizeOperation(objIndex, obj, newSize);
if (obj.setSizeOfMode)
obj.setSizeOfMode(newSize, this.getEditor().getCoordMode());
//this._moveResizeOperExecPending = true;
},
/*
* Moving complete, do the wrap up job.
* @private
*/
/*
endMoving: function()
{
this.stopManipulate();
},
*/
/**
* Returns whether the controller is in direct manipulating state.
*/
isDirectManipulating: function()
{
return (this.getState() === Kekule.Editor.BasicManipulationIaController.State.MANIPULATING)
&& (!this.getIsManipulatingSelection());
},
/**
* Click on a object or objects and manipulate it directly.
* @private
*/
startDirectManipulate: function(manipulateType, objOrObjs, startCoord, startBox, rotateCenter, rotateRefCoord)
{
this.manipulateBegin();
return this.doStartDirectManipulate(manipulateType, objOrObjs, startCoord, startBox, rotateCenter, rotateRefCoord);
},
/** @private */
doStartDirectManipulate: function(manipulateType, objOrObjs, startCoord, startBox, rotateCenter, rotateRefCoord)
{
var objs = Kekule.ArrayUtils.toArray(objOrObjs);
this.setState(Kekule.Editor.BasicManipulationIaController.State.MANIPULATING);
this.setBaseCoord(startCoord);
this.setStartCoord(startCoord);
this.setRotateRefCoord(rotateRefCoord);
this.setIsManipulatingSelection(false);
//console.log('call prepareManipulating', startCoord, manipulateType, objOrObjs);
this.prepareManipulating(manipulateType || Kekule.Editor.BasicManipulationIaController.ManipulationType.MOVE, objs, startCoord, startBox, rotateCenter, rotateRefCoord);
},
/**
* Called when a manipulation is applied and the changes has been reflected in editor (editor redrawn done).
* Descendants may override this method.
* @private
*/
manipulateStepDone: function()
{
// do nothing here
},
/** @private */
doManipulateObjectsEnd: function(manipulatingObjs)
{
var map = this.getManipulateObjInfoMap();
for (var i = manipulatingObjs.length - 1; i >= 0; --i)
{
this.doManipulateObjectEnd(manipulatingObjs[i], map.get(manipulatingObjs[i]));
}
},
/** @private */
doManipulateObjectEnd: function(manipulateObj, objInfo)
{
/*
if (objInfo.enableIndirectCoord && manipulateObj.setEnableIndirectCoord)
manipulateObj.setEnableIndirectCoord(true);
*/
},
/**
* Called when a manipulation is beginning (usually with point down event).
* Descendants may override this method.
* @private
*/
manipulateBegin: function()
{
this.notifyEditorBeginManipulateObjects();
},
/**
* Called when a manipulation is ended (stopped or cancelled).
* Descendants may override this method.
* @private
*/
manipulateEnd: function()
{
if (this._runManipulationStepId)
{
Kekule.window.cancelAnimationFrame(this._runManipulationStepId);
this._runManipulationStepId = null;
}
this.doManipulateObjectsEnd(this.getManipulateObjs());
this._lastTransformParams = null;
this.setIsOffsetManipulating(false);
this.setManipulateObjs(null);
this.getManipulateObjInfoMap().clear();
this.getObjOperationMap().clear();
this.notifyEditorEndManipulateObjects();
},
/**
* Called before method stopManipulate.
* Descendants may do some round-off work here.
* @private
*/
manipulateBeforeStopping: function()
{
// do nothing here
},
/**
* Stop manipulate of objects.
* @private
*/
stopManipulate: function()
{
this.manipulateEnd();
},
/** @private */
refreshManipulateObjs: function()
{
this.setManipulateObjs(this.getManipulateObjs());
},
/** @private */
createManipulateObjInfo: function(obj, objIndex, startScreenCoord)
{
var editor = this.getEditor();
var info = {
//'obj': obj,
'objCoord': editor.getObjCoord(obj), // abs base coord
//'objSelfCoord': obj.getCoordOfMode? obj.getCoordOfMode(editor.getCoordMode()): null,
'screenCoord': editor.getObjectScreenCoord(obj),
'size': editor.getObjSize(obj),
'enableIndirectCoord': !!(obj.getEnableIndirectCoord && obj.getEnableIndirectCoord())
};
info.hasNoCoord = !info.objCoord;
if (!info.hasNoCoord && startScreenCoord)
info.screenCoordOffset = Kekule.CoordUtils.substract(info.screenCoord, startScreenCoord);
if (obj.getCoordStickTarget) // wether is a sticking object
{
info.stickTarget = obj.getCoordStickTarget();
}
return info;
},
/** @private */
notifyCoordChangeOfObjects: function(objs)
{
var changedDetails = [];
var editor = this.getEditor();
var coordPropName = this.getEditor().getCoordMode() === Kekule.CoordMode.COORD3D? 'coord3D': 'coord2D';
for (var i = 0, l = objs.length; i < l; ++i)
{
var obj = objs[i];
Kekule.ArrayUtils.pushUnique(changedDetails, {'obj': obj, 'propNames': [coordPropName]});
var relatedObjs = obj.getCoordDeterminateObjects? obj.getCoordDeterminateObjects(): [obj];
for (var j = 0, k = relatedObjs.length; j < k; ++j)
Kekule.ArrayUtils.pushUnique(changedDetails, {'obj': relatedObjs[j], 'propNames': [coordPropName]});
}
// notify
editor.objectsChanged(changedDetails);
},
/** @private */
canInteractWithObj: function(obj)
{
return (this.getState() === Kekule.Editor.BasicManipulationIaController.State.NORMAL) && obj;
},
/** @ignore */
doTestMouseCursor: function(coord, e)
{
if (!this.getEditor().isRenderable()) // if chem object not painted, do not need to test
return '';
var result = '';
// since client element is not the same to widget element, coord need to be recalculated
var c = this._getEventMouseCoord(e, this.getEditor().getEditClientElem());
if (this.getState() === Kekule.Editor.BasicManipulationIaController.State.NORMAL)
{
var R = Kekule.Editor.BoxRegion;
var region = this.getEditor().getCoordRegionInSelectionMarker(c);
if (this.getEnableSelect()) // show move/rotate/resize marker in select ia controller only
{
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var availManipulationTypes = this.getCurrAvailableManipulationTypes();
//if (this.getEnableMove())
if (availManipulationTypes.indexOf(T.MOVE) >= 0)
{
result = (region === R.INSIDE)? 'move': '';
}
//if (!result && this.getEnableResize())
if (!result && (availManipulationTypes.indexOf(T.RESIZE) >= 0))
{
var result =
(region === R.CORNER_TL)? 'nwse-resize':
(region === R.CORNER_TR)? 'nesw-resize':
(region === R.CORNER_BL)? 'nesw-resize':
(region === R.CORNER_BR)? 'nwse-resize':
(region === R.EDGE_TOP) || (region === R.EDGE_BOTTOM)? 'ns-resize':
(region === R.EDGE_LEFT) || (region === R.EDGE_RIGHT)? 'ew-resize':
'';
}
if (!result)
{
//if (this.getEnableRotate())
if (availManipulationTypes.indexOf(T.ROTATE) >= 0)
{
var region = this.getCoordOnSelectionRotationRegion(c);
if (!!region)
{
var SN = Kekule.Widget.StyleResourceNames;
result = (region === R.CORNER_TL)? SN.CURSOR_ROTATE_NW:
(region === R.CORNER_TR)? SN.CURSOR_ROTATE_NE:
(region === R.CORNER_BL)? SN.CURSOR_ROTATE_SW:
(region === R.CORNER_BR)? SN.CURSOR_ROTATE_SE:
SN.CURSOR_ROTATE;
//console.log('rotate cursor', result);
}
}
}
}
}
return result;
},
/**
* Set operations in suspended state.
* @param {Func} immediateOper
* @param {Func} delayedOper
* @param {Int} delay In ms.
* @private
*/
setSuspendedOperations: function(immediateOper, delayedOper, delay)
{
if (this._suspendedOperations)
this.haltSuspendedOperations(); // halt old
var self = this;
this._suspendedOperations = {
'immediate': immediateOper,
'delayed': delayedOper,
'delayExecId': setTimeout(this.execSuspendedDelayOperation.bind(this), delay)
};
return this._suspendedOperations;
},
/**
* Execute the immediate operation in suspended operations, cancelling the delayed one.
* @private
*/
execSuspendedImmediateOperation: function()
{
if (this._suspendedOperations)
{
//console.log('exec immediate');
clearTimeout(this._suspendedOperations.delayExecId);
var oper = this._suspendedOperations.immediate;
this._suspendedOperations = null; // clear old
return oper.apply(this);
}
},
/**
* Execute the delayed operation in suspended operations, cancelling the immediate one.
* @private
*/
execSuspendedDelayOperation: function()
{
if (this._suspendedOperations)
{
//console.log('exec delayed');
clearTimeout(this._suspendedOperations.delayExecId);
var oper = this._suspendedOperations.delayed;
this._suspendedOperations = null; // clear old
return oper.apply(this);
}
},
/**
* Halt all suspend operations.
* @private
*/
haltSuspendedOperations: function()
{
if (this._suspendedOperations)
{
clearTimeout(this._suspendedOperations.delayExecId);
this._suspendedOperations = null; // clear old
}
},
/** @private */
_startNewSelecting: function(startCoord, shifted)
{
if (this.getEnableSelect())
{
this.getEditor().startSelecting(startCoord, shifted || this.getEditor().getIsToggleSelectOn());
this.setState(Kekule.Editor.BasicManipulationIaController.State.SELECTING);
}
},
/** @private */
_startOffSelectionManipulation: function(currCoord)
{
//console.log('off selection!');
this.setIsOffsetManipulating(true);
this.startManipulation(currCoord, null, Kekule.Editor.BasicManipulationIaController.ManipulationType.MOVE);
this.getEditor().pulseSelectionAreaMarker(); // pulse selection, reach the user's attention
},
/**
* Begin a manipulation.
* Descendants may override this method.
* @param {Hash} currCoord Current coord of pointer (mouse or touch)
* @param {Object} e Pointer (mouse or touch) event parameter.
*/
startManipulation: function(currCoord, e, explicitManipulationType)
{
var S = Kekule.Editor.BasicManipulationIaController.State;
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var availManipulationTypes = this.getCurrAvailableManipulationTypes();
var evokedByTouch = e && e.pointerType === 'touch'; // edge resize/rotate will be disabled in touch
if (e)
{
this.setManipulationPointerType(e && e.pointerType);
}
this.manipulateBegin();
this.setBaseCoord(currCoord);
this.setStartCoord(currCoord);
this._lastTransformParams = null;
var coordRegion = currCoord && this.getEditor().getCoordRegionInSelectionMarker(currCoord);
var R = Kekule.Editor.BoxRegion;
var rotateRegion = currCoord && this.getCoordOnSelectionRotationRegion(currCoord);
// test manipulate type
/*
var isTransform = (this.getEnableResize() || this.getEnableRotate())
&& (explicitManipulationType === T.TRANSFORM); // gesture transform
*/
var isTransform = (availManipulationTypes.indexOf(T.TRANSFORM) >= 0)
&& (explicitManipulationType === T.TRANSFORM); // gesture transform
//console.log('check isTransform', isTransform, explicitManipulationType, availManipulationTypes);
if (!isTransform)
{
var isResize = !evokedByTouch && (availManipulationTypes.indexOf(T.RESIZE) >= 0) //&& this.getEnableResize()
&& ((explicitManipulationType === T.RESIZE) || ((coordRegion !== R.INSIDE) && (coordRegion !== R.OUTSIDE)));
var isMove = !isResize && (availManipulationTypes.indexOf(T.MOVE) >= 0) // this.getEnableMove()
&& ((explicitManipulationType === T.MOVE) || (coordRegion !== R.OUTSIDE));
var isRotate = !evokedByTouch && !isResize && !isMove && (availManipulationTypes.indexOf(T.ROTATE) >= 0)//this.getEnableRotate()
&& ((explicitManipulationType === T.ROTATE) || !!rotateRegion);
}
else // transform
{
//console.log('set transform types', availManipulationTypes);
this._availTransformTypes = availManipulationTypes; // stores the available transform types
}
if (!isTransform && !isResize && !isRotate) // when pointer not at resize or rotate position, check if it is directly on an object to evoke direct manipulation
{
// check if mouse just on an object, if so, direct manipulation mode
var hoveredObj = this.getEditor().getTopmostBasicObjectAtCoord(currCoord, this.getCurrBoundInflation());
if (hoveredObj && !evokedByTouch) // mouse down directly on a object
{
//hoveredObj = hoveredObj.getNearestSelectableObject();
if (this.isInAncestorSelectMode())
hoveredObj = this.getStandaloneAncestor(hoveredObj);
hoveredObj = hoveredObj.getNearestMovableObject();
if (this.getEnableMove())
{
this.doStartDirectManipulate(null, hoveredObj, currCoord); // call doStartDirectManipulate rather than startDirectManipulate, avoid calling doStartDirectManipulate twice
return;
}
}
}
// check if already has selection and mouse in selection rect first
//if (this.getEditor().isCoordInSelectionMarkerBound(coord))
if (isTransform)
{
this.setState(S.MANIPULATING);
this.setIsManipulatingSelection(true);
this.setResizeStartingRegion(coordRegion);
this.setRotateStartingRegion(rotateRegion);
this.prepareManipulating(T.TRANSFORM, this.getEditor().getSelection(), currCoord, this.getEditor().getSelectionContainerBox());
}
else if (isResize)
{
this.setState(S.MANIPULATING);
this.setIsManipulatingSelection(true);
this.setResizeStartingRegion(/*this.getEditor().getCoordRegionInSelectionMarker(coord)*/coordRegion);
//console.log('box', this.getEditor().getUiSelectionAreaContainerBox());
this.prepareManipulating(T.RESIZE, this.getEditor().getSelection(), currCoord, this.getEditor().getSelectionContainerBox());
//console.log('Resize');
}
else if (isMove)
{
//if (this.getEnableMove())
{
this.setState(S.MANIPULATING);
this.setIsManipulatingSelection(true);
this.prepareManipulating(T.MOVE, this.getEditor().getSelection(), currCoord);
}
}
else if (isRotate)
{
this.setState(S.MANIPULATING);
this.setIsManipulatingSelection(true);
this.setRotateStartingRegion(rotateRegion);
this.prepareManipulating(T.ROTATE, this.getEditor().getSelection(), currCoord, this.getEditor().getSelectionContainerBox());
}
else
{
/*
var obj = this.getEditor().getTopmostBasicObjectAtCoord(currCoord, this.getCurrBoundInflation());
if (obj) // mouse down directly on a object
{
obj = obj.getNearestSelectableObject();
if (this.isInAncestorSelectMode())
obj = this.getStandaloneAncestor(obj);
// only mouse down and moved will cause manupulating
if (this.getEnableMove())
this.startDirectManipulate(null, obj, currCoord);
}
*/
if (hoveredObj) // point on an object, direct move
{
if (this.getEnableMove())
this.startDirectManipulate(null, hoveredObj, currCoord);
}
else // pointer down on empty region, deselect old selection and prepare for new selecting
{
if (this.getEnableMove() && this.getEnableSelect()
&& this.getEditorConfigs().getInteractionConfigs().getEnableOffSelectionManipulation()
&& this.getEditor().hasSelection() && this.getEditor().isSelectionVisible())
{
//console.log('enter suspend');
this.setState(S.SUSPENDING);
// need wait for a while to determinate the actual operation
var delay = this.getEditorConfigs().getInteractionConfigs().getOffSelectionManipulationActivatingTimeThreshold();
var shifted = e && e.getShiftKey();
this.setSuspendedOperations(
this._startNewSelecting.bind(this, currCoord, shifted),
this._startOffSelectionManipulation.bind(this, currCoord),
delay
);
//this._startOffSelectionManipulation(currCoord);
}
else if (this.getEnableSelect())
{
var shifted = e && e.getShiftKey();
/*
//this.getEditor().startSelectingBoxDrag(currCoord, shifted);
//this.getEditor().setSelectMode(this.getSelectMode());
this.getEditor().startSelecting(currCoord, shifted);
this.setState(S.SELECTING);
*/
this._startNewSelecting(currCoord, shifted);
}
}
}
},
/**
* Do manipulation based on mouse/touch move step.
* //@param {Hash} currCoord Current coord of pointer (mouse or touch)
* //@param {Object} e Pointer (mouse or touch) event parameter.
*/
execManipulationStep: function(/*currCoord, e*/timeStamp)
{
if (this.getState() !== Kekule.Editor.BasicManipulationIaController.State.MANIPULATING)
return false;
var currCoord = this._manipulationStepBuffer.coord;
var e = this._manipulationStepBuffer.event;
var explicitTransformParams = this._manipulationStepBuffer.explicitTransformParams;
//console.log('step', this.getState(), this._manipulationStepBuffer.explicitTransformParams);
if (explicitTransformParams) // has transform params explicitly in gesture transform
{
this.doExecManipulationStepWithExplicitTransformParams(explicitTransformParams, this._manipulationStepBuffer);
}
else if (currCoord && e)
{
//console.log('do actual manipulate');
this.doExecManipulationStep(currCoord, e, this._manipulationStepBuffer);
// empty buffer, indicating that the event has been handled
}
this._manipulationStepBuffer.coord = null;
this._manipulationStepBuffer.event = null;
this._manipulationStepBuffer.explicitTransformParams = null;
/*
if (this._lastTimeStamp)
console.log('elpase', timeStamp - this._lastTimeStamp);
this._lastTimeStamp = timeStamp;
*/
this._runManipulationStepId = Kekule.window.requestAnimationFrame(this.execManipulationStepBind);
},
/**
* Do actual manipulation based on mouse/touch move step.
* Descendants may override this method.
* @param {Hash} currCoord Current coord of pointer (mouse or touch)
* @param {Object} e Pointer (mouse or touch) event parameter.
*/
doExecManipulationStep: function(currCoord, e, manipulationStepBuffer)
{
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var manipulateType = this.getManipulationType();
var editor = this.getEditor();
editor.beginUpdateObject();
try
{
this._isBusy = true;
if (manipulateType === T.MOVE)
{
this.moveManipulatedObjs(currCoord);
}
else if (manipulateType === T.RESIZE)
{
//this.doResizeManipulatedObjs(currCoord);
this.doTransformManipulatedObjs(manipulateType, currCoord);
}
else if (manipulateType === T.ROTATE)
{
//this.rotateManipulatedObjs(currCoord);
this.doTransformManipulatedObjs(manipulateType, currCoord);
}
}
finally
{
editor.endUpdateObject();
this._isBusy = false;
}
},
/**
* Do actual manipulation based on mouse/touch move step.
* Descendants may override this method.
* @param {Hash} currCoord Current coord of pointer (mouse or touch)
* @param {Object} e Pointer (mouse or touch) event parameter.
*/
doExecManipulationStepWithExplicitTransformParams: function(transformParams, manipulationStepBuffer)
{
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var manipulateType = this.getManipulationType();
if (manipulateType === T.TRANSFORM)
{
var editor = this.getEditor();
editor.beginUpdateObject();
try
{
this._isBusy = true;
this.doTransformManipulatedObjs(manipulateType, null, transformParams);
}
finally
{
editor.endUpdateObject();
this._isBusy = false;
}
}
},
/**
* Refill the manipulationStepBuffer.
* Descendants may override this method.
* @param {Object} e Pointer (mouse or touch) event parameter.
* @private
*/
updateManipulationStepBuffer: function(buffer, value)
{
Object.extend(buffer, value);
/*
buffer.coord = coord;
buffer.event = e;
*/
},
// event handle methods
/** @ignore */
react_pointermove: function(/*$super, */e)
{
this.tryApplySuper('react_pointermove', [e]) /* $super(e) */;
if (this._isBusy)
{
return true;
}
if (Kekule.ObjUtils.notUnset(this.getActivePointerId()) && e.pointerId !== this.getActivePointerId())
{
//console.log('hhh', e.pointerId, this.getActivePointerId());
return true;
}
var S = Kekule.Editor.BasicManipulationIaController.State;
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
var state = this.getState();
var coord = this._getEventMouseCoord(e);
var distanceFromLast;
if (state === S.NORMAL || state === S.SUSPENDING)
{
if (this._lastMouseMoveCoord)
{
var dis = Kekule.CoordUtils.getDistance(coord, this._lastMouseMoveCoord);
distanceFromLast = dis;
if (dis < 4) // less than 4 px, too tiny to react
{
return true;
}
}
}
this._lastMouseMoveCoord = coord;
/*
if (state !== S.NORMAL)
this.getEditor().hideHotTrack();
if (state === S.NORMAL)
{
// in normal state, if mouse moved to boundary of a object, it may be highlighted
this.getEditor().hotTrackOnCoord(coord);
}
else
*/
if (state === S.SUSPENDING)
{
var disThreshold = this.getEditorConfigs().getInteractionConfigs().getUnmovePointerDistanceThreshold() || 0;
if (Kekule.ObjUtils.notUnset(distanceFromLast) && (distanceFromLast > disThreshold))
this.execSuspendedImmediateOperation();
}
if (state === S.SELECTING)
{
if (this.getEnableSelect())
{
//this.getEditor().dragSelectingBoxToCoord(coord);
this.getEditor().addSelectingAnchorCoord(coord);
}
e.preventDefault();
}
else if (state === S.MANIPULATING) // move or resize objects
{
//console.log('mouse move', coord);
this.updateManipulationStepBuffer(this._manipulationStepBuffer, {'coord': coord, 'event': e});
//this.execManipulationStep(coord, e);
e.preventDefault();
}
return true;
},
/** @private */
react_pointerdown: function(/*$super, */e)
{
this.tryApplySuper('react_pointerdown', [e]) /* $super(e) */;
//console.log('pointerdown', e);
this.setActivePointerId(e.pointerId);
var S = Kekule.Editor.BasicManipulationIaController.State;
//var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
if (e.getButton() === Kekule.X.Event.MouseButton.LEFT)
{
this._lastMouseMoveCoord = null;
var coord = this._getEventMouseCoord(e);
if ((this.getState() === S.NORMAL)/* && (this.getEditor().getMouseLBtnDown()) */)
{
//var evokedByTouch = e && e.pointerType === 'touch';
var self = this;
var beginNormalManipulation = function(){
if (self.getState() === S.NORMAL || self.getState() === S.SUSPENDING)
{
self.startManipulation(coord, e);
e.preventDefault();
}
};
this.setState(S.SUSPENDING);
// wait for a while for the possible gesture operations
this.setSuspendedOperations(beginNormalManipulation, beginNormalManipulation, 50);
}
}
else if (e.getButton() === Kekule.X.Event.MouseButton.RIGHT)
{
//if (this.getEnableMove())
{
if (this.getState() === S.MANIPULATING) // when click right button on manipulating, just cancel it.
{
this.cancelManipulate();
this.setState(S.NORMAL);
e.stopPropagation();
e.preventDefault();
}
else if (this.getState() === S.SUSPENDING)
this.haltSuspendedOperations();
}
}
return true;
},
/** @private */
react_pointerup: function(e)
{
if (e.getButton() === Kekule.X.Event.MouseButton.LEFT)
{
var coord = this._getEventMouseCoord(e);
this.setEndCoord(coord);
var startCoord = this.getStartCoord();
var endCoord = coord;
var shifted = e.getShiftKey();
var S = Kekule.Editor.BasicManipulationIaController.State;
if (this.getState() === S.SUSPENDING) // done suspended first, then finish the operation
this.execSuspendedImmediateOperation();
var state = this.getState();
if (state === S.SELECTING) // mouse up, end selecting
{
//this.getEditor().endSelectingBoxDrag(coord, shifted);
this.getEditor().endSelecting(coord, shifted || this.getEditor().getIsToggleSelectOn());
this.setState(S.NORMAL);
e.preventDefault();
var editor = this.getEditor();
editor.endManipulateObject();
}
else if (state === S.MANIPULATING)
{
//var dis = Kekule.CoordUtils.getDistance(startCoord, endCoord);
//if (dis <= this.getEditorConfigs().getInteractionConfigs().getUnmovePointerDistanceThreshold())
if (startCoord && endCoord && Kekule.CoordUtils.isEqual(startCoord, endCoord)) // mouse down and up in same point, not manupulate, just select a object
{
if (this.getEnableSelect())
this.getEditor().selectOnCoord(startCoord, shifted || this.getEditor().getIsToggleSelectOn());
}
else // move objects to new pos
{
this.manipulateBeforeStopping();
/*
if (this.getEnableMove())
{
//this.moveManipulatedObjs(coord);
//this.endMoving();
// add operation to editor's historys
this.addOperationToEditor();
}
*/
this.addOperationToEditor();
}
this.stopManipulate();
this.setState(S.NORMAL);
e.preventDefault();
}
}
return true;
},
/** @private */
react_mousewheel: function(/*$super, */e)
{
if (e.getCtrlKey())
{
var state = this.getState();
if (state === Kekule.Editor.BasicManipulationIaController.State.NORMAL)
{
// disallow mouse zoom during manipulation
return this.tryApplySuper('react_mousewheel', [e]) /* $super(e) */;
}
e.preventDefault();
}
},
/* @private */
/*
react_keyup: function(e)
{
var keyCode = e.getKeyCode();
switch (keyCode)
{
case 46: // delete
{
if (this.getEnableRemove())
this.removeSelection();
}
}
}
*/
//////////////////// Hammer Gesture event handlers ///////////////////////////
/** @private */
_isGestureManipulationEnabled: function()
{
return this.getEditorConfigs().getInteractionConfigs().getEnableGestureManipulation();
},
/** @private */
_isGestureZoomOnEditorEnabled: function()
{
return this.getEditorConfigs().getInteractionConfigs().getEnableGestureZoomOnEditor();
},
/** @private */
_isInGestureManipulation: function()
{
return !!this._initialGestureTransformParams;
},
/** @private */
_isGestureZoomOnEditor: function()
{
return !!this._initialGestureZoomLevel;
},
/**
* Starts a gesture transform.
* @param {Object} event
* @private
*/
beginGestureTransform: function(event)
{
if (this.getEditor().hasSelection())
{
this._initialGestureZoomLevel = null;
if (this._isGestureManipulationEnabled())
{
this.haltSuspendedOperations(); // halt possible touch hold manipulations
// stores initial gesture transform params
this._initialGestureTransformParams = {
'angle': (event.rotation * Math.PI / 180) || 0
};
//console.log('begin gesture manipulation', this.getState(), this.getManipulationType());
// start a brand new one
if (this.getState() !== Kekule.Editor.BasicManipulationIaController.State.MANIPULATING)
{
this.startManipulation(null, null, Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM);
}
else
{
if (this.getManipulationType() !== Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM)
{
// the gesture event may be evoked after pointerdown event,
// and in pointerdown, a calling to startManipulation without transform may be already called.
// So here we force a new manipulation with transform on.
//this.setManipulationType(Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM);
this.startManipulation(null, null, Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM);
}
}
}
else
this._initialGestureTransformParams = null;
}
else if (this._isGestureZoomOnEditorEnabled()) // zoom on editor
{
this.getEditor().cancelSelecting(); // force store the selecting
this.setState(Kekule.Editor.BasicManipulationIaController.State.NORMAL);
this._initialGestureZoomLevel = this.getEditor().getZoom();
}
},
/**
* Ends a gesture transform.
* @private
*/
endGestureTransform: function()
{
if (this.getState() === Kekule.Editor.BasicManipulationIaController.State.MANIPULATING) // stop prev manipulation first
{
if (this._isInGestureManipulation())
{
this.manipulateBeforeStopping();
this.addOperationToEditor();
this.stopManipulate();
this.setState(Kekule.Editor.BasicManipulationIaController.State.NORMAL);
this._initialGestureTransformParams = null;
}
}
if (this._isGestureZoomOnEditor())
{
this._initialGestureZoomLevel = null;
}
},
/**
* Do a new transform step according to received event.
* @param {Object} e Gesture event received.
* @private
*/
doGestureTransformStep: function(e)
{
var T = Kekule.Editor.BasicManipulationIaController.ManipulationType;
if ((this.getState() === Kekule.Editor.BasicManipulationIaController.State.MANIPULATING)
&& (this.getManipulationType() === T.TRANSFORM)
&& (this._isInGestureManipulation()))
{
var availTransformTypes = this._availTransformTypes || [];
// get transform params from event directly
var center = this.getRotateCenter(); // use the center of current editor selection
var resizeScales, rotateAngle;
if (availTransformTypes.indexOf(T.RESIZE) >= 0)
{
var scale = e.scale;
resizeScales = this._calcActualResizeScales(this.getManipulateObjs(), {'scaleX': scale, 'scaleY': scale});
}
else
resizeScales = {'scaleX': 1, 'scaleY': 1};
if (availTransformTypes.indexOf(T.ROTATE) >= 0)
{
var absAngle = e.rotation * Math.PI / 180;
var rotateAngle = absAngle - this._initialGestureTransformParams.angle;
// get actual rotation angle
rotateAngle = this._calcActualRotateAngle(this.getManipulateObjs(), rotateAngle, this._initialGestureTransformParams.angle, absAngle);
}
else
{
rotateAngle = 0;
}
//console.log('here', resizeScales.scaleX, resizeScales.scaleY, rotateAngle, availTransformTypes);
this.updateManipulationStepBuffer(this._manipulationStepBuffer, {
'explicitTransformParams': {
'center': center,
'scaleX': resizeScales.scaleX, 'scaleY': resizeScales.scaleY,
'rotateAngle': rotateAngle
//'rotateDegree': e.rotation,
//'event': e
}
});
e.preventDefault();
}
else if (this._isGestureZoomOnEditor())
{
var editor = this.getEditor();
var scale = e.scale;
var initZoom = this._initialGestureZoomLevel;
editor.zoomTo(initZoom * scale, null, e.center);
}
},
/** @ignore */
react_rotatestart: function(e)
{
if (this.getEnableGestureManipulation())
this.beginGestureTransform(e);
},
/** @ignore */
react_rotate: function(e)
{
if (this.getEnableGestureManipulation())
this.doGestureTransformStep(e);
},
/** @ignore */
react_rotateend: function(e)
{
if (this.getEnableGestureManipulation())
this.endGestureTransform();
},
/** @ignore */
react_rotatecancel: function(e)
{
if (this.getEnableGestureManipulation())
this.endGestureTransform();
},
/** @ignore */
react_pinchstart: function(e)
{
if (this.getEnableGestureManipulation())
this.beginGestureTransform(e);
},
/** @ignore */
react_pinchmove: function(e)
{
if (this.getEnableGestureManipulation())
this.doGestureTransformStep(e);
},
/** @ignore */
react_pinchend: function(e)
{
if (this.getEnableGestureManipulation())
this.endGestureTransform();
},
/** @ignore */
react_pinchcancel: function(e)
{
if (this.getEnableGestureManipulation())
this.endGestureTransform();
}
});
/**
* Enumeration of state of a {@link Kekule.Editor.BasicManipulationIaController}.
* @class
*/
Kekule.Editor.BasicManipulationIaController.State = {
/** Normal state. */
NORMAL: 0,
/** Is selecting objects. */
SELECTING: 1,
/** Is manipulating objects (e.g. changing object position). */
MANIPULATING: 2,
/**
* The pointer is down, but need to wait to determinate if there will be a gesture event.
*/
WAITING: 10,
/**
* Just put down pointer, if move the pointer immediately, selecting state will be open.
* But if hold down still for a while, it may turn to manipulating state to move current selected objects.
*/
SUSPENDING: 11
};
/**
* Enumeration of manipulation types of a {@link Kekule.Editor.BasicManipulationIaController}.
* @class
*/
Kekule.Editor.BasicManipulationIaController.ManipulationType = {
MOVE: 0,
ROTATE: 1,
RESIZE: 2,
TRANSFORM: 4 // scale and rotate simultaneously by touch
};
/** @ignore */
Kekule.Editor.IaControllerManager.register(Kekule.Editor.BasicManipulationIaController, Kekule.Editor.BaseEditor);
})(); |
// @flow
import type { ConfigSparseWithSource } from '../../';
import configResolve from '../';
type Fixture = {
name: string,
in: ConfigSparseWithSource,
};
const fixtures: Fixture[] = [
{
name: '01 empty input config',
in: {},
},
{
name: '02 empty input config with configFile',
in: {
configFile: '/foo/bar/package.json',
},
},
{
name: '03 empty input config with rootDir',
in: {
rootDir: '/foo/bar',
},
},
{
name: '04 empty input config with both configFile and rootDir',
in: {
configFile: '/a/b/c/package.json',
rootDir: '/foo/bar',
},
},
];
describe('lib/config/resolve', () => {
fixtures.forEach((fixture) => {
it(fixture.name, () => {
const received = configResolve(fixture.in);
expect(received).toMatchSnapshot();
});
});
});
|
var sys = require('pex-sys');
var glu = require('pex-glu');
var geom = require('pex-geom');
var gen = require('pex-gen');
var materials = require('pex-materials');
var color = require('pex-color');
var gui = require('pex-gui');
var Cube = gen.Cube;
var Sphere = gen.Sphere;
var Mesh = glu.Mesh;
var TexturedCubeMap = materials.TexturedCubeMap;
var SkyBox = materials.SkyBox;
var PerspectiveCamera = glu.PerspectiveCamera;
var Arcball = glu.Arcball;
var Color = color.Color;
var TextureCube = glu.TextureCube;
var GUI = gui.GUI;
sys.Window.create({
settings: {
width: 1280,
height: 720,
type: '3d',
fullscreen: sys.Platform.isBrowser
},
lod: 4,
init: function() {
this.gui = new GUI(this);
this.gui.addParam('Mipmap level', this, 'lod', { min: 0, max: 8, step: 1 });
var levels = ['m00'];
var sides = ['c00', 'c01', 'c02', 'c03', 'c04', 'c05'];
var cubeMapFiles = [];
levels.forEach(function(level) {
sides.forEach(function(side) {
cubeMapFiles.push('../../assets/cubemaps/uffizi_lod/uffizi_' + level + '_' + side + '.png');
});
});
var cubeMap = TextureCube.load(cubeMapFiles, { mipmap: true });
this.mesh = new Mesh(new Sphere(), new TexturedCubeMap({ texture: cubeMap }));
this.cubeMesh = new Mesh(new Cube(50), new SkyBox({ texture: cubeMap }));
this.camera = new PerspectiveCamera(60, this.width / this.height);
this.arcball = new Arcball(this, this.camera);
},
draw: function() {
if (!this.mesh.material.uniforms.texture.ready) return;
glu.clearColorAndDepth(Color.Black);
glu.enableDepthReadAndWrite(true);
this.cubeMesh.material.uniforms.lod = this.lod;
this.cubeMesh.draw(this.camera);
this.mesh.draw(this.camera);
this.mesh.material.uniforms.lod = this.lod;
this.gui.draw();
}
}); |
// namespace line first
import * as XA from "X";
import XD, { X2 } from "X";
import { X3 } from "X";
|
'use strict';
//
// Third party modules.
//
module.exports = require('canihaz')({
location: __dirname,
dot: 'smithy'
});
|
import path from 'path'
import inquirer from 'inquirer'
import downloadTwitterPhoto from './utils/download-twitter-photo'
inquirer.prompt([
{
name: 'twitter',
type: 'input',
message: 'Twitter handle?',
},
]).then(({twitter}) => {
const destinationPath = path.join(process.cwd(), 'data/contributors')
downloadTwitterPhoto(twitter, destinationPath)
})
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
// =====================================================================
// Non $scope member
// =====================================================================
var init = function() {
$scope.authentication = Authentication;
};
init();
var redirectToHome = function(user) {
var location = '/';
if(user.roles.indexOf('admin') !== -1) {
location = '/admin/home';
} else if(user.roles.indexOf('ero') !== -1) {
location = '/ero/home';
} else if(user.roles.indexOf('resource') !== -1) {
location = '/resource/home';
}
$location.path(location);
};
if ($scope.authentication.user) {
redirectToHome($scope.authentication.user);
}
// =====================================================================
// $scope Member
// =====================================================================
$scope.prepare = function() {
$scope.credentials = {
email: null,
password: null
};
};
$scope.signin = function() {
$scope.authenticationPromise = $http.post('/api/auth/signin', $scope.credentials).success(function(response) {
$scope.authentication.user = response;
redirectToHome($scope.authentication.user);
}).error(function(response) {
$scope.error = response.message;
});
};
// =====================================================================
// Event listener
// =====================================================================
}
]);
|
import React, { useCallback, useState } from 'react';
import { css } from 'emotion';
import { Button, Col, Input, Row } from 'reactstrap';
import Localized from 'components/Localized/Localized';
import LocationsCount from 'components/LocationsCount/LocationsCount';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { GoX } from 'react-icons/go';
import { useSelectAll } from 'selectors/selectAll';
import { logEvent } from 'utils/analytics';
import DefaultLocationsList from './DefaultLocationsList';
import CustomLocationsList from './CustomLocationsList';
import FilteredLocationsList from './FilteredLocationsList';
import ExportLocations from './ExportLocations';
import DownloadLocations from './DownloadLocations';
export const Settings = () => {
const [t] = useTranslation();
const [filter, setFilter] = useState('');
const { selectAllLocations, deselectAllLocations } = useSelectAll();
const onFilterChange = useCallback((event) => {
logEvent('LOCATIONS_FILTER');
setFilter(event.target.value);
}, []);
const onClearFilter = useCallback(() => {
logEvent('LOCATIONS_FILTER_CLEAR');
setFilter('');
}, []);
return (
<Row className={`${styles.container} justify-content-center`}>
<Col xs={12} md={10}>
<Row className={styles.locationsContainer}>
<Col className="text-center">
<h4><Localized name="interface.game_locations" /> (<LocationsCount />)</h4>
</Col>
</Row>
<Row className={`${styles.filterContainer} justify-content-center`}>
<Col className="text-center">
<Input placeholder={t('interface.filter')} value={filter} onChange={onFilterChange} />
{!!filter && <GoX className={`${styles.clearFilter} text-dark`} onClick={onClearFilter} />}
</Col>
</Row>
{!filter && (
<>
<DefaultLocationsList version={1} onSelectAll={selectAllLocations} onDeselectAll={deselectAllLocations} />
<DefaultLocationsList version={2} onSelectAll={selectAllLocations} onDeselectAll={deselectAllLocations} />
<CustomLocationsList onSelectAll={selectAllLocations} onDeselectAll={deselectAllLocations} />
</>
)}
{!!filter && <FilteredLocationsList filter={filter} />}
<ExportLocations />
<DownloadLocations />
<Row className={`${styles.backContainer} justify-content-center`}>
<Col xs={12} className="text-center">
<Link className={styles.backLink} to="/">
<Button color="danger" block><Localized name="interface.back_to_game" /></Button>
</Link>
</Col>
</Row>
</Col>
</Row>
);
};
const styles = {
container: css({
marginBottom: 50,
}),
locationsContainer: css({
marginTop: 20,
}),
filterContainer: css({
marginTop: 20,
}),
backContainer: css({
marginTop: 20,
}),
backLink: css({
textDecoration: 'none',
':hover': {
textDecoration: 'none',
},
}),
clearFilter: css({
position: 'absolute',
right: 25,
top: 8,
fontSize: 22,
cursor: 'pointer',
}),
};
export default React.memo(Settings);
|
import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
height: 100%;
`;
export const EditorContainer = styled.div`
${''/* padding: 30px 30px; */}
width: 100%;
box-sizing: border-box;
position: relative;
font-family: 'Proxima-Nova', 'helvetica', 'arial';
box-sizing: border-box;
font-size: 21px;
color: #131517;
font-weight: 300;
line-height: 1.54;
& h1 {
font-size: 48px;
font-weight: bold;
letter-spacing: -.024em;
line-height: 1.18;
margin-bottom: 20px;
color: #131517;
}
& h2 {
font-size: 28px;
font-weight: normal;
letter-spacing: -.008em;
line-height: 1.24;
margin-bottom: 20px;
color: #797C80;
}
& ul {
padding-left: 24px;
${''/* list-style: none; */}
}
& ol {
padding-left: 24px;
${''/* list-style: none; */}
}
& li {
font-size: 21px;
line-height: 1,78;
}::selection {
background-color: #B1DFCB;
}
`;
|
/*globals rabbitmq_test_bindings: false,
rabbitmq_bindings_to_remove: false */
/*jslint mocha: true */
"use strict";
var expect = require('chai').expect,
util = require('util'),
Qlobber = require('..').Qlobber;
function QlobberTopicCount (options)
{
Qlobber.call(this, options);
this.topic_count = 0;
}
util.inherits(QlobberTopicCount, Qlobber);
QlobberTopicCount.prototype._initial_value = function (val)
{
this.topic_count += 1;
return Qlobber.prototype._initial_value(val);
};
QlobberTopicCount.prototype._remove_value = function (vals, val)
{
var removed = Qlobber.prototype._remove_value(vals, val);
if (removed)
{
this.topic_count -= 1;
}
return removed;
};
QlobberTopicCount.prototype.clear = function ()
{
this.topic_count = 0;
return Qlobber.prototype.clear.call(this);
};
describe('qlobber-topic-count', function ()
{
it('should be able to count topics added', function ()
{
var matcher = new QlobberTopicCount();
rabbitmq_test_bindings.forEach(function (topic_val)
{
matcher.add(topic_val[0], topic_val[1]);
});
expect(matcher.topic_count).to.equal(25);
rabbitmq_bindings_to_remove.forEach(function (i)
{
matcher.remove(rabbitmq_test_bindings[i-1][0],
rabbitmq_test_bindings[i-1][1]);
});
expect(matcher.topic_count).to.equal(21);
matcher.clear();
expect(matcher.topic_count).to.equal(0);
expect(matcher.match('a.b.c').length).to.equal(0);
});
it('should not decrement count if entry does not exist', function ()
{
var matcher = new QlobberTopicCount();
expect(matcher.topic_count).to.equal(0);
matcher.add('foo.bar', 23);
expect(matcher.topic_count).to.equal(1);
matcher.remove('foo.bar', 24);
expect(matcher.topic_count).to.equal(1);
matcher.remove('foo.bar2', 23);
expect(matcher.topic_count).to.equal(1);
matcher.remove('foo.bar', 23);
expect(matcher.topic_count).to.equal(0);
matcher.remove('foo.bar', 24);
expect(matcher.topic_count).to.equal(0);
matcher.remove('foo.bar2', 23);
expect(matcher.topic_count).to.equal(0);
});
});
|
'use strict';
/* eslint-disable no-console */
const cryptoJS = require('crypto-js');
module.exports = {
toJsonObj: function (str) {
try {
return JSON.parse(str);
} catch (e) {
return false;
}
},
getMacString: function (req) {
var arr = [];
for (let key in req) {
if (req.hasOwnProperty(key)) {
arr.push(key + '=' + req[key]);
}
}
arr.sort();
return arr.join(':');
},
calculateMac: function (macString, secret) {
return '1:' + cryptoJS.enc.Base64.stringify(cryptoJS.HmacSHA256(macString, secret));
},
encodeData: function (data) {
return Object.keys(data).map(function (key) {
return [key, data[key]].map(encodeURIComponent).join('=');
}).join('&');
}
}
|
/**
* download webdriver
*/
var path = require('path');
var fs = require('fs');
var rimraf = require('rimraf');
var Download = require('download');
var Decompress = require('decompress');
var fse = require('fs-extra');
var debug = require('debug')('browser');
var chromeVersion = '2.20';
var phantomVersion = '1.9.7';
var basePath = 'https://npm.taobao.org/mirrors/';
var driversDest = path.resolve(__dirname, './driver');
/**
* 下载对应平台的 driver
*/
function downloadDrivers() {
var driversConfig = {
darwin: [
{name: 'phantomjs-darwin', url: 'phantomjs/phantomjs-' + phantomVersion + '-macosx.zip'},
{name: 'chromedriver-darwin', url: 'chromedriver/' + chromeVersion + '/chromedriver_mac32.zip'}
],
win32: [
{name: 'chromedriver.exe', url: 'chromedriver/' + chromeVersion + '/chromedriver_win32.zip'},
{name: 'phantomjs.exe', url: 'phantomjs/phantomjs-' + phantomVersion + '-windows.zip'}
],
linux: [
{name: 'phantomjs-linux', url: 'phantomjs/phantomjs-' + phantomVersion + '-linux-x86_64.tar.bz2'}
]
};
var driverConfig = driversConfig[process.platform];
var count = 0;
console.log('load: download webDrivers...');
if (fs.existsSync(driversDest)) {
rimraf.sync(driversDest);
}
fs.mkdirSync(driversDest);
driverConfig.forEach(function(item) {
var download = new Download({
mode: '777'
// 取不出 tar
// extract: true
});
debug('download', item);
download
.get(basePath + item.url)
// .rename(item.name)
.dest(path.resolve(__dirname, './driver/'))
.run(function(err, files) {
if (err) {
throw new Error('Download drivers error, please reinstall ' + err.message);
}
var downloadFilePath = files[0].path;
var compressDir = path.resolve(driversDest, './' + item.name + '-dir');
debug('下载完一个文件:', downloadFilePath, '开始压缩:');
new Decompress({mode: '777'})
.src(downloadFilePath)
.dest(compressDir)
.use(Decompress.zip({strip: 1}))
.run(function(err) {
if (err) {
throw err;
}
debug('压缩完一个文件');
var type = /phantom/.test(item.name) ? 'phantomjs' : 'chromedriver';
reworkDest(downloadFilePath, compressDir, type);
debug('更改文件权限');
fs.chmodSync(path.resolve(driversDest, item.name), '777');
count ++;
if (count >= driverConfig.length) {
console.log('Download drivers successfully.');
}
});
});
});
}
/**
* 解压之后对文件夹重新整理
*/
function reworkDest(downloadFilePath, compressDir, type) {
// 清理下载的压缩文件
fse.removeSync(downloadFilePath);
var binName = type + (process.platform === 'win32' ? '.exe' : '-' + process.platform);
var binSrcPath = path.resolve(compressDir, type === 'phantomjs' ? './bin/phantomjs' : './chromedriver');
var binDestPath = path.resolve(driversDest, binName);
debug('复制 bin 文件:', binSrcPath, binDestPath);
fse.copySync(binSrcPath, binDestPath);
debug('移除源的文件夹');
fse.removeSync(compressDir);
}
downloadDrivers(); |
import { combineReducers } from 'redux';
import PostsReducer from './reducer-posts';
import { reducer as formReducer } from 'redux-form';
const rootReducer = combineReducers({
posts: PostsReducer,
form: formReducer
});
export default rootReducer;
|
(function(){
var app = angular.module('howtoApp', []);
/*TODO - add custom filters
https://scotch.io/tutorials/building-custom-angularjs-filters
*/
app.filter('facetedNavFilter', function() {
return function(input,scope) {
/*console.log(scope);
var out = [];
var tmpArr = [];
var isEmptyFilterNav = true;
angular.forEach(scope.tmpListing, function(howto) {
angular.forEach(howto.metaData, function(metaRaw){
angular.forEach(metaArr,function(meta){
angular.forEach(tmpArr,function(el){
if(el!==meta){
tmpArr.push(meta);
isEmptyFilterNav = false;
}
});
});
});
});
if(!isEmptyFilterNav){
angular.forEach(input, function(facetCollection){
angular.forEach(facetCollection.categories, function(facetCat){
angular.forEach(facetCat.values, function(facet){
//console.log(facet);
});
});
});
return out;
}else{
return input;
}*/
return input;
}
});
app.filter('facetFilterListings', function() {
return function(input,scope) {
//scope.tmpListing = [];
/*var out = [];
var facetSelectionArr = scope.facetSelectionArr;
angular.forEach(input, function(howto) {
if(facetSelectionArr.length > 0){
var addToOut = false;
angular.forEach(howto.metaData, function(metaRaw){
metaArr = metaRaw.split(",");
angular.forEach(metaArr,function(meta){
angular.forEach(facetSelectionArr,function(facet){
if(facet === meta){
addToOut = true;
}
});
});
});
if(!addToOut){
out.push(howto);
}
}else{
out.push(howto);
}
});
console.log($scope);
return out;*/
return input;
}
});
app.controller('howToController', ['$scope','$filter','$http',function($scope,$filter,$http){
$scope.orderBy = $filter('orderBy');
$scope.callbackName = 'fbcallback';
$scope.defaultQry = "!padrenullquery";
$scope.query = {};
$scope.angularCallback = "&callback=JSON_CALLBACK";
$scope.minInputToSearch = 3;
$scope.numRanks = 10;
$scope.currentPage = 1;
$scope.facetSelectionArr = [];
$scope.xhrSource = "search.json?1";
//$scope.xhrSource = "//funnelback-dev.ucl.ac.uk/s/search.json?collection=isd-howto&profile=_default_preview&num_ranks=1000";
$scope.log = function(){
console.log($scope.resultModel);
}
$scope.fbEncodeURI = function(str){
var str = encodeURI(str);
//return 'hello world';
return str.replace('+','%20').replace('%257C','%7C');//convert fb use of + and | char
}
$scope.loadResultsTmp = function(){
return 'js/includes/listings.html';
}
$scope.loadFacetsTmp = function(){
return 'js/includes/facets.html';
}
$scope.loadPaginationTmp = function(){
return 'js/includes/pagination.html';
}
$scope.removeFacet = function(arr,el){
var pos = arr.indexOf(el);
if(pos >= 0){
arr.splice(pos,1);//second arg ensures 1 item is removed from array
}
return arr;
}
$scope.filterFacets = function(currentElQry,currentElLabel){
var isSelected = false;
if($scope.facetSelectionArr){
for(var i in $scope.facetSelectionArr){
var tmpSelectedItem = $scope.facetSelectionArr[i]
if(tmpSelectedItem == currentElLabel){
isSelected = true;
$scope.facetSelectionArr = $scope.removeFacet($scope.facetSelectionArr,currentElLabel);
}
if(isSelected == true)break;
}
if(isSelected == false){
$scope.facetSelectionArr.push(currentElLabel);
}
}
//$scope.filterListings();
}
$scope.updateMeta = function(){
console.log($filter);
}
$scope.isInputChecked = function(el){
var isChecked = false;
var facets = $scope.xhrDataSelectedFacets;
for(var i in facets){
var tmpArr = facets[i];
for(var j in tmpArr){
var tmpQry = encodeURI(i + '=' + tmpArr[j]);
if($scope.fbEncodeURI(el) === tmpQry)
isChecked = true;
}
}
return isChecked;
}
$scope.facetHasCount = function(el){
//console.log($scope.listingModel);
if($scope.getCount(el) > 0){
return true;
}else{
return false;
}
}
$scope.getCount = function(el){
var count = 0;
angular.forEach($scope.xhrDataResults,function(result){
angular.forEach(result.metaData,function(metaArr){
metaArr = metaArr.split(",");
angular.forEach(metaArr,function(meta){
if(el==meta){
count+=1;
}
});
});
});
return count;
}
$scope.showFacetCount = function(facetObj){
var showFacet = false;
var tmpCount = 0;
if(typeof facetObj.categories[0] !== 'undefined'){
for(var i in facetObj.categories[0].values){
var facet = facetObj.categories[0].values[i];
tmpCount += parseInt(facet.count);
}
}
if(tmpCount > 0)showFacet = true;
return showFacet;
}
$scope.updatePage = function(x) {
$scope.currentPage = x;
return;
}
$scope.isCurrentPage = function(x) {
if(x === $scope.currentPage) {
return true;
}else{
return false;
}
}
$scope.showListing = function(x) {
var rankStart = $scope.currentPage * $scope.numRanks;
var rankEnd = ($scope.currentPage + 1) * $scope.numRanks;
if(x >= rankStart && x < rankEnd) {
return true;
}else{
return false;
}
}
$scope.getData = function(){
var requestUrl = $scope.xhrSource + "&query=" + $scope.defaultQry + $scope.angularCallback;
$http.jsonp(requestUrl).success(function(data) {
$scope.data = data;//make available to $scope variable
//$scope.xhrDataResults = $scope.orderBy(data.response.resultPacket.results,'title',$scope.direction);
$scope.xhrDataResults = data.response.resultPacket.results;
$scope.xhrDataFacets = $scope.orderBy(data.response.facets,'title',$scope.direction);
$scope.xhrDataSelectedFacets = data.question.selectedCategoryValues;
$scope.totalPages = Math.ceil(data.response.resultPacket.resultsSummary.fullyMatching/$scope.numRanks);
$scope.paginationArr = [];
var i=1;
for(i=1;i<=$scope.totalPages;i++){
$scope.paginationArr.push(i);
}
});
}
$scope.getData();
}]);
})();
|
describe("Test", function () {
function testRegex(regexText, text, expectedResult, allTextMatched = true) {
let textArray;
if (Array.isArray(text)) {
textArray = text;
} else {
textArray = [text];
}
const regex = parser.compile(regexText);
textArray.forEach(function (txt) {
const match = regex.match(txt);
expect( allTextMatched ? match.matches : match.allMatchersMatched).toBe(expectedResult);
});
}
describe("Start End", function () {
describe("Matches", function () {
it("Both", function () {
testRegex('^ab$', ['ab'], true);
});
it("Start", function () {
testRegex('^ab', ['ab', 'abc'], true, false);
});
it("End", function () {
testRegex('ab$', ['ab'], true);
testRegex('.*ab$', ['cab'], true);
});
});
describe("Mismatches", function () {
it("Both", function () {
testRegex('^ab$', ['a', 'b', 'ac', 'd'], false);
});
it("Start", function () {
testRegex('^ab', ['a', 'b', 'ac', 'bc'], false);
});
it("End", function () {
testRegex('ab$', ['acb', 'a', 'ba'], false);
testRegex('.*ab$', ['caxb'], false);
});
});
});
describe("Literals", function () {
describe("Matches", function () {
it("empty string", function () {
testRegex('', '', true);
});
it("single character", function () {
testRegex('a', 'a', true);
});
it("multiple characters", function () {
testRegex('abc', 'abc', true);
});
});
describe("Mismatches", function () {
it("empty string", function () {
testRegex('', 'a', false);
});
it("single character", function () {
testRegex('a', ['x', '', 'aa'], false);
});
it("multiple characters", function () {
testRegex('abc', ['abcd', 'ab', 'Abc'], false);
testRegex('zabc', 'abc', false);
});
});
});
describe("Dot", function () {
describe("Matches", function () {
it("single dot", function () {
testRegex('.', ['a', '.'], true);
testRegex('a.', 'ax', true);
testRegex('.b', 'xb', true);
});
it("multiple dots", function () {
testRegex('..', 'ab', true);
testRegex('.x.x.', 'xxxxx', true);
});
});
describe("Mismatches", function () {
it("single dot", function () {
testRegex('.', '', false);
testRegex('a.', 'a', false);
testRegex('.a', 'a', false);
});
it("multiple dots", function () {
testRegex('..', 'abc', false);
testRegex('a.b.c', 'abc', false);
});
});
});
describe("Inclusive Character Specifications", function () {
describe("Matches", function () {
it("literals", function () {
testRegex('[a]', 'a', true);
testRegex('[aaa]', 'a', true);
testRegex('[abc]', ['a', 'b', 'c'], true);
});
it("ranges", function () {
testRegex('[a-a]', 'a', true);
testRegex('[a-b]', 'a', true);
testRegex('[a-b]', 'b', true);
testRegex('[a-z]', 'q', true);
testRegex('[a-cx-z]', ['a', 'b', 'c', 'x', 'y', 'z'], true);
});
it("combinations", function () {
testRegex('[ag-imv-xz]', ['a', 'g', 'h', 'i', 'm', 'v', 'w', 'x', 'z'], true);
});
it("multiples", function () {
testRegex('[a]b[c-f]', ['abc', 'abd', 'abe', 'abf'], true);
});
it("meta-characters", function () {
testRegex('[-+]', ['+', '-'], true);
testRegex('[\-\+\\\\]', ['+', '-','\\'], true);
});
});
describe("Mismatches", function () {
it("literals", function () {
testRegex('[a]', 'b', false);
testRegex('[aaa]', 'b', false);
testRegex('[abc]', 'd', false);
});
it("ranges", function () {
testRegex('[a-a]', 'b', false);
testRegex('[a-b]', 'B', false);
testRegex('[a-cx-z]', 'd', false);
});
it("combinations", function () {
testRegex('[ag-imv-xz]', ['b', 'f', 'j', 'l', 'n', 'u', 'y'], false);
});
});
});
describe("Exclusive Character Specifications", function () {
describe("Matches", function () {
it("literals", function () {
testRegex('[^a]', 'b', true);
testRegex('[^aaa]', 'b', true);
testRegex('[^abc]', 'd', true);
});
it("ranges", function () {
testRegex('[^a-a]', 'b', true);
testRegex('[^a-b]', 'B', true);
testRegex('[^a-cx-z]', 'd', true);
});
it("combinations", function () {
testRegex('[^ag-imv-xz]', ['b', 'f', 'j', 'l', 'n', 'u', 'y'], true);
});
});
describe("Mismatches", function () {
it("literals", function () {
testRegex('[^a]', 'a', false);
testRegex('[^aaa]', 'a', false);
testRegex('[^abc]', ['a', 'b', 'c'], false);
});
it("ranges", function () {
testRegex('[^a-a]', 'a', false);
testRegex('[^a-b]', 'a', false);
testRegex('[^a-b]', 'b', false);
testRegex('[^a-z]', 'q', false);
testRegex('[^a-cx-z]', ['a', 'b', 'c', 'x', 'y', 'z'], false);
});
it("combinations", function () {
testRegex('[^ag-imv-xz]', ['a', 'g', 'h', 'i', 'm', 'v', 'w', 'x', 'z'], false);
});
it("multiples", function () {
testRegex('[^a]b[c-f]', ['abc', 'abd', 'abe', 'abf'], false);
testRegex('[a]b[^c-f]', ['abc', 'abd', 'abe', 'abf'], false);
});
});
});
describe("test", function() {
it("Matches", function () {
testRegex('[a-c]*', '', true);
})
})
describe("Exact Number Of", function () {
it("Matches", function () {
testRegex('a{0}', '', true);
testRegex('a{1}', 'a', true);
testRegex('a{3}', 'aaa', true);
testRegex('.{2}', 'ab', true);
testRegex('[abc]{2}', ['aa', 'bc', 'cc'], true);
});
it("Mismatches", function () {
testRegex('a{0}', 'a', false);
testRegex('a{1}', ['', 'aa', 'b', 'ab', 'ba'], false);
testRegex('a{3}', ['', 'a', 'aa', 'aaaa', 'aba'], false);
testRegex('.{2}', 'abc', false);
testRegex('.{2}', 'a', false);
testRegex('[abc]{2}', 'ad', false);
});
});
describe("Number Range Of", function () {
it("Matches", function () {
testRegex('a{0,0}', '', true);
testRegex('.{3,3}', 'abc', true);
testRegex('a{0,2}', '', true);
testRegex('[abc]{2,5}', ['ab', 'cca', 'abca', 'cccca'], true);
});
it("Mismatches", function () {
testRegex('a{0,0}', 'a', false);
testRegex('.{3,3}', ['ab', 'aaaa'], false);
testRegex('a{0,2}', 'aaa', false);
testRegex('[abc]{2,5}', ['a', 'aaabbb', 'ax', 'xbc'], false);
});
});
describe("Number Or More Of", function () {
it("Matches", function () {
testRegex('a{0,}', ['', 'a', 'aaa'], true);
testRegex('a{1,}', ['a', 'aa'], true);
testRegex('a{3,}', ['aaa', 'aaaaaaaa'], true);
testRegex('.{2,}', ['ab', 'xx', 'abc'], true);
testRegex('[abc]{2,}', ['aa', 'bc', 'cc', 'aaa', 'bbcc'], true);
});
it("Mismatches", function () {
testRegex('a{1,}', ['', 'b', 'ab', 'ba'], false);
testRegex('a{3,}', ['', 'a', 'aa', 'aab', 'baaa'], false);
testRegex('.{2,}', ['', 'a'], false);
testRegex('[abc]{2,}', ['a', 'ad', 'dabc'], false);
});
});
describe("Zero Or More", function () {
it("Matches", function () {
testRegex('a*', ['', 'a', 'aa', 'aaa'], true);
testRegex('[a-c]*', ['', 'a', 'b', 'c', 'ab', 'ccc', 'bcabca'], true);
});
it("Mismatches", function () {
testRegex('a*', ['b', 'aaab', 'baaa'], false);
testRegex('[a-c]*', ['d', 'abcd'], false);
});
});
describe("One Or More", function () {
it("Matches", function () {
testRegex('a+', ['a', 'aa', 'aaa'], true);
testRegex('[a-c]+', ['a', 'b', 'c', 'ab', 'ccc', 'bcabca'], true);
});
it("Mismatches", function () {
testRegex('a+', ['', 'aab', 'aabaa'], false);
testRegex('[a-c]+', ['', 'd', 'aaad', 'bcadbca'], false);
});
});
describe("Zero Or One", function () {
it("Matches", function () {
testRegex('a?', ['', 'a'], true);
testRegex('[a-c]?', ['', 'a', 'b', 'c'], true);
});
it("Mismatches", function () {
testRegex('a?', ['b', 'aa'], false);
testRegex('[a-c]?', ['d', 'aa', 'abc'], false);
});
});
describe("Combinations", function () {
it("Matches", function () {
testRegex('a[b-d]{3,5}e{2,}f?g*h+', ['abcdeefgh', 'abbbbbeeeeeh', 'adddeefgggghhhh'], true);
});
it("Mismatches", function () {
testRegex('a[b-d]{3,5}e{2,}f?g*h+', ['bbbeefgh', 'abbeeh', 'abbbeh', 'abcdeef'], false);
});
});
describe("Alternatives", function () {
it("Matches", function () {
testRegex('a|b', ['a', 'b'], true);
testRegex('a||b', ['', 'a', 'b'], true);
testRegex('a+|b+', ['a', 'aaa', 'b', 'bb'], true);
testRegex('a*|b*|c*', ['', 'a', 'aaa', 'b', 'bb', 'c', 'cccc'], true);
});
it("Mismatches", function () {
testRegex('a|b', ['', 'c', 'aa', 'ab'], false);
});
});
describe("Brackets", function () {
it("Matches", function () {
testRegex('(a)', 'a', true);
testRegex('(ab)*', ['', 'ab', 'ababab'], true);
testRegex('(ab|cd)*', ['', 'ab', 'ababab', 'cd', 'cdcd', 'abcdababcdab'], true);
testRegex('(ab(c|d)+e)*', ['abce', 'abde', 'abcde', 'abccddcce'], true);
});
it("Mismatches", function () {
testRegex('(a)', ['', 'aa', 'b', '(a)'], false);
testRegex('(ab)*', ['a', 'b', 'aba', 'abbb'], false);
testRegex('(ab|cd)*', ['a', 'b', 'c', 'd', 'ac', 'abd'], false);
testRegex('(ab(c|d)+e)*', ['abe', 'abcd'], false);
});
});
describe("Capturing Groups", function () {
it("Matches", function () {
testRegex('(a)=\\1', 'a=a', true);
testRegex('(a)\\1\\1b', 'aaab', true);
testRegex('(a)(b)(c) \\1\\2\\3', 'abc abc', true);
testRegex('(a)(b)(c) \\3\\2\\1', 'abc cba', true);
testRegex('(a|b)\\1', ['aa', 'bb'], true);
testRegex('(.)\\1', ['aa', 'bb', 'cc'], true);
testRegex('(a*)\\1', ['', 'aa', 'aaaa'], true);
testRegex('(a+)\\1', ['aa', 'aaaa'], true);
testRegex('(A+) (B+) \\1 \\2', ['A B A B', 'AAA BB AAA BB'], true);
});
it("Mismatches", function () {
testRegex('(a)\\1', ['', 'ab', 'a', 'a\\1', 'aaa'], false);
testRegex('(a|b)\\1', ['ab', 'ba'], false);
testRegex('(.)\\1', ['', 'a'], false);
testRegex('(a*)\\1', ['a', 'aaa', 'aaaaa'], false);
testRegex('(a+)\\1', ['', 'a', 'aaa'], false);
testRegex('(A+) (B+) \\1 \\2', ['A B AA B', 'AAA BB AAA B'], false);
});
});
describe("Whitespace", function () {
it("Matches", function () {
testRegex('\\s', ' ', true);
testRegex('\\s+', ' \t\r\n\f', true);
testRegex('\\s*', '', true);
});
it("Mismatches", function () {
testRegex('\\s', ['', 'a', '\\s', ' '], false);
});
});
describe("Non-Whitespace", function () {
it("Matches", function () {
testRegex('\\S', 'a', true);
});
it("Mismatches", function () {
testRegex('\\S', [' ', '\n', '\t', '\r', '\f'], false);
});
});
describe("Digit Alias", function () {
it("Matches", function () {
testRegex('\\d', ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], true);
});
it("Mismatches", function () {
testRegex('\\d', ['00', 'a', '.', ' '], false);
});
});
describe("Non-Digit Alias", function () {
it("Matches", function () {
testRegex('\\D', ['a', '.', ' '], true);
});
it("Mismatches", function () {
testRegex('\\D', ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], false);
});
});
function expectError(regexText, consumed){
expect(function(){
parser.compile(regexText)
}).toThrow('Unable to parse regex, consumed "' + consumed + '"')
}
describe("Invalid Regexes", function(){
it("Throw Errors", function(){
expectError('*', '');
expectError('abc[]', 'abc');
expectError('abc[xyz', 'abc');
expectError('+++', '');
expectError('a(', 'a');
expectError('abc[^]', 'abc');
expectError('a{z}', 'a');
expectError('a{1,x}', 'a');
})
});
});
|
__d("UPoCs",function(o,e,s){s.exports="Here is brisk demo!"}); |
var icons = [
'moneybag',
'save',
'establishment',
'completion',
'share',
'no_money',
'euro',
'palette',
'puzzle',
'backward',
'partial',
'minimize',
'tick',
'tick_thin',
'tick_bold',
'compass',
'minus',
'supplies',
'alarm',
'analytics',
'charts',
'apps',
'nine_tiles',
'archive',
'arrow_double',
'forward',
'arrow_east',
'east_arrow',
'east_thin_arrow',
'chevron_east',
'arrow_full_east',
'arrow_full_north',
'arrow_full_south',
'arrow_full_west',
'arrow_north',
'north_arrow',
'north_thin_arrow',
'chevron_north',
'arrow_south',
'south_arrow',
'south_thin_arrow',
'chevron_south',
'arrow_west',
'west_arrow',
'west_thin_arrow',
'chevron_west',
'priority_lowest',
'priority_highest',
'answer',
'api_sync',
'attach',
'banking_card',
'bill',
'birthday',
'book',
'branch',
'breakfast',
'broken_heart',
'build',
'bus',
'calendar',
'calendar_off',
'planning',
'calendar_checked',
'camera',
'car',
'certif_ok',
'certif_ko',
'certif_waiting',
'chat',
'talk',
'messenger',
'dialog',
'chrono_on',
'clean_car',
'clock',
'close',
'thin_cross',
'cross',
'cross_bold',
'coffee',
'breakTime',
'collapse',
'computer',
'computer_mouse',
'contract',
'copy',
'credit_debit',
'cut',
'dashboard',
'database',
'diner',
'discount',
'distribute',
'dollar',
'download',
'drag',
'drink',
'edit',
'edit_mini',
'edit_write',
'editFrame',
'equal',
'error',
'evolution',
'evolution_down',
'expand',
'family_tree',
'org_tree',
'file',
'file_export',
'file_import',
'import_dirty',
'import_pristine',
'filter',
'filter_abstract',
'flag',
'folder',
'forbidden',
'format_bold',
'format_clear',
'format_italic',
'format_justify',
'format_link',
'format_list_nb',
'format_redo',
'format_size',
'format_strikethrough',
'format_underlined',
'format_undo',
'fullscreen',
'fullscreen_exit',
'gallery',
'gasoline',
'gift',
'present',
'heart',
'help',
'help_outline',
'history',
'home',
'hotel',
'image',
'import_cb',
'info',
'iron',
'journey',
'milestone',
'key',
'laptop',
'light_bulb',
'list',
'list_checked',
'list_todo',
'location',
'lock',
'login',
'logout',
'lucca',
'luggage',
'lunch',
'meal',
'lunch_alternative',
'mail',
'mailbox',
'stamp',
'postage',
'menu',
'hamburger_menu',
'menu_ellipsis',
'ellipsis',
'mileage',
'money',
'payment',
'notification',
'outside',
'overplanned',
'parking',
'paste',
'clipboard',
'piggy_bank',
'pause',
'pay_period',
'pin',
'plane',
'planning_edit',
'planning_manage',
'play',
'play_full',
'plus',
'plus_bold',
'postpone',
'pressing',
'pricetag',
'print',
'refresh',
'update',
'reply',
'restaurant',
'user_roles',
'rotate',
'rotate_right',
'school',
'search',
'send',
'send2User',
'settings',
'sign',
'sliders',
'snack',
'sort',
'reorder',
'star',
'stop',
'subway',
'success',
'sync',
'sync_disabled',
'table',
'target',
'taxi',
'telephone',
'test',
'timer',
'timesheet',
'thumb_down',
'thumb_up',
'thumbnail',
'toll',
'toll_dollar',
'toll_euro',
'tools',
'train',
'trash',
'truck',
'unlink',
'unlock',
'unstared',
'unwatch',
'upload',
'cloud_upload',
'user',
'face',
'user_add',
'addUser',
'user_file',
'dossier_rh',
'user_group',
'group',
'user_remove',
'wallet',
'warning',
'watch',
'weather_cloudy',
'weather_storm',
'weather_sun',
'weight',
'divide',
'crown',
'unarchive',
];
export default icons; |
import Ember from 'ember';
import moment from 'moment';
import dateFormat from '../utils/date-format';
export default Ember.Controller.extend({
loadingMeta: false,
notify: Ember.inject.service(),
aggController: Ember.inject.controller('discover.aggregate'),
queryParams: ['center', 'obs_date__le', 'obs_date__ge', 'agg', 'location_geom__within'],
obs_date__le: dateFormat(moment()),
obs_date__ge: dateFormat(moment().subtract(90, 'days')),
agg: 'week',
center: 'default',
location_geom__within: null,
_resetParams() {
this.set('obs_date__le', dateFormat(moment()));
this.set('obs_date__ge', dateFormat(moment().subtract(90, 'days')));
this.set('agg', 'week');
this.set('center', 'default');
this.set('location_geom__within', null);
},
queryParamsHash: Ember.computed('obs_date__le', 'obs_date__ge',
'agg', 'center', 'location_geom__within', function () {
return this.getProperties(this.get('queryParams'));
}),
queryParamsClone() {
return Ember.copy(this.get('queryParamsHash'));
},
// Central location to define all acceptable values for aggregate-query-maker
// IDs for cities, their display names, and bounds (usually city limits)
// City bounding boxes determined via https://www.mapdevelopers.com/geocode_bounding_box.php
cities: {
default: {
// "Cities" named "default" are not shown to the user
// This is a copy of Chicago
bounds: [
[42.023131, -87.940267], // NW corner
[41.644335, -87.523661], // SE corner
],
location: [41.795509, -87.581916],
zoom: 10,
},
chicago: {
label: 'Chicago, IL',
bounds: [
[42.023131, -87.940267], // NW corner
[41.644335, -87.523661], // SE corner
],
location: [41.795509, -87.581916],
zoom: 10,
},
newyork: {
label: 'New York, NY',
bounds: [
[40.917577, -74.259090], // NW corner
[40.477399, -73.700272], // SE corner
],
location: [40.7268362, -74.0017699],
zoom: 10,
},
seattle: {
label: 'Seattle, WA',
bounds: [
[47.734140, -122.459696],
[47.491912, -122.224433],
],
location: [47.6076397, -122.3258644],
zoom: 10,
},
sanfrancisco: {
label: 'San Francisco, CA',
bounds: [
[37.929820, -123.173825], // NW corner (yes, the city limits DO include those tiny islands)
[37.639830, -122.281780], // SE corner
],
location: [37.7618864, -122.4406926],
zoom: 12,
},
austin: {
label: 'Austin, TX',
bounds: [
[30.516863, -97.938383], // NW corner
[30.098659, -97.568420], // SE corner
],
location: [30.3075693, -97.7399898],
zoom: 10,
},
denver: {
label: 'Denver, CO',
bounds: [
[39.914247, -105.109927], // NW corner
[39.614430, -104.600296], // SE corner
],
location: [39.7534338, -104.890141],
zoom: 11,
},
bristol: {
label: 'Bristol, England, UK',
bounds: [
[51.544433, -2.730516], // NW corner
[51.392545, -2.450902], // SE corner
],
location: [51.4590572, -2.5909956],
zoom: 11,
},
atlanta: {
label: 'Atlanta, GA',
bounds: [
[33.647808, -84.551819],
[33.887618, -84.2891076],
],
location: [33.748998, -84.388113],
zoom: 10,
},
},
aggOptions: ([
{ id: 'day', label: 'day' },
{ id: 'week', label: 'week' },
{ id: 'month', label: 'month' },
{ id: 'quarter', label: 'quarter' },
{ id: 'year', label: 'year' },
]),
resOptions: ([
{ id: '100', label: '100 meters' },
{ id: '200', label: '200 meters' },
{ id: '300', label: '300 meters' },
{ id: '400', label: '400 meters' },
{ id: '500', label: '500 meters' },
{ id: '1000', label: '1 kilometer' },
]),
// ------------- end of central aggregate-query-maker values ---------------//
// _zoomIn() {
// this.set('zoom', true);
// const self = this;
// Ember.run.next(() => {
// self.set('zoom', false);
// });
// },
_resetDatePickers() {
this.set('override', true);
Ember.run.next(() => {
this.set('override', false);
});
},
_inIndex() {
// Thanks: https://gist.github.com/eliotsykes/8954cf64fcd0df16f519
return Ember.getOwner(this).lookup('controller:application').currentPath === 'discover.index';
},
actions: {
submit() {
if (this.get('submitCooldown')) {
this.get('notify').info('Cooldown active. Please wait a few seconds between query submissions.');
return;
}
// Implement a cooldown on the submit button to
// prevent double-clicks from reloading the query
// before a new one begins (resulting in undefined behavior)
this.set('submitCooldown', true);
Ember.run.later(this, function () {
this.set('submitCooldown', false);
}, 500);
// Reflect to find if we need to transition,
// or just reload current model.
if (this._inIndex()) {
this.transitionToRoute('discover.aggregate');
} else {
this.get('aggController').send('submit');
}
// Refocus map on user-drawn shape.
// if (this.get('location_geom__within')) {
// this._zoomIn();
// }
},
reset() {
if (!this._inIndex()) {
this.transitionToRoute('index');
}
this._resetParams();
this._resetDatePickers();
},
},
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:5df6faea233808c6556f6ab7b79d7e126b054faf6651af82437fe36f225404cf
size 1193
|
/*
* Copyright (c) 2014 airbug Inc. All rights reserved.
*
* All software, both binary and source contained in this work is the exclusive property
* of airbug Inc. Modification, decompilation, disassembly, or any other means of discovering
* the source code of this software is prohibited. This work is protected under the United
* States copyright law and other international copyright treaties and conventions.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@Export('bugyarn.Yarn')
//@Require('ArgumentBug')
//@Require('Bug')
//@Require('Class')
//@Require('Obj')
//@Require('ObjectUtil')
//@Require('Set')
//@Require('TypeUtil')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var ArgumentBug = bugpack.require('ArgumentBug');
var Bug = bugpack.require('Bug');
var Class = bugpack.require('Class');
var Obj = bugpack.require('Obj');
var ObjectUtil = bugpack.require('ObjectUtil');
var Set = bugpack.require('Set');
var TypeUtil = bugpack.require('TypeUtil');
//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------
/**
* @class
* @extends {Obj}
*/
var Yarn = Class.extend(Obj, {
_name: "bugyarn.Yarn",
//-------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------
/**
* @constructs
* @param {Object} yarnContext
* @param {LoomContext} loomContext
*/
_constructor: function(yarnContext, loomContext) {
this._super();
//-------------------------------------------------------------------------------
// Private Properties
//-------------------------------------------------------------------------------
/**
* @private
* @type {LoomContext}
*/
this.loomContext = loomContext;
/**
* @private
* @type {Set.<string>}
*/
this.spunSet = new Set();
/**
* @private
* @type {Object}
*/
this.yarnContext = yarnContext;
},
//-------------------------------------------------------------------------------
// Getters and Setters
//-------------------------------------------------------------------------------
/**
* @return {LoomContext}
*/
getLoomContext: function() {
return this.loomContext;
},
/**
* @return {Object}
*/
getYarnContext: function() {
return this.yarnContext;
},
//-------------------------------------------------------------------------------
// Public Methods
//-------------------------------------------------------------------------------
/**
* @param {string} yarnName
* @return {*}
*/
get: function(yarnName) {
return this.yarnContext[yarnName];
},
/**
* @param {(string | Array.<string>)} winderNames
*/
spin: function(winderNames) {
var _this = this;
if (TypeUtil.isString(winderNames)) {
winderNames = [winderNames];
}
if (!TypeUtil.isArray(winderNames)) {
throw new ArgumentBug(ArgumentBug.ILLEGAL, "winderNames", winderNames, "parameter must either be either a string or an array of strings");
}
winderNames.forEach(function(winderName) {
if (!_this.spunSet.contains(winderName)) {
/** @type {Winder} */
var winder = _this.loomContext.getWinderByName(winderName);
if (!winder) {
throw new Bug("NoWinder", {}, "Cannot find Winder by the name '" + winderName + "'");
}
_this.spunSet.add(winderName);
winder.runWinder(_this);
}
});
},
/**
* @param {string} weaverName
* @param {Array.<*>=} args
* @return {*}
*/
weave: function(weaverName, args) {
if (!TypeUtil.isString(weaverName)) {
throw new ArgumentBug(ArgumentBug.ILLEGAL, "weaverName", weaverName, "parameter must either be a string");
}
/** @type {Weaver} */
var weaver = this.loomContext.getWeaverByName(weaverName);
if (!weaver) {
throw new Bug("NoWeaver", {}, "Cannot find Weaver by the name '" + weaverName + "'");
}
return weaver.runWeaver(this, args);
},
/**
* @param {Object} windObject
*/
wind: function(windObject) {
var _this = this;
ObjectUtil.forIn(windObject, function(yarnName, yarnValue) {
if (!ObjectUtil.hasProperty(_this.yarnContext, yarnName)) {
_this.yarnContext[yarnName] = yarnValue;
}
});
}
});
//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------
bugpack.export('bugyarn.Yarn', Yarn);
});
|
// _____ _ _ _ _ _
// | ___| | (_) | | | | | |
// _ __ |___ \ ___| |_ ___| | ____ _| |__ | | ___
// | '_ \ \ \/ __| | |/ __| |/ / _` | '_ \| |/ _ \
// | |_) /\__/ / (__| | | (__| < (_| | |_) | | __/
// | .__/\____(_)___|_|_|\___|_|\_\__,_|_.__/|_|\___|
// | | www.github.com/lartu/p5.clickable
// |_| created by Lartu, version 1.2
//Determines if the mouse was pressed on the previous frame
var cl_mouseWasPressed = false;
//Last hovered button
var cl_lastHovered = null;
//Last pressed button
var cl_lastClicked = null;
//All created buttons
var cl_clickables = [];
//This function is what makes the magic happen and should be ran after
//each draw cycle.
p5.prototype.runGUI = function(){
for(i = 0; i < cl_clickables.length; ++i){
if(cl_lastHovered != cl_clickables[i])
cl_clickables[i].onOutside();
}
if(cl_lastHovered != null){
if(cl_lastClicked != cl_lastHovered){
cl_lastHovered.onHover();
}
}
if(!cl_mouseWasPressed && cl_lastClicked != null){
cl_lastClicked.onPress();
}
if(cl_mouseWasPressed && !mouseIsPressed && cl_lastClicked != null){
if(cl_lastClicked == cl_lastHovered){
cl_lastClicked.onRelease();
}
cl_lastClicked = null;
}
cl_lastHovered = null;
cl_mouseWasPressed = mouseIsPressed;
}
p5.prototype.registerMethod('post', p5.prototype.runGUI);
//Button Class
function Clickable(x,y,img)
{
this.x = x || 0; //X position of the clickable
this.y = y || 0; //Y position of the clickable
this.width = img ? img.width : 100; //Width of the clickable
this.height = img ? img.height : 50; //Height of the clickable
this.color = "#FFFFFF"; //Background color of the clickable
this.cornerRadius = 10; //Corner radius of the clickable
this.strokeWeight = 2; //Stroke width of the clickable
this.stroke = "#000000"; //Border color of the clickable
this.text = "Press Me"; //Text of the clickable
this.textColor = "#000000"; //Color for the text shown
this.textSize = 12; //Size for the text shown
this.textFont = "sans-serif"; //Font for the text shown
this.img = img;
this.onHover = function(){
//This function is ran when the clickable is hovered but not
//pressed.
}
this.onOutside = function(){
//This function is ran when the clickable is NOT hovered.
}
this.onPress = function(){
//This function is ran when the clickable is pressed.
}
this.onRelease = function(){
//This funcion is ran when the cursor was pressed and then
//released inside the clickable. If it was pressed inside and
//then released outside this won't work.
}
this.locate = function(x, y){
this.x = x;
this.y = y;
}
this.resize = function(w, h){
this.width = w;
this.height = h;
}
this.draw = function()
{
if (this.img != null)
{
image(this.img, this.x, this.y, this.width, this.height);
} else
{
fill(this.color);
stroke(this.stroke);
strokeWeight(this.strokeWeight);
rect(this.x, this.y, this.width, this.height, this.cornerRadius);
fill(this.textColor);
noStroke();
textAlign(CENTER, CENTER);
textSize(this.textSize);
textFont(this.textFont);
text(this.text, this.x+1, this.y+1, this.width, this.height);
}
if(mouseX >= this.x && mouseY >= this.y
&& mouseX < this.x+this.width && mouseY < this.y+this.height){
cl_lastHovered = this;
if(mouseIsPressed && !cl_mouseWasPressed)
cl_lastClicked = this;
}
}
cl_clickables.push(this);
}
|
"use strict";
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
var randomPoem = require('./tools/poemBuilder1.js')
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static("client"))
app.use(bodyParser.json());
app.get("/poem", function(req, res) {
res.render('index', {data: randomPoem()});
})
/////???????////?////????//?
let mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/literate_telegram");
let WordPairSchema = new mongoose.Schema({
aKey: String,
bKey: String,
cKey: String,
aPhones: String,
bPhones: String,
cPhones: String,
aCount: Number,
bCount: Number,
cCount: Number,
occurances: Number,
});
let PronunciationSchema = new mongoose.Schema({
key: String,
phones: String,
syllable_count: Number,
alternate: Boolean
});
var Pronunciation = mongoose.model("Pronunciation", PronunciationSchema);
var WordPair = mongoose.model("WordPair", WordPairSchema);
app.post("/pronunciation", function(req, res){
console.log(req.body);
// Pronunciation.findOne({key: req.body.key}, function(err, word){
// if(err) res.status(404).json(err)
// else res.json(word);
// })
})
app.get("/word-pairs/random", function(req, res){
WordPair.aggregate([{$sample: {size: 1}},{$project: {_id: false, aKey:true, bKey:true}}], function(err, words){
res.json(words[0]);
});
})
app.post("/word-pairs/next", function(req, res){
// console.log(req.body)
WordPair.aggregate([{$match: {aKey: req.body.bKey}}, {$sample: {size: 1}}, {$project: {_id: false, aKey:true, bKey:true}}], function(err, pairs){
// console.log(pairs);
res.json(pairs);
})
})
app.listen(1337, function(){
console.log('l33t rhymes')
}); |
/* Game namespace */
var game = {
// an object where to store game information
data : {
// score
score : 0
},
// Run on page load.
"onload" : function () {
// Initialize the video.
if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0')) {
alert("Your browser does not support HTML5 canvas.");
return;
}
// add "#debug" to the URL to enable the debug Panel
if (document.location.hash === "#debug") {
window.onReady(function () {
me.plugin.register.defer(this, debugPanel, "debug");
});
}
// Initialize the audio.
me.audio.init("mp3,ogg");
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
// Load the resources.
me.loader.preload(game.resources);
// Initialize melonJS and display a loading screen.
me.state.change(me.state.LOADING);
},
// Run on game resources loaded.
"loaded" : function () {
me.pool.register("player", game.PlayerEntity, true);
me.state.set(me.state.MENU, new game.TitleScreen());
me.state.set(me.state.PLAY, new game.PlayScreen());
// Start the game.
me.state.change(me.state.PLAY);
}
};
|
/**
* @class EZ3.Box
* @constructor
* @param {EZ3.Vector3} [min]
* @param {EZ3.Vector3} [max]
*/
EZ3.Box = function(min, max) {
/**
* @property {EZ3.Vector3} min
* @default new EZ3.Vector3(Infinity)
*/
this.min = (min !== undefined) ? min : new EZ3.Vector3(Infinity);
/**
* @property {EZ3.Vector3} max
* @default new EZ3.Vector3(-Infinity)
*/
this.max = (max !== undefined) ? max : new EZ3.Vector3(-Infinity);
};
EZ3.Box.prototype.constructor = EZ3.Box;
/**
* @method EZ3.Box#set
* @param {EZ3.Vector3} min
* @param {EZ3.Vector3} max
* @return {EZ3.Box}
*/
EZ3.Box.prototype.set = function(min, max) {
this.min.copy(min);
this.max.copy(max);
return this;
};
/**
* @method EZ3.Box#copy
* @param {EZ3.Box} box
* @return {EZ3.Box}
*/
EZ3.Box.prototype.copy = function(box) {
this.min.copy(box.min);
this.max.copy(box.max);
return this;
};
/**
* @method EZ3.Box#clone
* @return {EZ3.Box}
*/
EZ3.Box.prototype.clone = function() {
return new EZ3.Box(this.min, this.max);
};
/**
* @method EZ3.Box#expand
* @param {EZ3.Vector3} point
* @return {EZ3.Box}
*/
EZ3.Box.prototype.expand = function(point) {
this.min.min(point);
this.max.max(point);
return this;
};
/**
* @method EZ3.Box#union
* @param {EZ3.Box} box
* @return {EZ3.Box}
*/
EZ3.Box.prototype.union = function(box) {
this.min.min(box.min);
this.max.max(box.max);
return this;
};
/**
* @method EZ3.Box#applyMatrix4
* @param {EZ3.Matrix4} matrix
* @return {EZ3.Box}
*/
EZ3.Box.prototype.applyMatrix4 = function(matrix) {
var points = [];
var i;
points.push((new EZ3.Vector3(this.min.x, this.min.y, this.min.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.min.x, this.min.y, this.max.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.min.x, this.max.y, this.min.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.min.x, this.max.y, this.max.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.max.x, this.min.y, this.min.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.max.x, this.min.y, this.max.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.max.x, this.max.y, this.min.z)).mulMatrix4(matrix));
points.push((new EZ3.Vector3(this.max.x, this.max.y, this.max.z)).mulMatrix4(matrix));
this.min.set(Infinity);
this.max.set(-Infinity);
for (i = 0; i < 8; i++)
this.expand(points[i]);
return this;
};
/**
* @method EZ3.Box#size
* @return {EZ3.Vector3}
*/
EZ3.Box.prototype.size = function() {
return new EZ3.Vector3().sub(this.max, this.min);
};
/**
* @method EZ3.Box#getCenter
* @return {EZ3.Vector3}
*/
EZ3.Box.prototype.center = function() {
return new EZ3.Vector3().add(this.max, this.min).scale(0.5);
};
|
'use strict';
angular.module('drunkeeperApp')
.config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'app/account/login/login.html',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'app/account/signup/signup.html',
controller: 'SignupCtrl'
})
.when('/settings', {
templateUrl: 'app/account/settings/settings.html',
controller: 'SettingsCtrl',
authenticate: true
});
}); |
require('./check-versions')();
const config = require('../config');
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.stringify(config.dev.env.NODE_ENV);
}
const opn = require('opn');
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const proxyMiddleware = require('http-proxy-middleware');
const webpackConfig = process.env.NODE_ENV === 'testing'
? require('./webpack.prod.conf')
: require('./webpack.dev.conf');
// default port where dev server listens for incoming traffic
const port = process.env.PORT || config.dev.port;
// automatically open browser, if not set will be false
const autoOpenBrowser = !!config.dev.autoOpenBrowser;
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
const proxyTable = config.dev.proxyTable;
const app = express();
const compiler = webpack(webpackConfig);
const devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true,
});
const hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
});
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', (compilation) => {
compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => {
hotMiddleware.publish({ action: 'reload' });
cb();
});
});
// proxy api requests
Object.keys(proxyTable).forEach((context) => {
let options = proxyTable[context];
if (typeof options === 'string') {
options = { target: options };
}
app.use(proxyMiddleware(options.filter || context, options));
});
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')());
// serve webpack bundle output
app.use(devMiddleware);
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware);
// serve pure static assets
const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory);
app.use(staticPath, express.static('./static'));
const uri = `http://localhost:${port}`;
/* eslint no-underscore-dangle: "off" */
let _resolve;
const readyPromise = new Promise((resolve) => {
_resolve = resolve;
});
console.log('> Starting dev server...');
devMiddleware.waitUntilValid(() => {
console.log(`> Listening at ${uri}\n`);
// when env is testing, don't need open it
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri);
}
_resolve();
});
const server = app.listen(port);
module.exports = {
ready: readyPromise,
close: () => {
server.close();
},
};
|
$(document).ready(function(){
//fancybox.js init
/*$('.fancybox').fancybox({
openEffect : 'none',
closeEffect : 'none',
prevEffect : 'none',
nextEffect : 'none',
arrows : false,
helpers : {
media : {},
buttons : {}
}
});*/
//wow.js init
wow = new WOW(
{
animateClass: 'animated',
mobile: false,
offset: 100
}
);
wow.init();
});
|
#!/usr/bin/env node
/*
try {
require(./newrelic)
require('newrelic')
} catch (e) {
// Don't load New Relic if the configuration file does't exist.
}
*/
/*
require('babel/register')({
only: new RegExp(__dirname + '/lib' + '|' +
__dirname + '/node_modules/p2p-file-transfer')
})
*/
module.exports = require('./lib/server')
|
"use strict";
var compression = require("../lib/core/middleware/compression");
describe("core.middleware.compression", function() {
var fakeThis;
beforeEach("create fake this", function() {
fakeThis = {
enabled: sinon.stub().withArgs("compress").returns(true),
app: {
use: sinon.spy()
}
};
});
it("should be a function", function() {
compression.should.be.a("function");
});
it("should only check the compress option", function() {
compression.call(fakeThis);
fakeThis.enabled.should.be.calledOnce;
fakeThis.enabled.should.be.calledWith("compress");
});
it("should use one middleware function if enabled", function() {
compression.call(fakeThis);
fakeThis.app.use.should.be.calledOnce;
// express-compress returns an array of middleware
fakeThis.app.use.args[0][0].should.be.a("function");
});
it("should not use any middleware if not enabled", function() {
fakeThis.enabled = sinon.stub().withArgs("compress").returns(false);
compression.call(fakeThis);
fakeThis.app.use.should.not.be.called;
});
});
|
var os = require('os');
var fs = require('fs');
var path = require('path');
var SerialPort = require("serialport");
//Default configuration
var config = {
spm: { }, //Serial port manager
cli: true, //Command line interface
port: 5147,
mode: "http", //HTTP server with WebSocket by default
prefix: "/api/v1", //REST API route prefix, e.g. "/" for root or "/api/v1" etc.
verbose: process.env.NODE_VERBOSE == "true" || process.env.NODE_VERBOSE == "1",
debug: process.env.NODE_DEBUG == "true" || process.env.NODE_DEBUG == "1", //Even more details than verbose
permissions: {
list: true,
read: true,
write: true,
ui: true,
ws: true
}
};
//Command line interface
var args = process.argv.slice(2);
for (var i = 0; i < args.length; i++) {
switch (args[i]) {
case "--help":
help();
process.exit(0);
break;
case "--list":
return listSerialPorts();
case "-p":
case "--port":
config.port = parseInt(args[++i]);
if (!(config.port > 0)) {
console.error("Expected a numeric HTTP port number!");
process.exit(2);
}
break;
case "-m":
case "--mode":
config.mode = args[++i];
break;
case "--prefix":
config.prefix = args[++i];
break;
case "--no-list":
config.permissions.list = false;
break;
case "--no-read":
config.permissions.read = false;
break;
case "--no-write":
config.permissions.write = false;
break;
case "--no-ui":
config.permissions.ui = false;
break;
case "--no-ws":
config.permissions.ws = false;
break;
case "--allow-ports":
var ports = args[++i];
if (!ports) {
console.error("Expected serial port names after --allow-ports");
process.exit(2);
}
config.permissions.allowedPorts = ports.split(",");
break;
case "--config":
var ssp = args[++i];
ssp = ssp.split(",");
config.options = { };
for (var s = 0; s < ssp.length; s++) {
switch (s) {
case 0:
config.portname = ssp[s];
break;
case 1:
config.options.baudRate = parseInt(ssp[s]);
if (!(config.options.baudRate > 0)) {
throw new Error("Error in --config argument: baud rate must be greater than 0");
}
break;
case 2:
//Example: 8N1 = 8 data bits, no parity, 1 stop bit
var value = ssp[s];
if (value.length != 3) {
throw new Error("Error in --config argument: " + value);
}
//Parse data bits settings
config.options.dataBits = parseInt(value[0]);
if (!(5 <= config.options.dataBits && config.options.dataBits <= 8)) {
throw new Error("Error in --config argument: data bits should be 5, 6, 7 or 8");
}
//Parse stop bits settings
config.options.stopBits = parseInt(value[2]);
if (config.options.stopBits != 1 && config.options.stopBits != 2) {
throw new Error("Error in --config argument: stop bits should be 1 or 2");
}
//Parse parity settings
var parity = { "N": "none", "E": "even", "O": "odd", "M": "mark", "S": "space" };
config.options.parity = parity[value[1].toUpperCase()];
if (!config.options.parity) {
throw new Error("Error in --config argument: parity should be N - none, E - even, O - odd, M - mark or S - space");
}
break;
default:
throw new Error("Unknown --config argument: " + ssp[s]);
}
}
break;
case "--verbose":
config.verbose = true;
break;
//Intentionally undocumented in help()
case "--debug":
config.debug = true;
config.verbose = true;
break;
case "--version":
console.log(require('./package.json').version);
process.exit(0);
break;
default:
console.error("Unknown command line argument: " + args[i]);
process.exit(2);
break;
}
}
//Prints help message
function help() {
console.log("Usage:");
console.log(" remote-serial-port-server [options]");
console.log("");
console.log("Options:");
console.log(" --help Print this message");
console.log(" --list Print serial ports and exit");
console.log(" --port, -p [num] Socket port number, default: 5147");
console.log(" --mode, -m [mode] Server mode: http, tcp, udp, echo; default: http");
console.log(" --prefix [path] URL prefix: '/' for root or '/api/v1' etc.");
console.log(" --no-list Disable serial port list");
console.log(" --no-read Disable read ops");
console.log(" --no-write Disable write ops");
console.log(" --no-ui Disable web interface");
console.log(" --no-ws Disable web socket");
console.log(" --allow-ports [list] Allow only specific ports");
console.log(" --config [port,baud,extra]");
console.log(" Socket serial port configuration, only for TCP and UDP");
console.log(" [extra] as data bits, parity and stop bits");
console.log(" Data bits 5, 6, 7 or 8 and stop bits 1 or 2");
console.log(" Parity: N-none, E-even, O-odd, M-mark or S-space");
console.log(" For example 8N1 = 8 data bits, N no parity, 1 stop bit");
console.log(" --verbose Enable detailed logging");
console.log(" --version Print version number");
console.log("");
console.log("Examples:");
console.log(" remote-serial-port-server");
console.log(" remote-serial-port-server --list");
console.log(" remote-serial-port-server --allow-ports COM1,COM2,COM3");
console.log(" remote-serial-port-server --no-read --no-write --no-ws --port 80");
console.log(" remote-serial-port-server --mode tcp --config COM1,115200 --port 3000");
console.log(" remote-serial-port-server --mode udp --config /dev/ttyUSB0,9600,8N1 -p 3000");
}
//Prints serial ports
function listSerialPorts() {
console.log("Serial ports:");
SerialPort.list(function (err, ports) {
if (err) {
console.error(err);
process.exit(2);
}
ports.forEach(function(port) {
console.log(" " + port.comName);
});
process.exit(0);
});
}
function startUdpSocket(config) {
try {
var listen = require('./lib/udp.js');
config.host = "0.0.0.0";
listen(config);
}
catch (e) {
console.error(e.message);
process.exit(1);
}
}
function startTcpSocket(config) {
try {
var listen = require('./lib/tcp.js');
listen(config);
}
catch (e) {
console.error(e.message);
process.exit(1);
}
}
function startWebServer(config) {
var express = require('express');
var logger = require('morgan');
var engine = require('ejs');
var bodyParser = require('body-parser');
//Initialize express
var app = express();
app.startup = new Date();
app.uptime = function() {
return Math.ceil(new Date().getTime() - app.startup.getTime());
};
//Set up the view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
//Register path /lib/RemoteSerialPort.js for web access
var clientPath = path.join(__dirname, "node_modules", "remote-serial-port-client", "lib");
if (fs.existsSync(clientPath)) {
app.use("/lib", express.static(clientPath));
}
else {
if (config.permissions.ui) {
console.warn("Warning: Web interface not available!");
}
config.permissions.ui = false;
}
//Default index page
app.get("/", function(req, res, next) {
if (!config.permissions.ui) {
return next(new Error("No web interface permissions!"));
}
res.render("index");
});
//API status and version
app.get(config.prefix, function(req, res, next) {
var pkg = require('./package.json');
res.json({ name: pkg.name, version: pkg.version, uptime: app.uptime() });
});
//Register REST API
var webserver = require('./lib/webserver.js');
var subapp = webserver(config);
app.use(config.prefix, subapp);
//Catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//Error handler
app.use(function(err, req, res, next) {
if (config.verbose) {
console.error(err);
}
//HTTP status code
res.status(err.status || 500);
if (!config.permissions.ui) {
return res.end();
}
//HTML output
res.render('error', {
status: err.status,
message: err.message,
stack: err.stack
});
});
//Start the HTTP server
var server = app.listen(config.port, function() {
console.log('HTTP on port ' + server.address().port);
});
//WebSocket
if (config.permissions.ws) {
try {
var websocket = require('./lib/websocket.js');
var wss = websocket(config).use(server);
//Register receive event to forward data over web socket
if (config.spm && typeof config.spm == "object") {
config.spm.on("received", function(e) {
var port = config.spm[e.port];
if (!port || !port.websockets) {
return;
}
var websockets = port.websockets;
if (websockets && config.permissions.read) {
for (var i = 0; i < websockets.length; i++) {
var ws = websockets[i];
ws.send(e.data);
}
}
});
}
}
catch (error) {
console.warn("Warning: WebSocket not available!", error);
}
}
}
function startEcho(config) {
try {
var listen = require('./lib/echo.js');
listen(config);
setInterval(function() { }, Number.POSITIVE_INFINITY);
}
catch (e) {
console.error(e.message);
process.exit(1);
}
}
switch (config.mode) {
case "udp":
startUdpSocket(config);
break;
case "tcp":
startTcpSocket(config);
break;
case "http":
startWebServer(config);
break;
case "echo":
startEcho(config);
break;
default:
console.error("Unknown mode: " + config.mode);
process.exit(2);
break;
} |
/**
reframe.js - Reframe.js: responsive iframes for embedded content
@version v3.0.0
@link https://github.com/yowainwright/reframe.ts#readme
@author Jeff Wainwright <[email protected]> (http://jeffry.in)
@license MIT
**/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.reframe = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
/**
* REFRAME.TS 🖼
* ---
* @param target
* @param cName
* @summary defines the height/width ratio of the targeted <element>
*/
function reframe(target, cName) {
var _a, _b;
if (cName === void 0) { cName = 'js-reframe'; }
var frames = __spreadArrays((typeof target === 'string' ? document.querySelectorAll(target) : target));
var c = cName || 'js-reframe';
for (var i = 0; i < frames.length; i += 1) {
var frame = frames[i];
var hasClass = frame.className.split(' ').indexOf(c) !== -1;
if (hasClass || frame.style.width.indexOf('%') > -1)
continue;
// get height width attributes
var height = frame.getAttribute('height') || frame.offsetHeight;
var width = frame.getAttribute('width') || frame.offsetWidth;
var heightNumber = typeof height === 'string' ? parseInt(height) : height;
var widthNumber = typeof width === 'string' ? parseInt(width) : width;
// general targeted <element> sizes
var padding = (heightNumber / widthNumber) * 100;
// created element <wrapper> of general reframed item
// => set necessary styles of created element <wrapper>
var div = document.createElement('div');
div.className = cName;
var divStyles = div.style;
divStyles.position = 'relative';
divStyles.width = '100%';
divStyles.paddingTop = padding + "%";
// set necessary styles of targeted <element>
var frameStyle = frame.style;
frameStyle.position = 'absolute';
frameStyle.width = '100%';
frameStyle.height = '100%';
frameStyle.left = '0';
frameStyle.top = '0';
// reframe targeted <element>
(_a = frame.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(div, frame);
(_b = frame.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(frame);
div.appendChild(frame);
}
}
return reframe;
})));
|
/**
*
* STREAM: MVA (window: 15)
*
*
*
* DESCRIPTION:
* -
*
*
* API:
* -
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* HISTORY:
* - 2014/05/28: Created. [AReines].
*
*
* DEPENDENCIES:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. [email protected]. 2014.
*
*/
(function() {
'use strict';
// MODULES //
var // Stream combiner:
pipeline = require( 'stream-combiner' ),
// Flow streams:
flow = require( 'flow.io' );
// FUNCTIONS //
/**
* FUNCTION: map( fcn )
* Returns a data transformation function.
*
* @private
* @param {function} fcn - function which performs the map transform
* @returns {function} data transformation function
*/
function map( fcn ) {
/**
* FUNCTION: map( data )
* Defines the data transformation.
*
* @private
* @param {*} data - stream data
* @returns {number} transformed data
*/
return function map( data ) {
return fcn( data );
};
} // end FUNCTION map()
// STREAM //
/**
* FUNCTION: Stream()
* Stream constructor.
*
* @returns {Stream} Stream instance
*/
function Stream() {
this.name = '';
this._window = 15;
// ACCESSORS:
this._value = function( d ) {
return d.y;
};
return this;
} // end FUNCTION Stream()
/**
* ATTRIBUTE: type
* Defines the stream type.
*/
Stream.prototype.type = 'mva-w15';
/**
* METHOD: metric( metric )
* Metric setter and getter. If a metric instance is supplied, sets the metric. If no metric is supplied, returns the instance metric value function.
*
* @param {object} metric - an object with a 'value' method; see constructor for basic example. If the metric has a name property, sets the transform name.
* @returns {Stream|object} Stream instance or instance metric
*/
Stream.prototype.metric = function ( metric ) {
if ( !arguments.length ) {
return this._value;
}
if ( !metric.value ) {
throw new Error( 'metric()::invalid input argument. Metric must be an object with a \'value\' method.' );
}
// Extract the method to calculate the metric value and bind the metric context:
this._value = metric.value.bind( metric );
// If the metric has a name, set the transform name:
this.name = ( metric.name ) ? metric.name : '';
// Return the stream instance:
return this;
}; // end METHOD metric()
/**
* METHOD: stream()
* Returns a JSON data transform stream for performing MVA.
*
* @returns {stream} transform stream
*/
Stream.prototype.stream = function() {
var mTransform, tStream, mva, mStream, pStream;
// Create the input transform stream:
mTransform = flow.map()
.map( map( this._value ) );
// Create the input transform stream:
tStream = mTransform.stream();
// Create an MVA stream generator and configure:
mva = flow.mva()
.window( this._window );
// Create an MVA stream:
mStream = mva.stream();
// Create a stream pipeline:
pStream = pipeline(
tStream,
mStream
);
// Return the pipeline:
return pStream;
}; // end METHOD stream()
// EXPORTS //
module.exports = function createStream() {
return new Stream();
};
})(); |
'use strict';
module.exports = {
compile: {
options: {
style: 'expanded',
},
src : 'src/css/style.scss',
dest : 'dist/css/style.css',
},
};
|
// Generated on 2014-11-07 using generator-angular 0.9.8
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
sass: {
src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}bower_components\//
}
},
// Compiles Sass to CSS and generates necessary files if requested
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: './bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false,
assetCacheBuster: false,
raw: 'Sass::Script::Number.precision = 10\n'
},
dist: {
options: {
generatedImagesDir: '<%= yeoman.dist %>/images/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: ['*.js', '!oldieshim.js'],
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'fonts/*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: '.',
src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'compass:server'
],
test: [
'compass'
],
dist: [
'compass:dist',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
function List(storage, $) {
var items = [];
var doneItems = [];
var nextId = 0;
this.storage = storage;
this.toDo = items;
this.done = doneItems;
this.add = function (text) {
var newItem = new ListItemModel(nextId,text);
items.push(newItem);
storage.store(newItem.id, JSON.stringify(newItem));
nextId++;
return newItem;
};
this.markDone = function(id) {
var currentDate = new Date();
var item = get(id, items);
doneItems.push(item);
item.done = true;
item.dateDone = currentDate;
storage.store(item.id, JSON.stringify(item));
return item;
};
this.loadItems = function(areDone) {
var deferred = $.Deferred();
storage.load()
.then(populateLists)
.then(function(){
deferred.resolve();
});
return deferred.promise();
};
function populateLists(data){
for(var i=0; i < data.length ;i++){
var item = JSON.parse(data[i], reviver);
if(item.id > nextId){
nextId = item.id;
}
if(item.done){
doneItems.push(item);
} else {
items.push(item);
}
}
// increase nextId by 1 so that it ready for use
nextId++;
}
function get(id, list){
for(var i=0; i < list.length; i++){
if(list[i].id == id){
return list[i];
}
}
return null;
}
} |
version https://git-lfs.github.com/spec/v1
oid sha256:5181d344dc3334a5a80ecae84df1bb3107af7d92135639b56a7f73ec2ea1931c
size 3057
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactRouter = require('react-router');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Menu = function (_Component) {
_inherits(Menu, _Component);
function Menu(props) {
_classCallCheck(this, Menu);
return _possibleConstructorReturn(this, (Menu.__proto__ || Object.getPrototypeOf(Menu)).call(this, props));
}
_createClass(Menu, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ className: 'menu-component' },
_react2.default.createElement(
'nav',
null,
_react2.default.createElement(
_reactRouter.Link,
{ to: '/anuncios', activeClassName: 'selected' },
_react2.default.createElement('img', { src: '/imgs/building.svg' }),
_react2.default.createElement(
'span',
null,
'An\xFAncios'
)
),
_react2.default.createElement(
_reactRouter.Link,
{ to: '/novo-anuncio', activeClassName: 'selected' },
_react2.default.createElement('img', { src: '/imgs/plus-icon.svg' }),
_react2.default.createElement(
'span',
null,
'Novo an\xFAncio'
)
)
)
);
}
}]);
return Menu;
}(_react.Component);
Menu.propTypes = {};
exports.default = Menu; |
bql`
image(size="foo") {
width
height
src
}
`; |
import plain from '../structure/plain'
import immutable from '../structure/immutable'
import defaultShouldError from '../defaultShouldError'
describe('defaultShouldError', () => {
it('should validate when initialRender is true', () => {
expect(
defaultShouldError({
initialRender: true
})
).toBe(true)
})
const describeDefaultShouldError = structure => {
const { fromJS } = structure
it('should validate if values have changed', () => {
expect(
defaultShouldError({
initialRender: false,
structure,
values: fromJS({
foo: 'fooInitial'
}),
nextProps: {
values: fromJS({
foo: 'fooChanged'
})
}
})
).toBe(true)
})
it('should not validate if values have not changed', () => {
expect(
defaultShouldError({
initialRender: false,
structure,
values: fromJS({
foo: 'fooInitial'
}),
nextProps: {
values: fromJS({
foo: 'fooInitial'
})
}
})
).toBe(false)
})
it('should validate if field validator keys have changed', () => {
expect(
defaultShouldError({
initialRender: false,
structure,
values: fromJS({
foo: 'fooValue'
}),
nextProps: {
values: fromJS({
foo: 'fooValue'
})
},
lastFieldValidatorKeys: [],
fieldValidatorKeys: ['foo']
})
).toBe(true)
})
it('should not validate if field validator keys have not changed', () => {
expect(
defaultShouldError({
initialRender: false,
structure,
values: fromJS({
foo: 'fooInitial'
}),
nextProps: {
values: fromJS({
foo: 'fooInitial'
})
},
lastFieldValidatorKeys: ['foo'],
fieldValidatorKeys: ['foo']
})
).toBe(false)
})
}
describeDefaultShouldError(plain)
describeDefaultShouldError(immutable)
})
|
const path = require('path');
module.exports = {
HOST: 'localhost',
PORT: 3000,
URL: {
ROOT: 'https://bootflex.herokuapp.com',
API: 'https://bootflex.herokuapp.com/api'
},
PATH: {
ROOT: path.join(__dirname, '..')
}
};
|
import Chaffle from "chaffle";
const scrambleAuthor = () => {
const elements = document.querySelectorAll("[data-chaffle]");
elements.forEach(el => {
const chaffle = new Chaffle(el, {
speed: 10,
delay: 20,
});
el.addEventListener("mouseover", () => {
chaffle.init();
});
});
};
export { scrambleAuthor };
|
// Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React, {PropTypes, Component} from 'react';
import ViewportMercator from 'viewport-mercator-project';
import window from 'global/window';
export default class CanvasOverlay extends Component {
static propTypes = {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired,
zoom: PropTypes.number.isRequired,
redraw: PropTypes.func.isRequired,
isDragging: PropTypes.bool.isRequired
};
componentDidMount() {
this._redraw();
}
componentDidUpdate() {
this._redraw();
}
_redraw() {
const pixelRatio = window.devicePixelRatio || 1;
const canvas = this.refs.overlay;
const ctx = canvas.getContext('2d');
ctx.save();
ctx.scale(pixelRatio, pixelRatio);
const mercator = ViewportMercator(this.props);
this.props.redraw({
width: this.props.width,
height: this.props.height,
ctx,
project: mercator.project,
unproject: mercator.unproject,
isDragging: this.props.isDragging
});
ctx.restore();
}
render() {
const pixelRatio = window.devicePixelRatio || 1;
return (
<canvas
ref="overlay"
width={ this.props.width * pixelRatio }
height={ this.props.height * pixelRatio }
style={ {
width: `${this.props.width}px`,
height: `${this.props.height}px`,
position: 'absolute',
pointerEvents: 'none',
left: 0,
top: 0
} }/>
);
}
} |
module.exports = {"1308":{"id":"1308","parentId":"155","name":"\u89e3\u653e\u533a"},"1309":{"id":"1309","parentId":"155","name":"\u4e2d\u7ad9\u533a"},"1310":{"id":"1310","parentId":"155","name":"\u9a6c\u6751\u533a"},"1311":{"id":"1311","parentId":"155","name":"\u5c71\u9633\u533a"},"1312":{"id":"1312","parentId":"155","name":"\u6c81\u9633\u5e02"},"1313":{"id":"1313","parentId":"155","name":"\u5b5f\u5dde\u5e02"},"1314":{"id":"1314","parentId":"155","name":"\u4fee\u6b66\u53bf"},"1315":{"id":"1315","parentId":"155","name":"\u535a\u7231\u53bf"},"1316":{"id":"1316","parentId":"155","name":"\u6b66\u965f\u53bf"},"1317":{"id":"1317","parentId":"155","name":"\u6e29\u53bf"}}; |
"use strict";
const removeDiacritics = require('diacritics').remove;
const request = require('request');
//const pSegCases = require('../test/promiseSwitchCase.js');
var utils = {
/**
* Resolve all promises in Object via for ... in loop
* @param {object} obj - The object containing function properties => Switch cases that resolve
*/
switchCasePromiseResolver: function switchCasePromiseResolver (obj, event) {
//Promise Resolver For...In Loop - returns out to Var as Array
let i = -1;
var promisesArr = [];
//Loop through the segmented Switch Cases (test is an obj with each Switch Case as a property)
for (var ligneFn in obj) {
//console.log(ligneFn);
i++;
//resolve each switch case with the event.message.text and return resolve
promisesArr[i] = Promise.resolve( obj[ligneFn](event) );
}
/**
* Returns newly filled in Arr from loop
* @return {array} - returns array with promise status (resolve, false) in array
*/
return promisesArr;
},
//////////////////
// Text Cleaners
//////////////////
cleanseText: function cleanseText (text) {
return removeDiacritics(
text.toLowerCase()
.replace(/\s\s+|[.-]/g, function (match) { return (match === "-" || " " ? " " : "") }
).trim())
//([\uD800-\uDBFF][\uDC00-\uDFFF]) to remove emojis
},
//////////////////////////////////////////
//Format Time before SearchStop Function
/////////////////////////////////////////
timeFormatter (time) {
var timeArr = time.split('T');
var finalTime = timeArr[1].slice(0,2) + ':' + timeArr[1].slice(2,4);
return finalTime;
},
//Random Number between 2 values
randNum (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
},
//Whitelist them domains bruh
setWhiteList(domains) {
if (!Array.isArray(domains)) {
throw "Error ... domains param MUST be an array. You passed in: " + typeof domains;
} else {
request(
{
method: 'POST',
uri: 'https://graph.facebook.com/v2.6/me/messenger_profile?access_token=' + process.env.PAGE_ACCESS_TOKEN,
headers: {
'content-type': 'application/json'
},
body: {
whitelisted_domains: domains
},
json: true
}, function (error, response, body) {
if (!error) {
request(
{
method: 'GET',
uri: 'https://graph.facebook.com/v2.6/me/messenger_profile?fields=whitelisted_domains&access_token=' + process.env.PAGE_ACCESS_TOKEN
}, function (error, response, body) {
if (!error) {
console.log('Displaying whitelisted sites:');
console.log(body);
} else if (error) {
console.error (error);
}
})
} else if (error) {
console.error(error);
}
}
);
};
}
}
module.exports = utils; |
var my = require('my');
var maxHeight = 300, maxWidth = 300;
exports.view = function(data) {
console.log("view: m.js");
console.log(data);
var topic = data.topic;
return(
my.page({title: 'Hello World', scripts:["http://code.jquery.com/jquery-latest.js"]},
/*my.div({id: 'myDiv', style: {height: '800px', border: 'red 1px solid'}},
'Actor ' + data.name
),*/
my.h1(topic.name),
tabs(topic.friends),
gallery2(topic.friends[0].entities, '100%', '300px', '200px', '270px', '30px', '30px')
)
)}
function tabs(friends)
{
var tabs = my.div({});
for (var i = 0; i < friends.length; i++)
tabs.children.push(my.p(friends[i]));
return gallery;
}
function gallery(imgUrls, width, height, thumbWidth, thumbHeight, hGap, vGap) {
var galleryStyle = {
margin: 'auto',
width: width,
height: height
};
var thumbStyle = {
'margin-top': vGap,
'margin-left': hGap,
'max-width': thumbWidth,
'max-height': thumbHeight,
'-moz-box-shadow': '1px 1px 6px #999',
'-webkit-box-shadow': '1px 1px 6px #999'
};
var gallery = my.div({style: galleryStyle});
for (var i = 0; i < imgUrls.length; i++)
gallery.children.push(my.img({style: thumbStyle, src: imgUrls[i]}));
return gallery;
}
function gallery2(imgUrls, width, height, thumbWidth, thumbHeight, hGap, vGap) {
var galleryStyle = {
display: 'inline-block',
width: width,
height: height
};
var thumbDivStyle = {
display: 'inline-block',
'margin-top': vGap,
'margin-left': hGap,
'width': thumbWidth,
'height': thumbHeight,
'text-align': 'center'
};
var thumbStyle = {
'max-width': thumbWidth,
'max-height': thumbHeight,
'-moz-box-shadow': '1px 1px 6px #999',
'-webkit-box-shadow': '1px 1px 6px #999'
};
var gallery = my.div({style: galleryStyle});
for (var i = 0; i < imgUrls.length; i++)
{
var imgUrl = "http://img.freebase.com/api/trans/image_thumb"+imgUrls[i].id+"?mode=fit&maxheight="+maxHeight+"&maxwidth="+maxWidth;
//console.log(imgUrls[i].id);
gallery.children.push(
my.div({style: thumbDivStyle},
my.img({style: thumbStyle, src: imgUrl}
)
));
}
return gallery;
}
|
/*eslint no-console: 1 */
console.warn('You are using the default filter for the fileMeta service. For more information about event filters see https://docs.feathersjs.com/api/events.html#event-filtering'); // eslint-disable-line no-console
module.exports = function(data, connection, hook) { // eslint-disable-line no-unused-vars
return data;
};
|
export default function HomeService($rootScope, $window, $http) {
var service = {
send: send,
loadSettings: loadSettings,
};
return service;
function send(msg, data) {
console.log(msg, data);
//$rootScope.$broadcast(msg, data);
}
function loadSettings() {
return $http({
method: 'GET',
url: 'http://dev.app.com/api/v1/foodtruck',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
}
}).then(function successCallback(response) {
return response;
}, function errorCallback(response) {
return "Error loading settings";
});
}
}
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { setSearchTerm } from './actionCreators'
import { Link } from 'react-router'
class Header extends Component {
constructor (props) {
super(props)
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
}
handleSearchTermChange (event) {
this.props.dispatch(setSearchTerm(event.target.value))
}
render () {
let utilSpace
if (this.props.showSearch) {
utilSpace = <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' />
} else {
utilSpace = (
<h2>
<Link to='/search'>Back</Link>
</h2>
)
}
return (
<header>
<h1>
<Link to='/'>
jordaflix
</Link>
</h1>
{utilSpace}
</header>
)
}
}
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
const { func, bool, string } = React.PropTypes
Header.propTypes = {
handleSearchTermChange: func,
dispatch: func,
showSearch: bool,
searchTerm: string
}
export default connect(mapStateToProps)(Header)
|
var answers = [];
var validate = () => {
$("#afev-answer-1").animate(
{ backgroundColor: "green"}
);
var good = true;
if (answers.indexOf(1) === -1) {
good = false;
}
if (answers.indexOf(2) !== -1) {
$("#afev-answer-2").animate(
{ backgroundColor: "red"}
);
good = false;
}
if (answers.indexOf(3) !== -1) {
$("#afev-answer-3").animate(
{ backgroundColor: "red"}
);
good = false;
}
if (good) {
$("#afev-secret-right").show();
}
else {
$("#afev-secret-wrong").show();
}
$("#afev-secret-response").show();
}
window.onload = () => {
for (var i = 0; i < 5; i++) {
let index = i + 1;
$("#afev-answer-" + index).on("click", () => {
answers.push(index);
$("#afev-answer-" + index).animate(
{ backgroundColor: "#1e5abc"}
);
})
}
var score = localStorage.getItem("afev-score");
if (score !== null) {
score = score.substring(0, 3) + '1' + score.substring(4, 5);
localStorage.setItem("afev-score", score);
} else {
localStorage.setItem("afev-score", "10000");
}
initLayout();
}; |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M17.5 8c.46 0 .91-.05 1.34-.12C17.44 5.56 14.9 4 12 4c-.46 0-.91.05-1.34.12C12.06 6.44 14.6 8 17.5 8zM8.08 5.03C6.37 6 5.05 7.58 4.42 9.47c1.71-.97 3.03-2.55 3.66-4.44z",
opacity: ".3"
}), h("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 2c2.9 0 5.44 1.56 6.84 3.88-.43.07-.88.12-1.34.12-2.9 0-5.44-1.56-6.84-3.88.43-.07.88-.12 1.34-.12zM8.08 5.03C7.45 6.92 6.13 8.5 4.42 9.47 5.05 7.58 6.37 6 8.08 5.03zM12 20c-4.41 0-8-3.59-8-8 0-.05.01-.1.01-.15 2.6-.98 4.68-2.99 5.74-5.55 1.83 2.26 4.62 3.7 7.75 3.7.75 0 1.47-.09 2.17-.24.21.71.33 1.46.33 2.24 0 4.41-3.59 8-8 8z"
}), h("circle", {
cx: "9",
cy: "13",
r: "1.25"
}), h("circle", {
cx: "15",
cy: "13",
r: "1.25"
})), 'FaceTwoTone'); |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'horizontalrule', 'no', {
toolbar: 'Sett inn horisontal linje'
} );
|
'use strict';
module.exports = function(localeA, localeB, options) {
options = options || {};
if (typeof localeA !== 'object' || typeof localeB !== 'object') {
throw new Error('s18n: `localeA` and `localeB` must be objects.');
}
var localeAMissing = {};
var localeBMissing = {};
var unmodifiedStrings = {};
var modifiedStrings = [];
for (var hashA in localeA) {
if (typeof localeB[hashA] === 'undefined') {
localeBMissing[hashA] = localeA[hashA];
} else {
if (localeA[hashA] === localeB[hashA]) {
unmodifiedStrings[hashA] = localeA[hashA];
} else {
modifiedStrings.push({
hash: hashA,
strings: [
localeA[hashA],
localeB[hashA]
]
});
}
}
}
for (var hashB in localeB) {
if (typeof localeA[hashB] === 'undefined') {
localeAMissing[hashB] = localeB[hashB];
}
}
return [
arrayifyResults(localeAMissing),
arrayifyResults(localeBMissing),
arrayifyResults(unmodifiedStrings),
modifiedStrings
];
};
function arrayifyResults(resultsObj) {
var array = [];
for (var hash in resultsObj) {
array.push({
hash: hash,
string: resultsObj[hash]
});
}
return array;
}
|
//basic physics entity
//This entity extends the joncom base entity and is responsible for
//collision categories
//property inheritance
//default settings/hooks
//It also defines the ObjectWorld and RenderWorld objects "soma" and "animus" (or whatever distinct names you can think of)
//The soma cannot call animus functions and vice versa. Both must be called from top level functions like update, init, draw, or top level physics callbacks like beginContact, preSolve, etc:.
//This is to maintain separation between ObjectWorld and RenderWorld
ig.module('game.entities.physEnt')
.requires('plugins.joncom.box2d.entity', 'game.const_defs', 'plugins.tween', 'plugins.tileUtil')
.defines(function() {
EntityPhysEnt = ig.Entity.extend({
//default settings, overwritten by _loadSettings
gravityFactor: 1,
categoryBits: ig.Filter.NOCOLLIDE,
maskBits: ig.Filter.ALL,
isTransient: false,
currentDim: 'normal',
currentFix: null,
init: function( x, y, settings ) {
//inject filter data into settings before creating box2d body
settings.categoryBits = this.categoryBits;
settings.maskBits = this.maskBits;
this.parent( x, y, settings );
//this._loadSettings(settings);
//presume non-rotating body
//will almost certainly be entity-specific later
if (!ig.global.wm) {
this.body.SetFixedRotation(this.isFixedRotation);
this.currentFix = this.body.GetFixtureList();
}
this.setupAnimation();
},
//checks that allow zero value... is there a shorter way to handle this?
//allows entities to get context-sensitive properties, though most settings will still be pre-defined
_loadSettings: function(settings) {
if (typeof(settings.categoryBits) !== 'null' && typeof(settings.categoryBits) !== 'undefined') {
console.log("Category is happening");
this.categoryBits = settings.categoryBits;
}
if (typeof(settings.maskBits) !== 'null' && typeof(settings.maskBits) !== 'undefined' ) {
console.log("Mask is happening");
this.maskBits = settings.maskBits;
}
if (typeof(settings.gravityFactor) !== 'null' && typeof(settings.gravityFactor) !== 'undefined') {
console.log("Gravity is happening");
this.gravityFactor = settings.gravityFactor;
}
if (typeof(settings.isFixedRotation) !== 'null' && typeof(settings.isFixedRotation) !== 'undefined') {
console.log("Rotation is happening");
this.isFixedRotation = settings.isFixedRotation;
}
if (settings.isTransient !== 'null' && settings.isTransient !== undefined) {
console.log("Transient is happening");
this.isTransient = settings.isTransient;
}
},
beginContact: function(other, contact) {
this.parent(other,contact);
},
setupAnimation: function() { },
//creates a sensor fixture for altering an entity's shape or size
makeDim: function(name, size, filterSettings) {
var shapeDef = new Box2D.Collision.Shapes.b2PolygonShape();
shapeDef.SetAsBox(size.x / 2 * Box2D.SCALE, size.y / 2 * Box2D.SCALE);
var fixtureDef = new Box2D.Dynamics.b2FixtureDef();
fixtureDef.shape = shapeDef;
fixtureDef.density = 0; //massless sensor
fixtureDef.friction = this.uniFriction;
fixtureDef.restitution = this.bounciness;
fixtureDef.userData = {name: name, categoryBits: null, maskBits: null, type: 'dim'};
if (filterSettings) {
fixtureDef.userData.categoryBits = filterSettings.categoryBits;
fixtureDef.userData.maskBits = filterSettings.maskBits;
}
else {
fixtureDef.userData.categoryBits = this.body.GetFixtureList().GetFilterData().categoryBits;
fixtureDef.userData.maskBits = this.body.GetFixtureList().GetFilterData().maskBits;
}
fixtureDef.filter.categoryBits = ig.Filter.NOCOLLIDE;
fixtureDef.filter.maskBits = ig.Filter.NOCOLLIDE;
fixtureDef.isSensor = true;
this.body.CreateFixture(fixtureDef);
},
//set a sensor fixture as the solid fixture that represents the entity. Automatically turns the current solid fixture into a sensor (standby).
setDim: function(name) {
var fix = this.body.GetFixtureList();
var curr = null;
var next = null;
do {
if (fix.GetUserData().name == name) {
next = fix;
}
if (fix.GetUserData().name == this.currentDim) {
curr = fix;
}
if (next && curr) {
break;
}
} while (fix = fix.GetNext());
if (next && curr) {
next.SetDensity(curr.GetDensity()); //should actually set to a density that sets the same mass
curr.SetSensor(true);
next.SetSensor(false);
curr.SetDensity(0);
this.currentDim = name;
this.currentFix = next;
var filt = curr.GetFilterData();
filt.categoryBits = ig.Filter.NOCOLLIDE;
filt.maskBits = ig.Filter.NOCOLLIDE;
curr.SetFilterData(filt);
filt = next.GetFilterData();
filt.categoryBits = next.GetUserData().categoryBits;
filt.maskBits = next.GetUserData().maskBits;
next.SetFilterData(filt);
}
else {
//PANIC
console.log("PANIC");
}
},
makeSense: function(name, senseObj) {
var shapeDef = new Box2D.Collision.Shapes.b2PolygonShape();
shapeDef.SetAsOrientedBox(senseObj.size.x*Box2D.SCALE/2, senseObj.size.y*Box2D.SCALE/2, new Box2D.Common.Math.b2Vec2(senseObj.pos.x*Box2D.SCALE, senseObj.pos.y*Box2D.SCALE), 0);
var fixtureDef = new Box2D.Dynamics.b2FixtureDef();
fixtureDef.shape = shapeDef;
fixtureDef.density = 0; //massless sensor
fixtureDef.friction = 0;
fixtureDef.restitution = 0;
fixtureDef.userData = {name: name, categoryBits: senseObj.categoryBits, maskBits: senseObj.maskBits, type: 'sense'};
fixtureDef.filter.categoryBits = senseObj.categoryBits;
fixtureDef.filter.maskBits = senseObj.maskBits;
fixtureDef.isSensor = true;
senseObj.fixture = this.body.CreateFixture(fixtureDef);
console.log(senseObj.fixture.GetFilterData());
},
getFirstNonSensor: function() {
for (var fix = this.body.GetFixtureList(); fix; fix = fix.GetNext()) {
if (!fix.IsSensor()) {
return fix;
}
}
return null;
},
//dump all fixture info to console
_dumpFixtureData: function() {
console.log("***FIXTURE DUMP***");
for (var fix = this.body.GetFixtureList(); fix; fix = fix.GetNext()) {
console.log(fix);
}
console.log("***END FIX DUMP***");
},
//draw all non-sensor, massive fixtures associated with this entity
_debugDraw: function() {
for (var fix = this.body.GetFixtureList(); fix; fix = fix.GetNext()) {
if (!fix.IsSensor() && fix.GetDensity()) {
this._debugDrawFixture(fix, 0);
}
}
},
//draw all fixtures associated with this entity, regardless of status
_debugDrawAll: function() {
for (var fix = this.body.GetFixtureList(); fix; fix = fix.GetNext()) {
this._debugDrawFixture(fix, 0);
}
},
//draw the given fixture, using the second parameter to generate a random outline color
//guess we ignore colorRand for now...
//currently only works for 4 vertex box shapes
//WILL NOT ERROR CHECK. The function will only work if the fixture's shape is an axially aligned box
_debugDrawFixture: function(fix, colorRand) {
if (!fix.GetUserData().color) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
fix.SetUserData({name: fix.GetUserData().name,
color: { r: r, g: g, b:b}
});
}
var color = fix.GetUserData().color;
ig.system.context.strokeStyle = 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + "," + '1)';
//figure out where we need to draw this box...
var bodyPos = this.body.GetPosition(); //center and scaled
var fixShape = fix.GetShape().GetVertices();
var width, height = null;
//lazy method to find width and height
for (var i = 0; i < fixShape.length; i++) {
for (var j = 0; j < fixShape.length; j++) {
if (i == j) continue;
if (fixShape[i].x == fixShape[j].x) {
if (height == null) {
height = Math.abs(fixShape[i].y - fixShape[j].y)/ Box2D.SCALE;
}
}
if (fixShape[i].y == fixShape[j].y) {
if (width == null) {
width = Math.abs(fixShape[i].x - fixShape[j].x)/ Box2D.SCALE;
}
}
}
}
var worldPos = {
x: (bodyPos.x/Box2D.SCALE) - width/2,
y: (bodyPos.y/Box2D.SCALE) - height/2,
};
//console.log("Drawing rect @ ", worldPos);
//console.log("Body position @ ", this.pos);
ig.system.context.strokeRect(
ig.system.getDrawPos(worldPos.x - ig.game.screen.x),
ig.system.getDrawPos(worldPos.y - ig.game.screen.y),
ig.system.getDrawPos(width),
ig.system.getDrawPos(height)
);
},
draw: function() {
this.parent();
if (this._debugD) {
this._debugDraw();
}
},
//spawn an entity @ local body coordinates rather than world coordinates
//x and y are already scaled (in pixels). Technically not local coords then
localSpawnEntity: function(entityType, x, y, settings) {
var worldX = this.body.GetPosition().x + x;
var worldY = this.body.GetPosition().y + y;
ig.game.spawnEntity(entityType, worldX, worldY, settings);
},
//passthrough
//some serious issues with getting rid of bodies...
kill: function() {
this.parent();
if (this.body && this._killed) {
ig.game.entityKillList.push(this.body);
}
},
update: function() {
this.parent();
},
//left = 1
//right = 2
//just checks if the current setup would result in cover
//unit is responsible for making sure all other conditions are met
checkCover: function() {
var result = 0;
if (this._checkCoverRight()) {
result += 2;
}
if (this._checkCoverLeft()) {
result +=1;
}
return result;
},
_checkCoverRight: function() {
var leading = {x: this.pos.x + this.size.x, y: this.pos.y + this.size.y};
var checkCoord = tileUtil.pxToTile(leading.x, leading.y);
checkCoord.tX += 1;
var pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 1 ) { //only regular solid blocks for now
return false;
}
if (pixelCoord.pX - (this.pos.x + this.size.x) > 8) {
return false;
}
checkCoord.tY -= 1;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 0) { //only totally blank spaces for now
return false;
}
checkCoord.tX -= 1;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 0) {
return false;
}
//underneath
checkCoord.tY += 2;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 1) {
return false;
}
return true;
},
//almost carbon copy!
_checkCoverLeft: function() {
var leading = {x: this.pos.x, y: this.pos.y + this.size.y};
var checkCoord = tileUtil.pxToTile(leading.x, leading.y);
checkCoord.tX -= 1;
var pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 1 ) { //only regular solid blocks for now
return false;
}
if (this.pos.x - pixelCoord.pX > 24) {
return false;
}
checkCoord.tY -= 1;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 0) { //only totally blank spaces for now
return false;
}
checkCoord.tX += 1;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 0) {
return false;
}
//underneath
checkCoord.tY += 2;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 1) {
return false;
}
return true;
},
});
}); |
import Ember from 'ember';
export default Ember.Mixin.create({
reduxStore: Ember.inject.service(),
dispatch(action) {
return this.get('reduxStore').dispatch(action);
},
dispatchAction(actionName, ...args) {
return this.dispatch(this.action(actionName).apply(this, args));
},
getState(path) {
return path ?
this.get(`reduxStore.state.${path}`) :
this.get('reduxStore.state');
},
action(actionName) {
if (!this.reduxActions[actionName]) {throw new Error(`No redux action found for ${actionName}`);}
return this.reduxActions[actionName].bind(this);
},
});
|
const gulp = require('gulp');
const nodemon = require('gulp-nodemon');
const mocha = require('gulp-spawn-mocha');
gulp.task('start', () => {
nodemon({
script: 'server.js',
ext: 'html js ejs css',
ignore: ['node_modules'],
})
.on('restart', () => {
console.log('restarted')
});
});
gulp.task('test', () => {
return gulp.src('test/test.js', {read: false})
.pipe(mocha({
// report 종류
R: 'spec',
}));
});
|
/**
* @license Copyright (c) 2012, Viet Trinh All Rights Reserved.
* Available via MIT license.
*/
/**
* An authorizeation interceptor used to determine if the user can access the given resource.
*/
define([ 'framework/controller/interceptor/i_interceptor',
'framework/core/utils/clazz',
'framework/core/deferred/deferred' ],
function(IInterceptor,
ClazzUtils,
Deferred)
{
var AuthorizationInterceptor = function()
{
IInterceptor.call(this);
return this;
}
AuthorizationInterceptor.prototype = new IInterceptor();
ClazzUtils.generateProperties(AuthorizationInterceptor);
// @override
AuthorizationInterceptor.prototype.before = function(requestContext)
{
var controller = requestContext.getController(),
secured = controller.getSecured && controller.getSecured() === true,
securedAdmin = controller.getSecuredAdmin && controller.getSecuredAdmin() === true,
stateService = requestContext.getStateService();
// If this controller is secured and there's no user logged in, then fail.
if ((secured || securedAdmin) && (!stateService.getCurrentUser() || !stateService.getCurrentUser().getId()))
{
requestContext.setStatusCode(401);
requestContext.setErrorMessage('Unauthorized Access! Please log in to access the given resource.');
return Deferred.rejectedPromise(requestContext);
}
// If this controller is secured admin and the user doesn't have access priveledges.
else if (securedAdmin && stateService.getCurrentUser().getIsAdmin() !== true)
{
requestContext.setStatusCode(403);
requestContext.setErrorMessage('Unauthorized Access! You are not allowed to access the given resource.');
return Deferred.rejectedPromise(requestContext);
}
// Assumes this function doesn't fail.
return Deferred.resolvedPromise(requestContext);
};
// @override
AuthorizationInterceptor.prototype.after = function(requestContext)
{
return Deferred.resolvedPromise(requestContext);
};
return AuthorizationInterceptor;
}); |
var pkg = require('./package.json'),
gulp = require('gulp'),
gutil = require('gulp-util'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
livereload = require('gulp-livereload'),
rename = require('gulp-rename'),
coffeelint = require('gulp-coffeelint'),
jade = require('gulp-jade'),
mainBowerFiles = require('main-bower-files'),
filter = require('gulp-filter'),
less = require('gulp-less'),
autoprefixer = require('gulp-autoprefixer'),
minify = require('gulp-minify-css'),
inject = require('gulp-inject'),
ignore = require('gulp-ignore');
gulp.task('default', ['coffee', 'jade', 'bower', 'less']);
gulp.task('coffee', function() {
return gulp.src('src/coffee/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter())
.pipe(coffee({ bare:true }).on('error', gutil.log))
.pipe(concat(pkg.name + '.all.js'))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulp.dest('public/js'))
.pipe(livereload({ auto: false }));
});
gulp.task('jade', function() {
return gulp.src('src/jade/**/*.jade')
.pipe(jade({ pretty: true }).on('error', gutil.log))
.pipe(gulp.dest('public'))
.pipe(livereload({ auto: false }));
});
gulp.task('bower', function() {
var jsFilter = filter('*.js');
var cssFilter = filter('*.css');
return gulp.src(mainBowerFiles())
.pipe(cssFilter)
.pipe(gulp.dest('public/css/vendor'))
.pipe(cssFilter.restore())
.pipe(jsFilter)
.pipe(gulp.dest('public/js/vendor'));
});
gulp.task('less', function() {
return gulp.src('src/less/style.less')
.pipe(less().on('error', gutil.log))
.pipe(autoprefixer("last 2 versions", "> 5%", "ie 8"))
.pipe(minify())
.pipe(rename(pkg.name + '.min.css'))
.pipe(gulp.dest('public/css/'))
.pipe(livereload({ auto: false }));
});
gulp.task('inject', function() {
gulp.src('src/jade/base.jade')
.pipe(inject(
gulp.src(['public/**/*.css', 'public/**/*.js'], { read: false })
.pipe(ignore(['**/normalize.css', '**/modernizr.js', '**/jquery.min.js'])), { ignorePath: 'public' }
))
.pipe(gulp.dest('src/jade'));
});
gulp.task('watch', function() {
livereload.listen();
gulp.watch('src/coffee/*.coffee', ['coffee']);
gulp.watch('src/jade/*.jade', ['jade']);
gulp.watch('src/less/*.less', ['less']);
}); |
const Card = require('./src/main');
Card.install = function(Vue) {
Vue.component(Card.name, Card);
};
module.exports = Card;
|
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */
/**
* Base object for objects that are using properites to flow updates through the application.
*/
dbm.registerClass("dbm.core.FlowBaseObject", "dbm.core.BaseObject", function(objectFunctions, staticFunctions, ClassReference) {
//console.log("dbm.core.FlowBaseObject");
//"use strict";
//Self reference
var FlowBaseObject = dbm.importClass("dbm.core.FlowBaseObject");
//Error report
var ErrorManager = dbm.importClass("dbm.core.globalobjects.errormanager.ErrorManager");
var ReportTypes = dbm.importClass("dbm.constants.error.ReportTypes");
var ReportLevelTypes = dbm.importClass("dbm.constants.error.ReportLevelTypes");
//Dependencies
var Property = dbm.importClass("dbm.core.objectparts.Property");
var GhostProperty = dbm.importClass("dbm.core.objectparts.GhostProperty");
var UpdateFunction = dbm.importClass("dbm.core.objectparts.UpdateFunction");
var UpdateFunctionWithArguments = dbm.importClass("dbm.core.objectparts.UpdateFunctionWithArguments");
var NamedArray = dbm.importClass("dbm.utils.data.NamedArray");
//Utils
var VariableAliases = dbm.importClass("dbm.utils.data.VariableAliases");
//Constants
/**
* Constructor
*/
objectFunctions._init = function() {
//console.log("dbm.core.FlowBaseObject::_init");
this.superCall();
this.__nodeId = (dbm.singletons.dbmIdManager) ? dbm.singletons.dbmIdManager.getNewId(this.__className) : this.__className;
this._properties = this.addDestroyableObject(NamedArray.create(true));
this._updateFunctions = this.addDestroyableObject(NamedArray.create(true));
return this;
};
objectFunctions.createUpdateFunction = function(aName, aUpdateFunction, aInputsArray, aOutputsArray) {
var newUpdateFunction = UpdateFunction.create(this, aUpdateFunction, aInputsArray, aOutputsArray);
newUpdateFunction.name = this.__nodeId + "::" + aName + "(f)";
this._updateFunctions.addObject(aName, newUpdateFunction);
return newUpdateFunction;
};
objectFunctions.createUpdateFunctionWithArguments = function(aName, aUpdateFunction, aInputsArray, aOutputsArray) {
var newUpdateFunction = UpdateFunctionWithArguments.create(this, aUpdateFunction, aInputsArray, aOutputsArray);
newUpdateFunction.name = this.__nodeId + "::" + aName + "(f)";
this._updateFunctions.addObject(aName, newUpdateFunction);
return newUpdateFunction;
};
objectFunctions.createGhostUpdateFunction = function(aName, aInputsArray, aOutputsArray) {
var newUpdateFunction = UpdateFunction.createGhostFunction(aInputsArray, aOutputsArray);
newUpdateFunction.name = this.__nodeId + "::" + aName + "(gf)";
this._updateFunctions.addObject(aName, newUpdateFunction);
return newUpdateFunction;
};
/**
* Creates (and adds) a property on this object.
*
* @param aName String The name of the property.
* @param aValue * The value that the property should have.
*
* @return Property The newly created property.
*/
objectFunctions.createProperty = function(aName, aValue) {
//console.log("dbm.core.FlowBaseObject::createProperty");
//console.log(aName, aValue);
var newProperty = Property.create(aValue);
newProperty.name = this.__nodeId + "::" + aName;
this._properties.addObject(aName, newProperty);
return newProperty;
};
/**
* Adds a property to this object.
*
* @param aName String The name of the property.
* @param aProperty Property The property to add.
*
* @return Property The property that is passed in.
*/
objectFunctions.addProperty = function(aName, aProperty) {
//console.log("dbm.core.FlowBaseObject::addProperty");
//console.log(aName, aProperty);
aProperty.name = this.__nodeId + "::" + aName;
this._properties.addObject(aName, aProperty);
//console.log("//dbm.core.FlowBaseObject::addProperty");
return aProperty;
};
/**
* Creates (and adds) a ghost property (a property without value) on this object.
*
* @param aName String The name of the property.
*
* @return GhostProperty The newly created property.
*/
objectFunctions.createGhostProperty = function(aName) {
//console.log("dbm.core.FlowBaseObject::createGhostProperty");
var newProperty = GhostProperty.create();
newProperty.name = this.__nodeId + "::" + aName + "(g)";
this._properties.addObject(aName, newProperty);
return newProperty;
};
/**
* Gets a property by name.
*
* @param aName String The name of the property.
*
* @return Property The property that matches the name. Null if property doesn't exist.
*/
objectFunctions.getProperty = function(aName) {
//console.log("dbm.core.FlowBaseObject::getProperty");
//console.log(this, aName);
if(this._properties !== null && this._properties.select(aName)) {
return this._properties.currentSelectedItem;
}
ErrorManager.getInstance().report(ReportTypes.ERROR, ReportLevelTypes.NORMAL, this, "getProperty", "Property " + aName + " doesn't exist on " + this + ".");
return null;
};
/**
* Checks if a property exists.
*
* @param aName String The name of the property.
*
* @return Boolean True if property exist.
*/
objectFunctions.hasProperty = function(aName) {
//console.log("dbm.core.FlowBaseObject::hasProperty");
//console.log(this, aName);
return (this._properties !== null && this._properties.select(aName));
};
/**
* Gets an update function on this object.
*
* @param aName String The name of the update function to get.
*
* @return UpdateFunction The update function that matches the name. Null if update function doesn't exist.
*/
objectFunctions.getUpdateFunction = function(aName) {
//console.log("dbm.core.FlowBaseObject::getUpdateFunction");
//console.log(this, aName);
if(this._updateFunctions.select(aName)) {
return this._updateFunctions.currentSelectedItem;
}
ErrorManager.getInstance().report(ReportTypes.ERROR, ReportLevelTypes.NORMAL, this, "getUpdateFunction", "Update function " + aName + " doesn't exist on " + this + ".");
return null;
};
/**
* Set the value to a property, or connects the input if it is a property.
*
* @param aName String The name of the property to set.
* @param aInput Property|* The value to set or the property to connect.
*
* @return self
*/
objectFunctions.setPropertyInput = function(aName, aInput) {
var theProperty = this.getProperty(aName);
if(theProperty === null) {
ErrorManager.getInstance().report(ReportTypes.ERROR, ReportLevelTypes.NORMAL, this, "setPropertyInput", "Property " + aName + " doesn't exist.");
return this;
}
dbm.singletons.dbmFlowManager.setPropertyInput(theProperty, aInput);
return this;
};
/**
* Set the value to a property, or connects the input if it is a property. Current value is not overridden if input is null/undefined.
*
* @param aName String The name of the property to set.
* @param aInput Property|* The value to set or the property to connect.
*
* @return self
*/
objectFunctions.setPropertyInputWithoutNull = function(aName, aInput) {
if(VariableAliases.isSet(aInput)) {
this.setPropertyInput(aName, aInput);
}
return this;
};
/**
* Gets the parameters for this class. Part of the toString function.
*
* @param aReturnArray Array The array that gets filled with the parameters description.
*/
objectFunctions._toString_getAttributes = function(aReturnArray) {
this.superCall(aReturnArray);
if(this._properties !== null && this._properties !== undefined) {
aReturnArray.push("properties: [" + this._properties.getNamesArray().join(", ") + "]");
}
};
/**
* Sets all the references to null. Part of the destroy function.
*/
objectFunctions.setAllReferencesToNull = function() {
this._properties = null;
this._updateFunctions = null;
this.superCall();
};
}); |
(function(exports) {
function changeSky(location) {
var sky = document.getElementById("image-360");
sky.setAttribute('src', location);
}
function addMonolith() {
var box = document.createElement('a-box');
document.querySelector('a-scene').appendChild(box);
box.setAttribute('id', 'monolith');
box.setAttribute('color', '#222');
box.setAttribute('width', '0.5');
box.setAttribute('height', '4');
box.setAttribute('depth', '2');
box.setAttribute('position', '-5 2 0');
box.setAttribute('scale', '0.4 0.4 0.4');
}
function removeMonolith() {
var element = document.getElementById('monolith');
element.parentNode.removeChild(element);
}
function addRain() {
var element = document.getElementById('scene')
console.log(element)
element.setAttribute('rain', '');
}
function stopRain() {
var element = document.getElementById('scene')
element.removeAttribute('rain', '');
}
exports.addRain = addRain;
exports.stopRain = stopRain;
exports.addMonolith = addMonolith;
exports.removeMonolith = removeMonolith;
exports.changeSky = changeSky;
})(this);
(function(exports) {
function captureToken(token) {
var database = firebase.database();
var browserTokens = database.ref('browserTokens')
var data = {
timestamp: Date.now(),
token: token
};
browserTokens.push(data, finished)
};
function finished(error) {
if (error) {
console.log('Did not save to DB' + error);
} else {
console.log('Browser token saved to DB');
}
}
exports.captureToken = captureToken
})(this);
|
function injectScript(file, node) {
var th = document.getElementsByTagName(node)[0];
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', file);
th.appendChild(s);
}
function injectStyle(file, node) {
var th = document.getElementsByTagName(node)[0];
var s = document.createElement('link');
s.setAttribute('type', 'text/css');
s.setAttribute('href', file);
s.setAttribute('rel', "stylesheet");
th.appendChild(s);
}
injectScript(chrome.extension.getURL("js/page-scripts.js"), "body");
injectStyle(chrome.extension.getURL("css/page-styles.css"), "body");
injectStyle("https://fonts.googleapis.com/css?family=Oxygen:400,700,300", "body");
chrome.storage.sync.get("backImgTog", function(storage) {
if (storage.backImgTog == undefined || !storage.backImgTog) {
$.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US", function(response) {
var url = "https://www.bing.com" + response.images[0].url;
$(window).trigger('resize');
$("#authenticate").css("background-image", "url(" + url + ")");
});
}
});
$(document).ready(function() {
$("form[name=authenticate] fieldset input[type=submit]").val("Login");
console.log("SchedulesPlus Ready!");
});
|
// Get User's Coordinate from their Browser
window.onload = function() {
// HTML5/W3C Geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(UserLocation);
}
// Default to Washington, DC
else
NearestCity(38.8951, -77.0367);
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation(position) {
NearestCity(position.coords.latitude, position.coords.longitude);
}
// Convert Degress to Radians
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
var lat = 20; // user's latitude
var lon = 40; // user's longitude
var cities = [
["3","Aachen","50.782659","6.094087","202","Nordrhein-Westfalen"],
["44","Großenkneten","52.933541","8.236997","43.5","Niedersachsen"],
["73","Aldersbach-Kriestorf","48.615935","13.050595","340","Bayern"],
["78","Alfhausen","52.485314","7.912553","65","Niedersachsen"],
["91","Alsfeld-Eifa","50.744591","9.344972","300","Hessen"],
["142","Altomünster-Maisbrunn","48.406038","11.311716","510","Bayern"],
["150","Alzey","49.7273","8.116356","215","Rheinland-Pfalz"],
["151","Amberg-Unterammersricht","49.469064","11.854641","383","Bayern"],
["164","Angermünde","53.031601","13.99066","54","Brandenburg"],
["183","Arkona","54.67916","13.434252","42","Mecklenburg-Vorpommern"],
["198","Artern","51.374461","11.291977","164","Thüringen"],
["217","Attenkam","47.877407","11.364245","672","Bayern"],
["232","Augsburg","48.425393","10.942011","461.4","Bayern"],
["243","Aurich","53.462052","7.466971","4","Niedersachsen"],
["257","Baden-Baden-Geroldsau","48.72696","8.245757","240","Baden-Württemberg"],
["282","Bamberg","49.874176","10.920581","240","Bayern"],
["298","Barth","54.340582","12.710828","3","Mecklenburg-Vorpommern"],
["320","Heinersreuth-Vollhof","49.96667","11.519692","350","Bayern"],
["330","Beerfelden","49.561729","8.967329","450","Hessen"],
["377","BadBergzabern","49.107025","7.996749","252","Rheinland-Pfalz"],
["400","Berlin-Buch","52.630941","13.50215","60","Berlin"],
["403","Berlin-Dahlem(FU)","52.453711","13.301731","51","Berlin"],
["427","Berlin-Schönefeld","52.380698","13.530609","46","Brandenburg"],
["430","Berlin-Tegel","52.564412","13.308848","36","Berlin"],
["433","Berlin-Tempelhof","52.467488","13.402115","48","Berlin"],
["435","Berlin-Zehlendorf","52.428902","13.232686","45","Berlin"],
["450","Bernkastel-Kues","49.9186","7.0664","120","Rheinland-Pfalz"],
["502","Bischbrunn","49.874669","9.48829","412","Bayern"],
["591","Boizenburg","53.391084","10.687761","45","Mecklenburg-Vorpommern"],
["596","Boltenhagen","54.002806","11.190772","15","Mecklenburg-Vorpommern"],
["614","Borgentreich-Bühne","51.570874","9.311999","240","Nordrhein-Westfalen"],
["648","Brande-Hörnerkirchen","53.855114","9.71521","9","Schleswig-Holstein"],
["662","Braunschweig","52.291443","10.446456","81.2","Niedersachsen"],
["691","Bremen","53.045015","8.797904","4.1","Bremen"],
["701","Bremerhaven","53.533162","8.576083","7","Bremen"],
["722","Brocken","51.79862","10.618265","1133.9","Sachsen-Anhalt"],
["755","Buchen; Kr.Neckar-Odenwald","49.518196","9.32127","340","Baden-Württemberg"],
["807","Schlüsselfeld(Kläranlage)","49.74499","10.643423","290","Bayern"],
["817","Burgwald-Bottendorf","51.030634","8.814579","293","Hessen"],
["850","Celle","52.595933","10.029573","39","Niedersachsen"],
["853","Chemnitz","50.791286","12.871977","418","Sachsen"],
["863","Clausthal-Zellerfeld","51.790354","10.347039","585","Niedersachsen"],
["880","Cottbus","51.775983","14.316811","69","Brandenburg"],
["891","Cuxhaven","53.871254","8.705821","5","Niedersachsen"],
["963","Diepholz","52.588112","8.342405","37.7","Niedersachsen"],
["979","Dillenburg","50.736371","8.267238","314","Hessen"],
["982","Dillingen/Donau","48.570123","10.498459","420","Bayern"],
["1001","Doberlug-Kirchhain","51.645104","13.574676","96.8","Brandenburg"],
["1048","Dresden-Klotzsche","51.127955","13.754338","227","Sachsen"],
["1078","Düsseldorf","51.295952","6.768648","36.6","Nordrhein-Westfalen"],
["1103","Ebersberg-Halbing","48.100186","11.987154","592","Bayern"],
["1107","Ebrach","49.851977","10.499043","346","Bayern"],
["1197","Ellwangen-Rindelbach","48.989498","10.131234","460","Baden-Württemberg"],
["1224","Emmendingen-Mundingen","48.137756","7.835089","201","Baden-Württemberg"],
["1266","Erfde","54.299212","9.316185","18","Schleswig-Holstein"],
["1270","Erfurt-Weimar","50.982859","10.960808","316","Thüringen"],
["1279","Möhrendorf-Kleinseebach","49.649744","11.007445","268","Bayern"],
["1292","Eschenbach/Oberpfalz","49.752196","11.822151","470","Bayern"],
["1297","Eschwege","51.204132","10.013767","156","Hessen"],
["1303","Essen-Bredeney","51.404085","6.967741","150","Nordrhein-Westfalen"],
["1327","Weilerswist-Lommersum","50.711886","6.790489","147","Nordrhein-Westfalen"],
["1332","Falkenberg; Kr.Rottal-Inn","48.48315","12.724108","472","Bayern"],
["1346","Feldberg/Schwarzwald","47.874893","8.003817","1489.6","Baden-Württemberg"],
["1357","Fichtelberg/Oberfranken-Hüttstadl","49.98069","11.837637","654","Bayern"],
["1358","Fichtelberg","50.428346","12.953506","1213","Sachsen"],
["1420","Frankfurt/Main","50.025911","8.521294","99.7","Hessen"],
["1443","Freiburg","48.023276","7.834441","236.3","Baden-Württemberg"],
["1451","Freiburg/Elbe","53.827696","9.249276","2","Niedersachsen"],
["1468","Freudenstadt","48.453728","8.409057","796.5","Baden-Württemberg"],
["1503","Friesoythe-Altenoythe","53.064299","7.902205","5.7","Niedersachsen"],
["1526","Fulda-Horas","50.566806","9.65325","242","Hessen"],
["1544","Gardelegen","52.512914","11.394131","47","Sachsen-Anhalt"],
["1550","Garmisch-Partenkirchen","47.48305","11.062293","719","Bayern"],
["1580","Geisenheim","49.985931","7.954853","110.2","Hessen"],
["1590","Geldern-Walbeck","51.494168","6.246343","37","Nordrhein-Westfalen"],
["1612","Gera-Leumnitz","50.881268","12.128858","311","Thüringen"],
["1619","Gernsheim","49.761079","8.487637","90","Hessen"],
["1639","Gießen/Wettenberg","50.601706","8.643902","202.7","Hessen"],
["1645","Gilserberg-Moischeid","50.965565","9.050014","340","Hessen"],
["1667","Glückstadt","53.79702","9.429456","1","Schleswig-Holstein"],
["1684","Görlitz","51.162151","14.950565","238","Sachsen"],
["1691","Göttingen","51.500331","9.950566","167","Niedersachsen"],
["1735","Grainet-Rehberg","48.789321","13.62911","628","Bayern"],
["1757","Greifswald","54.096736","13.405576","2","Mecklenburg-Vorpommern"],
["1803","GroßLüsewitz","54.071372","12.32378","34","Mecklenburg-Vorpommern"],
["1832","GroßerArber","49.113037","13.134204","1436","Bayern"],
["1920","Hagen-Fley","51.412887","7.489477","100","Nordrhein-Westfalen"],
["1975","Hamburg-Fuhlsbüttel","53.633187","9.988085","11","Hamburg"],
["1981","Hamburg-Neuwiedenthal","53.477658","9.895686","3","Hamburg"],
["1990","Hamburg-Wandsbek","53.585347","10.129348","18","Hamburg"],
["1993","Hameln","52.084784","9.389576","68","Niedersachsen"],
["2014","Hannover","52.464425","9.677917","55","Niedersachsen"],
["2074","Hechingen","48.375139","8.980076","522","Baden-Württemberg"],
["2080","Heidelberg","49.420618","8.667613","110","Baden-Württemberg"],
["2110","Heinsberg-Schleiden","51.041072","6.104239","57","Nordrhein-Westfalen"],
["2115","Helgoland","54.174957","7.891954","4","Schleswig-Holstein"],
["2120","Helmstedt","52.216409","11.02193","140","Niedersachsen"],
["2147","Herford","52.126408","8.68649","77","Nordrhein-Westfalen"],
["2167","Niederwörresbach","49.767176","7.335605","302","Rheinland-Pfalz"],
["2171","BadHersfeld","50.851917","9.737819","272.2","Hessen"],
["2173","Herten","51.588967","7.154827","60","Nordrhein-Westfalen"],
["2206","Hildesheim","52.140812","9.883806","117","Niedersachsen"],
["2211","Hilgenroth","50.737065","7.652755","295","Rheinland-Pfalz"],
["2250","Höllenstein(Kraftwerk)","49.127875","12.864512","403","Bayern"],
["2260","Hof(Stadt)","50.323032","11.907729","474","Bayern"],
["2261","Hof","50.312236","11.876052","565.1","Bayern"],
["2268","Hofheim","50.135244","10.515636","263","Bayern"],
["2290","Hohenpeißenberg","47.800864","11.010754","977","Bayern"],
["2303","Hohn","54.314596","9.538997","10","Schleswig-Holstein"],
["2306","Hohwacht","54.319391","10.673193","8","Schleswig-Holstein"],
["2319","Holzkirchen","47.882278","11.69615","685","Bayern"],
["2324","Holzminden-Silberborn","51.765853","9.544662","440","Niedersachsen"],
["2480","Kahl/Main","50.064313","8993","107","Bayern"],
["2483","KahlerAsten","51.180254","8.489068","839","Nordrhein-Westfalen"],
["2497","Kall-Sistig","50.50141","6.526408","505","Nordrhein-Westfalen"],
["2522","Karlsruhe","49.038161","8.36406","111.6","Baden-Württemberg"],
["2532","Kassel","51.296303","9.442424","231","Hessen"],
["2542","Kaufbeuren","47.865204","10.600653","716","Bayern"],
["2543","Kaufering","48.09158","10.860913","585","Bayern"],
["2559","Kempten","47.723259","10.334797","705.2","Bayern"],
["2597","BadKissingen","50.224063","10.079213","281.8","Bayern"],
["2600","Kitzingen","49.736304","10.178117","188","Bayern"],
["2601","KleinerFeldberg/Taunus","50.221815","8.446877","825.6","Hessen"],
["2629","Kleve","51.761242","6.095381","46","Nordrhein-Westfalen"],
["2638","Klippeneck","48.105371","8.754878","973.4","Baden-Württemberg"],
["2657","Koblenz-Horchheim","50.336911","7.599165","85","Rheinland-Pfalz"],
["2667","Köln-Bonn","50.864559","7.157488","92","Nordrhein-Westfalen"],
["2680","BadKönigshofen","50284","10.4456","288","Bayern"],
["2700","Kösching","48.830189","11.487243","416","Bayern"],
["2712","Konstanz","47.677419","9.190052","442.5","Baden-Württemberg"],
["2750","Kronach","50.252336","11.32093","312","Bayern"],
["2812","Lahr","48.364697","7.828016","155","Baden-Württemberg"],
["2814","Merklingen","48.512126","9.764464","685","Baden-Württemberg"],
["2925","Leinefelde","51.393291","10.312345","356","Thüringen"],
["2928","Leipzig-Holzhausen","51.315067","12.446226","138","Sachsen"],
["2932","Leipzig/Halle","51.43479","12.239622","131","Sachsen"],
["2947","Lennestadt-Theten","51.133253","8.034831","286","Nordrhein-Westfalen"],
["2950","Lensahn","54.218979","10.884417","14","Schleswig-Holstein"],
["2968","Köln-Stammheim","50.989428","6.977688","43","Nordrhein-Westfalen"],
["3015","Lindenberg","52.208491","14.117973","98","Brandenburg"],
["3018","Lindenfels-Winterkasten","49.711685","8.780395","445","Hessen"],
["3023","Lingen","52.518093","7.308057","22","Niedersachsen"],
["3028","BadLippspringe","51.785459","8.838777","157","Nordrhein-Westfalen"],
["3031","Lippstadt-Bökenförde","51.633617","8.39445","92","Nordrhein-Westfalen"],
["3032","ListaufSylt","55.010989","8.412531","24.7","Schleswig-Holstein"],
["3093","Lüchow","52.972375","11.137388","17","Niedersachsen"],
["3126","Magdeburg","52.102889","11.582678","76","Sachsen-Anhalt"],
["3137","Mainz-Lerchenberg(ZDF)","49.965563","8.213852","195","Rheinland-Pfalz"],
["3155","Manderscheid-Sonnenhof","50.101542","6.800909","413","Rheinland-Pfalz"],
["3167","BadMarienberg","50.662025","7.960193","546.6","Rheinland-Pfalz"],
["3196","Marnitz","53.322288","11.931949","81","Mecklenburg-Vorpommern"],
["3231","Meiningen","50.561159","10.377105","450","Thüringen"],
["3244","Memmingen","47.982038","10.138397","615","Bayern"],
["3257","Mergentheim; Bad-Neunkirchen","49.477317","9.762223","250","Baden-Württemberg"],
["3271","Metten","48.854761","12.918851","313","Bayern"],
["3307","Mittenwald-Buckelwiesen","47.477882","11.265305","981","Bayern"],
["3366","Mühldorf","48.279069","12.502379","405.6","Bayern"],
["3376","Müncheberg","52.517588","14.123226","63","Brandenburg"],
["3379","München-Stadt","48.163142","11.542922","515.2","Bayern"],
["3402","Münsingen-Apfelstetten","48.385066","9.483693","750","Baden-Württemberg"],
["3490","Neuenahr; Bad-Ahrweiler","50.534561","7.085337","111","Rheinland-Pfalz"],
["3509","Menz","53.101974","13.042072","77","Brandenburg"],
["3527","Neukirchen-Hauptschwenda","50.89228","9.40498","500","Hessen"],
["3537","Neumünster","54.087289","9.979065","26","Schleswig-Holstein"],
["3552","Neuruppin","52.903704","12.807205","38","Brandenburg"],
["3578","Regensburg-Burgweinting","48.983186","12.144318","341","Bayern"],
["3612","Nienburg","52.671083","9.22291","25","Niedersachsen"],
["3621","Reimlingen","48.825254","10.506667","435","Bayern"],
["3631","Norderney","53.712302","7.151921","11","Niedersachsen"],
["3640","Nordhorn-Blanke","52.412368","7.063994","24","Niedersachsen"],
["3667","Nürnberg-Netzstall","49.425781","11.253831","368","Bayern"],
["3668","Nürnberg","49.503031","11.054923","314","Bayern"],
["3730","Oberstdorf","47.398578","10.275988","806","Bayern"],
["3739","Oberviechtach","49.452098","12.436557","596","Bayern"],
["3761","Öhringen","49.207046","9.517492","275.9","Baden-Württemberg"],
["3811","Oschatz","51.295965","13.092837","150","Sachsen"],
["3875","Parsberg/Oberpfalz-Eglwang","49.15102","11.689638","549","Bayern"],
["3927","Pfullendorf","47.934445","9.28694","630","Baden-Württemberg"],
["3939","Pirmasens","49.191191","7.5879","385","Rheinland-Pfalz"],
["3987","Potsdam","52.381287","13.062229","81","Brandenburg"],
["4063","Rahden-Kleinendorf","52.446122","8.590574","40.5","Nordrhein-Westfalen"],
["4104","Regensburg","49.042357","12.102053","365.4","Bayern"],
["4169","Rheinau-Memprechtshofen","48.67025","7.993875","131","Baden-Württemberg"],
["4175","Rheinfelden","47.558997","7.772105","282","Baden-Württemberg"],
["4261","Rosenheim","47.87535","12.127954","444","Bayern"],
["4271","Rostock-Warnemünde","54.180279","12.080806","4","Mecklenburg-Vorpommern"],
["4278","RothbeiNürnberg","49.251149","11.093364","340","Bayern"],
["4287","RothenburgobderTauber","49.384842","10.173229","415","Bayern"],
["4318","Ruhpolding","47.731033","12.660966","692","Bayern"],
["4323","Ruppertsecken","49.646838","7.883741","461","Rheinland-Pfalz"],
["4336","Saarbrücken-Ensheim","49.212803","7.107712","320","Saarland"],
["4350","BadSäckingen","47.561928","7.939928","339","Baden-Württemberg"],
["4371","BadSalzuflen","52.104211","8.75208","134.6","Nordrhein-Westfalen"],
["4377","Sandberg","50.351741","10.003394","510","Bayern"],
["4393","SanktPeter-Ording","54.327918","8.602987","5","Schleswig-Holstein"],
["4411","Schaafheim-Schlierbach","49.919516","8.967138","155","Hessen"],
["4442","Schieder","51.911935","9.15332","155","Nordrhein-Westfalen"],
["4466","Schleswig","54.527539","9.548666","42.7","Schleswig-Holstein"],
["4501","Schmücke","50.654562","10.769332","937","Thüringen"],
["4508","Schneifelforsthaus","50.296848","6.419387","649","Rheinland-Pfalz"],
["4549","Schönwald/Schwarzwald","48.100168","8.196889","1021","Baden-Württemberg"],
["4560","Schotten","50.492508","9.122558","265","Hessen"],
["4592","Schwandorf","49.327832","12.087041","356","Bayern"],
["4597","Schwangau-Horn","47.576937","10.71814","792","Bayern"],
["4625","Schwerin","53.642521","11.387203","59","Mecklenburg-Vorpommern"],
["4642","Seehausen","52.891136","11.729697","21","Sachsen-Anhalt"],
["4651","Seesen","51.903973","10.188523","186","Niedersachsen"],
["4692","Siegen(Kläranlage)","50.853381","7.996614","229","Nordrhein-Westfalen"],
["4703","Sigmaringen-Laiz","48.071874","9.194248","580","Baden-Württemberg"],
["4706","Simbach/Inn","48.271874","13.027305","360","Bayern"],
["4745","Soltau","52.9604","9.79306","75.6","Niedersachsen"],
["4887","Stötten","48.665709","9.864648","733.8","Baden-Württemberg"],
["4896","Wagersrott","54.665383","9.805022","40","Schleswig-Holstein"],
["4926","Stuttgart(Neckartal)","48.789592","9.216739","224","Baden-Württemberg"],
["4928","Stuttgart(Schnarrenberg)","48.828188","9.200041","314.3","Baden-Württemberg"],
["4931","Stuttgart-Echterdingen","48.688307","9.223535","371","Baden-Württemberg"],
["5014","Worpswede-Hüttenbusch","53.275827","8.985687","7","Niedersachsen"],
["5017","Teuschnitz","50.400219","11.388904","633","Bayern"],
["5029","Tholey","49.473764","7.038578","385.9","Saarland"],
["5064","Tönisvorst","51.289722","6.443651","37","Nordrhein-Westfalen"],
["5100","Trier-Petrisberg","49.747889","6.658227","265","Rheinland-Pfalz"],
["5111","Trostberg","48.03111","12.53957","559","Bayern"],
["5142","Ueckermünde","53.744431","14.069699","1.2","Mecklenburg-Vorpommern"],
["5155","Ulm","48.383656","9.952422","566.8","Baden-Württemberg"],
["5165","Unterlüß","52.849932","10.289833","95","Niedersachsen"],
["5185","Uttenreuth","49.593309","11.070363","291","Bayern"],
["5229","Villingen-Schwenningen","48.045281","8.460835","720","Baden-Württemberg"],
["5279","Wahlsburg-Lippoldsberg","51.61941","9.57491","176","Hessen"],
["5280","Wittenborn","53.922412","10.226738","35","Schleswig-Holstein"],
["5361","Wartenberg-Angersbach","50.627083","9.441989","270","Hessen"],
["5371","Wasserkuppe","50.497345","9.942797","921","Hessen"],
["5397","Weiden","49.666262","12.184464","439.6","Bayern"],
["5426","Weinbiet","49.375835","8.121278","553","Rheinland-Pfalz"],
["5433","Weiskirchen/Saar","49.553365","6.811951","380","Saarland"],
["5440","Weißenburg-Emetzheim","49.011554","10.93081","439.3","Bayern"],
["5467","Wendelstein","47.703531","12.011857","1832","Bayern"],
["5540","Wiesbaden(Süd)","50.068132","8.260327","147","Hessen"],
["5610","Winterberg","51.196815","8.526821","681","Nordrhein-Westfalen"],
["5629","Wittenberg","51.889183","12.644523","105","Sachsen-Anhalt"],
["5654","Wörnitz-Bottenweiler","49.217848","10.229589","464","Bayern"],
["5664","Wolfach","48.295289","8.239094","291","Baden-Württemberg"],
["5676","Wolfsburg(Südwest)","52.396186","10.689225","82","Niedersachsen"],
["5692","Worms","49.605078","8.365906","88","Rheinland-Pfalz"],
["5705","Würzburg","49.770283","9.957723","268","Bayern"],
["5717","Wuppertal-Buchenhofen","51.224808","7.105335","130","Nordrhein-Westfalen"],
["5731","Wutöschingen-Ofteringen","47.678257","8.380129","398","Baden-Württemberg"],
["5745","Zehdenick","52.966353","13.326781","51","Brandenburg"],
["5779","Zinnwald-Georgenfeld","50.731376","13.751594","877","Sachsen"],
["5792","Zugspitze","47.420868","10.984724","2964","Bayern"],
["5906","Mannheim","49.509028","8.554076","96.1","Baden-Württemberg"],
["6159","Dörpen","52.954182","7.319582","8","Niedersachsen"],
["14311","Hersdorf-Weißenseifen","50.150531","6.55262","530","Rheinland-Pfalz"]
];
weather = [
["3",["1981-2010","3.8","3.1",".1","0","0","0","0","0","0","0",".4","2.6","10"]],
["44",["1981-2010","5.5","4.5",".5","0","0","0","0","0","0","0",".7","4.8","16"]],
["73",["1981-2010","11.1","5.4",".6","0","0","0","0","0","0","0","1.8","7.3","26.2"]],
["78",["1981-2010","4.8","3.8",".5","0","0","0","0","0","0","0",".6","4.1","13.8"]],
["91",["1981-2010","8.2","6.3",".8","0","0","0","0","0","0","0","1.4","6.2","22.9"]],
["142",["1981-2010","10.7","6.2","1","0","0","0","0","0","0","0","2.1","8.4","28.4"]],
["150",["1981-2010","6.3","3.9",".1","0","0","0","0","0","0","0","1.1","4.5","15.8"]],
["151",["1981-2010","10.3","5.9","1","0","0","0","0","0","0","0","1.6","8.1","26.9"]],
["164",["1981-2010","9","5.7","1.1","0","0","0","0","0","0","0","1.5","7.5","24.8"]],
["183",["1981-2010","6.1","5.6","1.4","0","0","0","0","0","0","0",".4","2.8","16.3"]],
["198",["1981-2010","8.1","6",".9","0","0","0","0","0","0","0","1.4","6.7","23.2"]],
["217",["1981-2010","10.4","7.5","2",".1","0","0","0","0","0","0","3.1","8.8","32"]],
["232",["1981-2010","10.7","6.9","1.4",".1","0","0","0","0","0","0","2.1","8.4","29.5"]],
["243",["1981-2010","4.4","3.1",".5","0","0","0","0","0","0","0",".5","3.4","12"]],
["257",["1981-2010","5.8","2.7",".2","0","0","0","0","0","0","0",".8","3.2","12.7"]],
["282",["1981-2010","8","4.3",".5","0","0","0","0","0","0","0","1.1","5.1","19"]],
["298",["1981-2010","7.7","5.8","1.3","0","0","0","0","0","0","0",".9","5.9","21.5"]],
["320",["1981-2010","9.4","5.3",".8","0","0","0","0","0","0","0","1.2","6.3","23.1"]],
["330",["1981-2010","9.3","6.6","1.1",".1","0","0","0","0","0","0","2","7.3","26.4"]],
["377",["1981-2010","6.2","3.7",".3","0","0","0","0","0","0","0","1.1","3.7","15"]],
["400",["1981-2010","8","4",".4","0","0","0","0","0","0","0","1.3","6.8","20.5"]],
["403",["1981-2010","8","4.6",".5","0","0","0","0","0","0","0","1.2","6.6","20.8"]],
["427",["1981-2010","8.3","5",".7","0","0","0","0","0","0","0","1.3","7","22.2"]],
["430",["1981-2010","7.4","4.7",".6","0","0","0","0","0","0","0","1.1","6.2","20"]],
["433",["1981-2010","7.8","4.8",".6","0","0","0","0","0","0","0","1.1","6.3","20.7"]],
["435",["1981-2010","6.9","4.5",".4","0","0","0","0","0","0","0","1","5.6","18.4"]],
["450",["1981-2010","4.4","2.1","0","0","0","0","0","0","0","0",".7","2.9","10.2"]],
["502",["1981-2010","10.2","7.4","1",".1","0","0","0","0","0","0","2","7.8","28.4"]],
["591",["1981-2010","8.9","5.4","1","0","0","0","0","0","0","0","1","7.1","23.4"]],
["596",["1981-2010","6.4","4.8","1.4","0","0","0","0","0","0","0",".5","4.4","17.5"]],
["614",["1981-2010","6.6","5.2",".6","0","0","0","0","0","0","0","1","4.6","18"]],
["648",["1981-2010","5.8","3.7",".5","0","0","0","0","0","0","0",".6","5.1","15.8"]],
["662",["1981-2010","7","5.3",".7","0","0","0","0","0","0","0","1.2","5.9","20.2"]],
["691",["1981-2010","5.6","3.7",".6","0","0","0","0","0","0","0",".5","4.5","14.9"]],
["701",["1981-2010","5.3","3.3",".5","0","0","0","0","0","0","0",".5","4.1","13.6"]],
["722",["1981-2010","18.3","17.7","13.9","5.8",".4","0","0","0","0","2.6","9.9","16.4","85"]],
["755",["1981-2010","8.6","5.7",".8","0","0","0","0","0","0","0","1.6","6.2","22.9"]],
["807",["1981-2010","8.2","4.5",".5","0","0","0","0","0","0","0","1.4","5.6","20.3"]],
["817",["1981-2010","7.6","4.6",".5","0","0","0","0","0","0","0","1.3","6.2","20.3"]],
["850",["1981-2010","6","4.7",".6","0","0","0","0","0","0","0",".8","5","17.2"]],
["853",["1981-2010","9.4","8.1","2.3",".2","0","0","0","0","0","0","2.3","7.9","30.2"]],
["863",["1981-2010","11.6","11","4",".4","0","0","0","0","0",".1","3.2","9.8","40.2"]],
["880",["1981-2010","7.4","5.1",".7","0","0","0","0","0","0","0","1.2","6.3","20.7"]],
["891",["1981-2010","5.4","3.5",".6","0","0","0","0","0","0","0",".5","3.7","13.7"]],
["963",["1981-2010","5.6","3.7",".5","0","0","0","0","0","0","0",".5","4.8","15.1"]],
["979",["1981-2010","6.6","3.5",".3","0","0","0","0","0","0","0",".9","5","16.4"]],
["982",["1981-2010","10.2","6.4",".7","0","0","0","0","0","0","0","2.2","7.2","26.8"]],
["1001",["1981-2010","8.3","5.4",".9","0","0","0","0","0","0","0","1.4","6.4","22.4"]],
["1048",["1981-2010","9","6.6","1.2","0","0","0","0","0","0","0","1.5","6.3","24.7"]],
["1078",["1981-2010","3.1","1.9",".1","0","0","0","0","0","0","0",".4","2","7.5"]],
["1103",["1981-2010","10.5","7.3","1.4","0","0","0","0","0","0","0","2.8","9.6","31.6"]],
["1107",["1981-2010","9.1","5.1",".6","0","0","0","0","0","0","0","1.7","6.6","23.2"]],
["1197",["1981-2010","9.1","6.3","1",".1","0","0","0","0","0","0","1.8","6.9","25.1"]],
["1224",["1981-2010","5.9","2.5",".2","0","0","0","0","0","0","0",".9","2.9","12.4"]],
["1266",["1981-2010","6.6","4",".6","0","0","0","0","0","0","0",".7","5.1","17.1"]],
["1270",["1981-2010","9.6","8","1.7",".1","0","0","0","0","0","0","2.1","8.1","29.6"]],
["1279",["1981-2010","7.7","3.9",".5","0","0","0","0","0","0","0","1","5","18.1"]],
["1292",["1981-2010","12","7.9","1",".1","0","0","0","0","0","0","2.6","9.7","33.3"]],
["1297",["1981-2010","7","4.9",".6","0","0","0","0","0","0","0","1","5.2","18.7"]],
["1303",["1981-2010","4.4","3.4",".2","0","0","0","0","0","0","0",".6","2.9","11.6"]],
["1327",["1981-2010","4.3","3.2",".1","0","0","0","0","0","0","0",".6","2.5","10.6"]],
["1332",["1981-2010","13","7.4","1.4","0","0","0","0","0","0","0","2.2","9.7","33.7"]],
["1346",["1981-2010","15","14.6","13","6.5","1","0","0","0","0","2.3","9.2","13","74.6"]],
["1357",["1981-2010","15.1","11.3","3.6",".4","0","0","0","0","0",".1","4.8","12.8","48"]],
["1358",["1981-2010","19.8","18.3","14.5","4.9",".2","0","0","0","0","3.1","11.1","18.3","90.1"]],
["1420",["1981-2010","5.9","2.8",".1","0","0","0","0","0","0","0",".8","3.8","13.3"]],
["1443",["1981-2010","5.3","2.4",".1","0","0","0","0","0","0","0",".9","3.1","11.9"]],
["1451",["1981-2010","6.2","3.9",".5","0","0","0","0","0","0","0",".7","5.3","16.5"]],
["1468",["1981-2010","10.5","8.9","2.9",".3","0","0","0","0","0","0","3.9","9.7","36.3"]],
["1503",["1981-2010","4.3","3.6",".5","0","0","0","0","0","0","0",".5","3.8","12.7"]],
["1526",["1981-2010","7.3","4.6",".5","0","0","0","0","0","0","0","1.3","5","18.7"]],
["1544",["1981-2010","7.7","4.4",".7","0","0","0","0","0","0","0",".9","6.7","20.4"]],
["1550",["1981-2010","9.4","5.4","1.4",".1","0","0","0","0","0","0","2.8","8.6","27.6"]],
["1580",["1981-2010","5.1","2.4",".1","0","0","0","0","0","0","0",".9","3.2","11.7"]],
["1590",["1981-2010","3.6","2.2",".1","0","0","0","0","0","0","0",".4","2.1","8.4"]],
["1612",["1981-2010","8.9","7.5","1.5",".1","0","0","0","0","0","0","1.8","7.2","27.1"]],
["1619",["1981-2010","5.2","2.2","0","0","0","0","0","0","0","0",".7","2.8","11"]],
["1639",["1981-2010","7.2","3.8",".2","0","0","0","0","0","0","0","1","5","17.2"]],
["1645",["1981-2010","9.5","7.3","1.2","0","0","0","0","0","0","0","1.9","7.4","27.3"]],
["1667",["1981-2010","5.9","3.8",".7","0","0","0","0","0","0","0",".6","4.7","15.6"]],
["1684",["1981-2010","9.9","7.5","1.5",".1","0","0","0","0","0","0","2.1","8.2","29.3"]],
["1691",["1981-2010","6.5","4.7",".6","0","0","0","0","0","0","0","1","4.9","17.6"]],
["1735",["1981-2010","12.4","8","2.2","0","0","0","0","0","0","0","3.3","10.3","36.3"]],
["1757",["1981-2010","7.4","5.3","1","0","0","0","0","0","0","0","1.1","5.7","20.4"]],
["1803",["1981-2010","7.6","5.6","1.1","0","0","0","0","0","0","0","1.3","6.2","21.8"]],
["1832",["1981-2010","19.5","18.1","14.5","6.4",".5","0","0","0",".1","3","11.6","17.1","90.8"]],
["1920",["1981-2010","3.5","2.7",".2","0","0","0","0","0","0","0",".5","2.1","8.9"]],
["1975",["1981-2010","6.1","3.7",".6","0","0","0","0","0","0","0",".7","5.2","16.4"]],
["1981",["1981-2010","5.9","3.7",".5","0","0","0","0","0","0","0",".6","4.9","15.5"]],
["1990",["1981-2010","5.6","3.4",".4","0","0","0","0","0","0","0",".6","4.9","15"]],
["1993",["1981-2010","5.2","4",".5","0","0","0","0","0","0","0",".7","3.5","13.8"]],
["2014",["1981-2010","6.3","4.7",".6","0","0","0","0","0","0","0",".9","5.3","17.8"]],
["2074",["1981-2010","7.4","5.8","1",".1","0","0","0","0","0","0","1.7","5.5","21.5"]],
["2080",["1981-2010","5.3","2.1",".1","0","0","0","0","0","0","0",".7","2.7","10.8"]],
["2110",["1981-2010","3.9","2.8","0","0","0","0","0","0","0","0",".5","2.2","9.4"]],
["2115",["1981-2010","3","2.8",".5","0","0","0","0","0","0","0",".1","1.1","7.5"]],
["2120",["1981-2010","6.8","5.7",".8","0","0","0","0","0","0","0","1.2","5.7","20.1"]],
["2147",["1981-2010","4.6","3.4",".4","0","0","0","0","0","0","0",".7","3","12.1"]],
["2167",["1981-2010","6.3","4.1",".3","0","0","0","0","0","0","0","1.1","4.6","16.4"]],
["2171",["1981-2010","7.8","5.2",".8","0","0","0","0","0","0","0","1.2","6.1","21.1"]],
["2173",["1981-2010","3.5","2.4",".1","0","0","0","0","0","0","0",".4","2","8.4"]],
["2206",["1981-2010","5.4","4.9",".8","0","0","0","0","0","0","0",".9","4.3","16.2"]],
["2211",["1981-2010","6.6","4.1",".3","0","0","0","0","0","0","0","1","4.4","16.4"]],
["2250",["1981-2010","12.8","8.1","1.2","0","0","0","0","0","0","0","2.7","10","34.8"]],
["2260",["1981-2010","11.2","8.4","2.1",".2","0","0","0","0","0","0","2.5","8.3","32.7"]],
["2261",["1981-2010","13.8","10","2.9",".3","0","0","0","0","0","0","3.8","12","42.8"]],
["2268",["1981-2010","8.3","5",".5","0","0","0","0","0","0","0","1.3","4.9","20.1"]],
["2290",["1981-2010","11.2","10.5","5",".7","0","0","0","0","0",".3","5.8","10.3","43.8"]],
["2303",["1981-2010","5.9","4.1",".7","0","0","0","0","0","0","0",".6","4.1","15.4"]],
["2306",["1981-2010","6.4","4.6",".8","0","0","0","0","0","0","0",".4","4.1","16.2"]],
["2319",["1981-2010","10","7.3","1.8",".1","0","0","0","0","0",".1","3.2","9","31.4"]],
["2324",["1981-2010","10","7.9","1.9",".1","0","0","0","0","0","0","2","7.8","29.6"]],
["2480",["1981-2010","5.5","2.7",".1","0","0","0","0","0","0","0",".8","3","12"]],
["2483",["1981-2010","15","13.4","7.4","1.2","0","0","0","0","0",".2","6.2","13.7","57"]],
["2497",["1981-2010","6.6","6.1","1.3",".1","0","0","0","0","0","0","1.6","5.6","21.3"]],
["2522",["1981-2010","5.4","2.5",".1","0","0","0","0","0","0","0",".7","2.4","11.1"]],
["2532",["1981-2010","7.9","5.7",".6","0","0","0","0","0","0","0","1.5","6","21.7"]],
["2542",["1981-2010","10","8.3","2.2",".1","0","0","0","0","0","0","3.1","8.6","32.4"]],
["2543",["1981-2010","10.2","8.3","1.3","0","0","0","0","0","0","0","2.9","9.1","31.9"]],
["2559",["1981-2010","8.5","7","1.9",".1","0","0","0","0","0","0","2.6","7.7","27.8"]],
["2597",["1981-2010","8.8","4.1",".5","0","0","0","0","0","0","0","1.2","5.8","20.4"]],
["2600",["1981-2010","7.6","3.9",".3","0","0","0","0","0","0","0","1.1","4.3","17.3"]],
["2601",["1981-2010","14.6","12.2","5.2",".6","0","0","0","0","0",".1","5.7","12.3","50.6"]],
["2629",["1981-2010","4.1","2.3",".1","0","0","0","0","0","0","0",".6","2.9","10.1"]],
["2638",["1981-2010","10.4","10.6","4.6",".5","0","0","0","0","0","0","5.6","10.4","42.2"]],
["2657",["1981-2010","3.8","1.9","0","0","0","0","0","0","0","0",".6","1.9","8.2"]],
["2667",["1981-2010","3.6","1.9",".1","0","0","0","0","0","0","0",".4","2","7.9"]],
["2680",["1981-2010","9.1","5",".6","0","0","0","0","0","0","0","1.3","6.1","22"]],
["2700",["1981-2010","12.4","7.3","1.1","0","0","0","0","0","0","0","2.1","9.1","32.1"]],
["2712",["1981-2010","7.8","4",".4","0","0","0","0","0","0","0","1.4","4.9","18.5"]],
["2750",["1981-2010","9.2","5.3","1","0","0","0","0","0","0","0","1.3","6.3","23.2"]],
["2812",["1981-2010","7","2.6","0","0","0","0","0","0","0","0",".6","3.8","14.1"]],
["2814",["1981-2010","11.5","9.3","2.6",".3","0","0","0","0","0",".1","4.3","10.1","38.1"]],
["2925",["1981-2010","9.6","8","1.9",".1","0","0","0","0","0","0","2.1","7.8","29.4"]],
["2928",["1981-2010","7.4","5.8","1","0","0","0","0","0","0","0","1.3","5.9","21.3"]],
["2932",["1981-2010","7.6","6","1","0","0","0","0","0","0","0","1.3","6.3","22.1"]],
["2947",["1981-2010","5.7","3.6",".4","0","0","0","0","0","0","0","1","4.2","14.9"]],
["2950",["1981-2010","6","4.3",".7","0","0","0","0","0","0","0",".7","4.1","15.7"]],
["2968",["1981-2010","2.5","1.6",".1","0","0","0","0","0","0","0",".2","1.2","5.6"]],
["3015",["1981-2010","9","5.8",".7","0","0","0","0","0","0","0","1.4","7.6","24.5"]],
["3018",["1981-2010","7.9","5.7",".6","0","0","0","0","0","0","0","1.8","6.2","22.2"]],
["3023",["1981-2010","4.3","3",".3","0","0","0","0","0","0","0",".5","3.7","11.8"]],
["3028",["1981-2010","5.5","4.6",".6","0","0","0","0","0","0","0",".8","3.7","15.2"]],
["3031",["1981-2010","4.2","3.4",".4","0","0","0","0","0","0","0",".6","2.8","11.4"]],
["3032",["1981-2010","5.4","4.1",".6","0","0","0","0","0","0","0",".3","2.9","13.3"]],
["3093",["1981-2010","6.8","4.7",".5","0","0","0","0","0","0","0","1.1","7","20"]],
["3126",["1981-2010","6.9","4.8",".5","0","0","0","0","0","0","0","1","6","19.2"]],
["3137",["1981-2010","5.7","2.3",".1","0","0","0","0","0","0","0",".7","3.5","12.2"]],
["3155",["1981-2010","7","4.9",".7","0","0","0","0","0","0","0","1.5","5","19.2"]],
["3167",["1981-2010","11.5","8.5","2.3",".1","0","0","0","0","0","0","2.7","9.2","34.2"]],
["3196",["1981-2010","8.7","5.6",".8","0","0","0","0","0","0","0","1.2","7.7","24.1"]],
["3231",["1981-2010","12.3","8.4","1.7",".1","0","0","0","0","0","0","2.8","10","35.3"]],
["3244",["1981-2010","10.3","7.6","1.4","0","0","0","0","0","0","0","2.6","8.6","30.5"]],
["3257",["1981-2010","7.3","4.5",".4","0","0","0","0","0","0","0","1.3","4.8","18.3"]],
["3271",["1981-2010","10.9","5.8",".7","0","0","0","0","0","0","0","1.7","7.6","26.6"]],
["3307",["1981-2010","7.4","6.4","2.1",".2","0","0","0","0","0","0","2.8","7.2","26.1"]],
["3366",["1981-2010","11.8","6.5","1","0","0","0","0","0","0","0","1.9","8.9","30.1"]],
["3376",["1981-2010","9.4","5.7","1.1","0","0","0","0","0","0","0","1.8","7.6","25.6"]],
["3379",["1981-2010","8.3","5.7","1","0","0","0","0","0","0","0","1.5","6.2","22.8"]],
["3402",["1981-2010","11","8.9","2.1",".3","0","0","0","0","0","0","3.9","10","36.1"]],
["3490",["1981-2010","3.7","2.4","0","0","0","0","0","0","0","0",".5","1.9","8.6"]],
["3509",["1981-2010","8.9","5.3","1","0","0","0","0","0","0","0","1.4","8.2","24.8"]],
["3527",["1981-2010","11.5","8.3","1.9",".1","0","0","0","0","0","0","2.7","9.1","33.5"]],
["3537",["1981-2010","6.3","3.8",".6","0","0","0","0","0","0","0",".5","4.7","15.9"]],
["3552",["1981-2010","8.1","4.9",".6","0","0","0","0","0","0","0","1.1","6.3","20.9"]],
["3578",["1981-2010","10.8","6",".6","0","0","0","0","0","0","0","1.7","7.2","26.3"]],
["3612",["1981-2010","5.5","3.8",".4","0","0","0","0","0","0","0",".6","4.3","14.7"]],
["3621",["1981-2010","10.3","6.6","1",".1","0","0","0","0","0","0","1.8","7.6","27.3"]],
["3631",["1981-2010","4.3","3.1",".4","0","0","0","0","0","0","0",".5","2.7","11"]],
["3640",["1981-2010","3.8","2.9",".3","0","0","0","0","0","0","0",".4","2.9","10.4"]],
["3667",["1981-2010","8.7","5.1",".7","0","0","0","0","0","0","0","1.4","6","21.9"]],
["3668",["1981-2010","8.2","5",".7","0","0","0","0","0","0","0","1.3","5.9","21.1"]],
["3730",["1981-2010","8.6","5.9","1.8",".1","0","0","0","0","0","0","2.9","7.4","26.8"]],
["3739",["1981-2010","14.2","9.8","2.1",".1","0","0","0","0","0","0","3.7","11.3","41.1"]],
["3761",["1981-2010","6.6","3.9",".3","0","0","0","0","0","0","0","1.3","4.4","16.5"]],
["3811",["1981-2010","7.2","5.7","1","0","0","0","0","0","0","0","1.3","5.9","21"]],
["3875",["1981-2010","13.4","7.9","1.7","0","0","0","0","0","0","0","3","11","36.9"]],
["3927",["1981-2010","12","8.4","1.6",".1","0","0","0","0","0","0","3.2","10.2","35.6"]],
["3939",["1981-2010","7.1","4.1",".4","0","0","0","0","0","0","0","1.3","4","17"]],
["3987",["1981-2010","8.2","4.8",".5","0","0","0","0","0","0","0","1.4","7.1","22"]],
["4063",["1981-2010","5.4","4.3",".6","0","0","0","0","0","0","0",".7","4.6","15.7"]],
["4104",["1981-2010","11.9","6.3",".7","0","0","0","0","0","0","0","1.6","8.4","28.9"]],
["4169",["1981-2010","6.3","2.8",".1","0","0","0","0","0","0","0",".8","3.6","13.6"]],
["4175",["1981-2010","4.7","2",".1","0","0","0","0","0","0","0",".5","2.1","9.5"]],
["4261",["1981-2010","8.5","5.4",".7","0","0","0","0","0","0","0","1.9","7.4","23.8"]],
["4271",["1981-2010","6.1","4.1",".8","0","0","0","0","0","0","0",".6","4.3","15.9"]],
["4278",["1981-2010","8.4","4.6",".5","0","0","0","0","0","0","0","1.4","5.9","20.7"]],
["4287",["1981-2010","9.5","6.3",".9",".1","0","0","0","0","0","0","2","6.8","25.6"]],
["4318",["1981-2010","10.1","8","2.7",".2","0","0","0","0","0","0","3.4","9","33.3"]],
["4323",["1981-2010","9.3","6.7","1.1",".1","0","0","0","0","0","0","2.1","7.8","27.2"]],
["4336",["1981-2010","6.8","4.2",".3","0","0","0","0","0","0","0","1.2","4.9","17.4"]],
["4350",["1981-2010","6.7","3.2",".3","0","0","0","0","0","0","0","1.2","3.9","15.3"]],
["4371",["1981-2010","5.5","3.8",".5","0","0","0","0","0","0","0",".8","4.2","14.8"]],
["4377",["1981-2010","11.7","8.2","1.8",".1","0","0","0","0","0","0","2.4","9.9","34"]],
["4393",["1981-2010","5.2","3.6",".6","0","0","0","0","0","0","0",".4","3.7","13.6"]],
["4411",["1981-2010","6.1","3.6",".2","0","0","0","0","0","0","0","1","3.6","14.4"]],
["4442",["1981-2010","5.6","4.3",".5","0","0","0","0","0","0","0",".7","3.8","14.9"]],
["4466",["1981-2010","7","4.5",".8","0","0","0","0","0","0","0",".5","5","17.8"]],
["4501",["1981-2010","17.8","15.3","9","2","0","0","0","0","0",".6","7.9","17","69.5"]],
["4508",["1981-2010","9.9","7.4","2.5",".1","0","0","0","0","0","0","3","8.9","31.8"]],
["4549",["1981-2010","10.2","10.3","5",".8","0","0","0","0","0",".2","4.3","9.6","40.5"]],
["4560",["1981-2010","7.7","5.1",".5","0","0","0","0","0","0","0","1.3","5.4","20"]],
["4592",["1981-2010","11.6","5.5",".6","0","0","0","0","0","0","0","1.8","8.5","28"]],
["4597",["1981-2010","8.3","7.3","1.7",".2","0","0","0","0","0","0","3","7","27.5"]],
["4625",["1981-2010","7.5","4.8",".6","0","0","0","0","0","0","0",".8","6.2","19.9"]],
["4642",["1981-2010","7.6","4.9",".7","0","0","0","0","0","0","0","1.1","6.5","20.8"]],
["4651",["1981-2010","6.9","5.9",".9","0","0","0","0","0","0","0","1.3","5.5","20.4"]],
["4692",["1981-2010","5.6","3.1",".2","0","0","0","0","0","0","0",".7","4.1","13.6"]],
["4703",["1981-2010","10.3","7","1.2",".1","0","0","0","0","0","0","2.4","8.6","29.7"]],
["4706",["1981-2010","12","5.9","1.1","0","0","0","0","0","0","0","1.7","8.2","28.8"]],
["4745",["1981-2010","6.6","4.3",".3","0","0","0","0","0","0","0","1","6.8","19.2"]],
["4887",["1981-2010","12.6","10.5","3.4",".3","0","0","0","0","0",".1","5.2","11.7","43.9"]],
["4896",["1981-2010","6.8","5.5","1.2","0","0","0","0","0","0","0",".4","4.2","18"]],
["4926",["1981-2010","4.6","2.8",".2","0","0","0","0","0","0","0",".7","2.3","10.5"]],
["4928",["1981-2010","6.2","4.1",".3","0","0","0","0","0","0","0","1.4","4.2","16.2"]],
["4931",["1981-2010","6.9","4.7",".8",".1","0","0","0","0","0","0","1.3","4.9","18.6"]],
["5014",["1981-2010","5.9","3.9",".6","0","0","0","0","0","0","0",".8","5.2","16.4"]],
["5017",["1981-2010","13.9","10.1","2.9",".2","0","0","0","0","0","0","4.1","11.9","43.1"]],
["5029",["1981-2010","7.4","5.5",".4","0","0","0","0","0","0","0","1.8","6.8","21.8"]],
["5064",["1981-2010","3.7","1.8","0","0","0","0","0","0","0","0",".4","2.1","8"]],
["5100",["1981-2010","5.8","3.4",".2","0","0","0","0","0","0","0","1.1","4","14.5"]],
["5111",["1981-2010","9.9","6.3","1.2",".1","0","0","0","0","0","0","2","7.9","27.5"]],
["5142",["1981-2010","8.5","5.3","1.3","0","0","0","0","0","0","0","1.4","6","22.6"]],
["5155",["1981-2010","11.9","6.9","1","0","0","0","0","0","0","0","2.6","9.2","31.6"]],
["5165",["1981-2010","6.8","4.9",".7","0","0","0","0","0","0","0","1.1","5.6","19.1"]],
["5185",["1981-2010","7.3","4",".4","0","0","0","0","0","0","0","1.1","4.9","17.7"]],
["5229",["1981-2010","9.3","6.6","1.3",".1","0","0","0","0","0","0","2.8","7.9","28.1"]],
["5279",["1981-2010","7.5","5.5",".7","0","0","0","0","0","0","0","1.3","5.6","20.6"]],
["5280",["1981-2010","6.6","4.1",".7","0","0","0","0","0","0","0",".8","5.3","17.5"]],
["5361",["1981-2010","6.5","4.6",".6","0","0","0","0","0","0","0","1.3","4.8","17.8"]],
["5371",["1981-2010","15.9","13.8","7.6","1.3","0","0","0","0","0",".3","6.8","14.3","60"]],
["5397",["1981-2010","12.3","7.7","1.4",".1","0","0","0","0","0","0","2.1","9.4","32.9"]],
["5426",["1981-2010","10.5","7.7","1.7",".2","0","0","0","0","0","0","2.7","9","31.8"]],
["5433",["1981-2010","6.5","4.1",".3","0","0","0","0","0","0","0","1.1","4.2","16.3"]],
["5440",["1981-2010","9.2","6.1",".8",".1","0","0","0","0","0","0","1.6","6.7","24.4"]],
["5467",["1981-2010","15.7","16.1","14.1","8.4","1.6",".2","0","0",".4","2.9","10.7","14.3","84.4"]],
["5540",["1981-2010","5.2","2.3",".1","0","0","0","0","0","0","0",".7","2.7","10.9"]],
["5610",["1981-2010","11.8","11.1","4.7",".5","0","0","0","0","0","0","4.1","10","42.3"]],
["5629",["1981-2010","7.9","5.1",".5","0","0","0","0","0","0","0","1.4","6.9","21.8"]],
["5654",["1981-2010","10.3","7.8","1.6","0","0","0","0","0","0","0","2.5","7.9","30.1"]],
["5664",["1981-2010","4.9","2.2",".1","0","0","0","0","0","0","0","1","2.7","10.9"]],
["5676",["1981-2010","6.6","4.5",".5","0","0","0","0","0","0","0","1.1","5.2","17.9"]],
["5692",["1981-2010","5.4","2.6","0","0","0","0","0","0","0","0",".9","3.2","12.1"]],
["5705",["1981-2010","8.5","4.5",".5","0","0","0","0","0","0","0","1.3","5.7","20.4"]],
["5717",["1981-2010","3.2","2.2",".1","0","0","0","0","0","0","0",".3","1.9","7.8"]],
["5731",["1981-2010","7.6","3.8",".3","0","0","0","0","0","0","0","1.6","4.8","18.1"]],
["5745",["1981-2010","8.9","5.3",".6","0","0","0","0","0","0","0","1.5","6.8","23.1"]],
["5779",["1981-2010","18.9","17.1","10.2","1.6","0","0","0","0","0","1","9.2","18.5","76.5"]],
["5792",["1981-2010","29.6","26.3","29.1","24.1","12.6","6.8","2.9","2.2","7.9","12.9","23.6","29","207"]],
["5906",["1981-2010","5.5","2.1",".1","0","0","0","0","0","0","0",".7","3","11.3"]],
["6159",["1981-2010","4.6","3.3",".5","0","0","0","0","0","0","0",".5","4.1","13"]],
["14311",["1981-2010","8.8","6.2","1",".1","0","0","0","0","0","0","2.1","7.2","25.3"]]
];
temperature = [
[1881,7.6,7.5,7.7,6.6,7.5,7.0,7.5,7.5,8.1,8.0,7.1,8.3,6.7,7.5,7.1,6.7,7.3],
[1882,9.0,9.0,8.1,7.3,8.2,8.5,8.9,8.9,9.0,8.6,8.8,8.8,8.1,8.8,8.4,7.8,8.3],
[1883,8.4,8.4,7.8,6.8,8.0,7.9,8.4,8.4,8.7,8.3,8.2,8.5,7.5,8.3,7.9,7.3,7.9],
[1884,9.1,9.1,8.4,7.5,8.6,8.7,9.1,9.1,9.4,8.9,8.9,9.2,8.2,8.9,8.5,7.9,8.6],
[1885,8.4,8.4,7.8,7.0,7.7,7.7,7.9,7.9,8.3,8.0,7.6,8.3,7.7,8.1,7.7,7.2,7.7],
[1886,8.5,8.5,8.1,7.3,8.1,7.9,8.2,8.2,8.7,8.4,7.8,8.7,7.8,8.4,7.9,7.4,8.0],
[1887,7.8,7.7,6.7,5.9,6.8,7.4,7.4,7.4,7.6,7.1,7.3,7.3,6.7,7.5,6.9,6.2,7.0],
[1888,7.4,7.4,7.0,6.2,6.8,6.7,7.1,7.1,7.4,7.1,6.7,7.3,6.7,7.3,6.8,6.2,6.9],
[1889,8.1,8.1,7.1,6.4,7.3,7.6,8.0,8.0,8.1,7.5,7.7,7.6,7.1,8.0,7.4,6.7,7.4],
[1890,8.1,8.1,7.0,6.5,7.3,7.6,7.7,7.7,7.8,7.4,7.6,7.6,7.2,7.8,7.3,6.7,7.3],
[1891,8.2,8.2,7.2,6.5,7.4,7.6,7.8,7.8,8.1,7.5,7.6,7.7,7.4,8.0,7.5,6.8,7.4],
[1892,8.0,7.9,7.8,6.9,7.5,7.2,7.6,7.6,8.2,7.8,7.1,8.1,7.4,7.9,7.5,6.9,7.5],
[1893,8.3,8.3,8.1,7.0,8.0,7.6,8.3,8.3,8.8,8.4,7.9,8.7,7.6,8.3,7.9,7.3,7.9],
[1894,8.7,8.7,8.0,7.2,8.1,8.2,8.6,8.6,8.9,8.3,8.4,8.5,7.9,8.6,8.1,7.5,8.1],
[1895,8.0,8.0,7.3,6.4,7.2,7.4,7.6,7.6,7.9,7.5,7.3,7.8,7.3,7.8,7.3,6.7,7.3],
[1896,8.3,8.3,7.4,6.4,7.6,7.9,8.2,8.2,8.3,7.8,8.1,8.0,7.4,8.1,7.5,6.8,7.6],
[1897,8.3,8.3,8.2,7.1,7.9,7.9,8.2,8.2,8.6,8.3,8.0,8.6,7.8,8.3,7.9,7.3,7.9],
[1898,9.1,9.0,8.6,7.6,8.5,8.4,8.9,8.9,9.1,8.7,8.5,8.9,8.6,9.0,8.5,7.9,8.5],
[1899,8.6,8.6,8.3,7.0,8.1,8.1,8.5,8.6,8.8,8.4,8.4,8.7,7.9,8.6,8.0,7.4,8.1],
[1900,8.8,8.8,8.5,7.5,8.4,8.2,8.7,8.8,8.9,8.7,8.3,9.0,8.3,8.8,8.3,7.7,8.4],
[1901,8.3,8.3,7.4,6.8,7.5,7.8,8.1,8.1,8.3,7.9,7.9,8.1,7.5,8.1,7.5,6.7,7.6],
[1902,7.3,7.2,7.5,6.8,7.3,6.6,7.3,7.3,7.7,7.7,7.0,7.9,6.9,7.3,6.9,6.4,7.2],
[1903,9.0,9.0,8.1,7.6,8.3,8.2,8.8,8.8,8.9,8.5,8.4,8.6,8.4,9.0,8.5,7.8,8.4],
[1904,8.8,8.8,8.4,7.8,8.3,8.0,8.6,8.6,8.8,8.6,8.2,8.7,8.3,8.8,8.4,7.8,8.4],
[1905,8.6,8.6,7.8,7.2,7.9,7.9,8.3,8.3,8.5,8.2,8.1,8.3,7.8,8.4,7.9,7.3,8.0],
[1906,9.1,9.1,8.0,7.4,8.2,8.4,8.8,8.8,8.8,8.4,8.5,8.5,8.2,9.0,8.4,7.7,8.3],
[1907,8.2,8.2,7.9,7.2,7.8,7.5,8.1,8.1,8.4,8.1,7.6,8.3,7.7,8.1,7.7,7.2,7.8],
[1908,8.0,8.0,7.3,6.6,7.3,7.6,8.0,8.0,8.1,7.6,7.8,7.8,7.4,7.9,7.4,6.8,7.5],
[1909,7.9,7.8,7.2,6.6,7.4,7.2,7.7,7.7,7.9,7.7,7.3,7.9,7.3,7.8,7.3,6.8,7.4],
[1910,9.0,9.0,8.0,7.5,8.4,8.6,9.0,9.0,9.1,8.5,8.8,8.7,8.4,8.9,8.4,7.8,8.4],
[1911,9.7,9.6,8.8,8.2,9.1,9.0,9.5,9.5,9.7,9.3,9.1,9.5,9.0,9.7,9.1,8.5,9.0],
[1912,8.2,8.2,7.7,7.0,7.9,7.7,8.3,8.3,8.8,8.3,8.0,8.5,7.7,8.2,7.8,7.3,7.9],
[1913,9.2,9.2,8.2,7.6,8.4,8.8,9.0,9.0,9.2,8.7,8.8,9.0,8.4,9.1,8.5,7.9,8.5],
[1914,9.3,9.3,7.9,7.3,8.4,9.2,9.2,9.2,9.2,8.6,9.2,8.8,8.4,9.1,8.5,7.8,8.5],
[1915,8.3,8.3,7.9,7.4,8.1,7.6,8.1,8.1,8.5,8.5,7.6,8.7,7.7,8.2,7.8,7.3,7.9],
[1916,9.0,9.0,8.3,8.0,8.4,8.3,8.6,8.6,8.9,8.8,8.2,8.9,8.4,8.8,8.4,7.8,8.4],
[1917,8.2,8.2,7.3,6.9,7.5,7.6,7.9,7.9,8.0,7.8,7.7,7.8,7.4,8.0,7.5,6.8,7.5],
[1918,9.2,9.1,8.2,7.8,8.5,8.5,8.9,8.9,9.1,8.9,8.4,9.0,8.5,9.0,8.5,8.0,8.5],
[1919,7.7,7.7,7.3,6.8,7.3,7.3,7.5,7.5,7.9,7.8,7.2,7.9,7.1,7.7,7.2,6.6,7.3],
[1920,9.0,9.0,8.5,8.1,8.5,8.5,9.0,9.0,9.2,8.8,8.6,8.9,8.5,9.0,8.6,8.0,8.6],
[1921,9.4,9.4,8.8,8.3,9.0,9.0,9.3,9.3,9.6,9.4,9.1,9.5,8.8,9.4,8.9,8.2,9.0],
[1922,7.4,7.4,7.3,6.7,7.1,7.1,7.4,7.4,7.8,7.7,7.1,7.8,6.9,7.4,7.0,6.4,7.2],
[1923,8.2,8.2,8.2,7.6,8.0,7.6,8.0,8.0,8.5,8.6,7.6,8.6,7.9,8.2,7.9,7.4,8.0],
[1924,8.0,8.0,7.4,6.7,7.4,7.5,8.0,8.0,8.2,7.8,7.6,7.9,7.5,8.0,7.6,7.0,7.5],
[1925,9.0,9.0,7.9,7.4,8.2,8.6,8.8,8.8,8.8,8.5,8.5,8.5,8.3,8.9,8.4,7.8,8.3],
[1926,9.3,9.2,8.6,8.0,8.7,8.7,9.1,9.1,9.3,9.0,8.7,9.1,8.6,9.2,8.7,8.2,8.7],
[1927,8.4,8.3,8.0,7.5,8.0,7.9,8.3,8.3,8.6,8.4,8.0,8.5,7.8,8.4,8.0,7.4,8.0],
[1928,8.6,8.6,8.6,7.9,8.3,8.0,8.5,8.5,8.9,8.8,8.1,9.0,8.0,8.6,8.2,7.6,8.3],
[1929,7.6,7.6,7.5,6.7,7.6,7.0,7.5,7.5,8.2,8.0,7.1,8.1,7.1,7.6,7.3,6.8,7.4],
[1930,9.2,9.2,8.7,8.1,8.8,8.6,9.0,9.0,9.4,9.1,8.7,9.3,8.6,9.2,8.7,8.2,8.8],
[1931,8.1,8.1,7.2,6.6,7.6,7.6,8.1,8.1,8.3,7.9,7.7,8.0,7.4,8.2,7.7,7.0,7.6],
[1932,9.0,8.9,7.9,7.4,8.2,8.6,8.9,8.9,9.0,8.5,8.7,8.7,8.1,8.9,8.4,7.7,8.3],
[1933,7.9,7.9,7.4,6.6,7.7,7.8,8.2,8.2,8.4,8.1,8.3,8.4,7.1,8.0,7.5,6.9,7.6],
[1934,10.4,10.4,9.0,8.7,9.5,9.7,10.0,10.0,10.1,9.7,9.7,9.8,9.6,10.3,9.8,9.1,9.5],
[1935,8.9,8.9,8.0,7.5,8.4,8.5,8.9,8.9,9.1,8.8,8.6,8.9,8.2,9.0,8.5,7.8,8.4],
[1936,8.9,8.9,8.2,7.7,8.4,8.3,8.8,8.8,9.0,8.7,8.4,8.8,8.3,8.9,8.4,7.8,8.4],
[1937,8.9,8.9,8.6,7.9,8.7,8.4,8.9,8.8,9.2,9.0,8.4,9.3,8.4,9.0,8.6,8.1,8.6],
[1938,9.3,9.3,8.1,7.6,8.5,9.0,9.2,9.2,9.2,8.7,9.1,9.0,8.5,9.2,8.7,7.9,8.6],
[1939,8.9,8.9,7.9,7.3,8.2,8.5,8.9,8.9,9.1,8.6,8.6,8.8,8.1,8.9,8.3,7.7,8.3],
[1940,6.7,6.7,6.8,6.0,6.7,6.2,6.9,6.9,7.5,7.3,6.5,7.6,6.2,6.7,6.4,5.9,6.6],
[1941,7.3,7.3,7.1,6.4,7.3,6.9,7.6,7.6,8.1,7.7,7.1,8.0,6.7,7.4,7.0,6.5,7.2],
[1942,7.6,7.6,7.4,6.7,7.3,6.9,7.5,7.5,8.0,7.8,7.0,8.1,7.0,7.6,7.2,6.7,7.3],
[1943,9.3,9.3,8.8,8.1,8.8,8.9,9.2,9.2,9.5,9.1,9.0,9.4,8.8,9.3,8.9,8.4,8.9],
[1944,9.0,9.0,7.8,7.3,8.3,8.6,8.9,8.9,8.9,8.4,8.6,8.6,8.1,9.0,8.4,7.7,8.3],
[1945,9.5,9.5,8.7,8.1,9.0,9.3,9.4,9.4,9.6,9.3,9.1,9.5,8.9,9.2,8.9,8.5,9.0],
[1946,8.9,8.8,8.2,7.8,8.3,8.8,8.6,8.6,8.9,8.5,8.2,8.7,8.2,8.8,8.3,7.8,8.4],
[1947,8.4,8.4,8.9,8.2,8.8,7.7,8.6,8.5,9.3,9.3,8.0,9.5,8.2,8.6,8.3,7.9,8.5],
[1948,9.6,9.6,8.7,8.3,8.9,9.0,9.5,9.5,9.7,9.2,9.1,9.5,9.1,9.7,9.2,8.5,9.0],
[1949,9.6,9.6,8.9,8.4,9.1,9.2,9.5,9.5,9.8,9.5,9.3,9.9,8.9,9.7,9.2,8.6,9.1],
[1950,9.0,9.0,8.5,8.1,8.5,8.5,8.9,8.9,9.2,8.8,8.6,9.1,8.5,9.0,8.5,8.0,8.6],
[1951,9.2,9.2,8.5,8.1,8.7,8.6,9.0,9.0,9.3,8.9,8.7,9.2,8.9,9.2,8.8,8.3,8.7],
[1952,8.2,8.2,8.1,7.4,8.0,7.6,8.1,8.1,8.5,8.4,7.7,8.7,7.8,8.2,7.9,7.4,7.9],
[1953,9.6,9.6,8.4,8.0,8.9,9.1,9.4,9.4,9.5,9.1,9.2,9.5,9.1,9.6,9.2,8.6,8.9],
[1954,8.0,8.0,7.5,6.9,7.8,7.5,8.1,8.1,8.5,8.1,7.9,8.3,7.5,8.1,7.7,7.2,7.7],
[1955,7.9,7.9,7.5,6.8,7.4,7.6,8.0,8.0,8.3,7.9,7.8,8.3,7.2,7.8,7.4,6.8,7.5],
[1956,7.2,7.2,6.7,6.0,6.9,6.9,7.3,7.3,7.6,7.2,7.2,7.4,6.4,7.1,6.7,6.2,6.8],
[1957,9.0,9.0,8.3,7.8,8.6,8.5,9.0,9.0,9.4,8.9,8.7,9.3,8.5,9.0,8.6,8.1,8.6],
[1958,8.5,8.5,8.1,7.5,8.3,8.0,8.6,8.6,8.9,8.6,8.1,8.9,8.2,8.6,8.2,7.7,8.2],
[1959,9.3,9.3,8.8,8.1,9.2,8.9,9.4,9.4,9.9,9.6,9.1,10.1,8.8,9.4,9.0,8.6,9.0],
[1960,8.7,8.7,8.3,7.7,8.5,8.2,8.8,8.8,9.2,8.8,8.3,9.1,8.2,8.8,8.4,7.8,8.4],
[1961,9.3,9.3,9.0,8.2,8.9,8.8,9.2,9.2,9.6,9.3,8.9,9.7,8.9,9.3,8.9,8.4,8.9],
[1962,7.7,7.7,7.1,6.4,7.0,7.2,7.4,7.4,7.6,7.5,7.4,7.9,7.1,7.5,7.1,6.5,7.1],
[1963,7.7,7.7,7.0,6.4,7.0,7.1,7.3,7.3,7.7,7.3,7.1,7.7,7.2,7.5,7.1,6.5,7.1],
[1964,8.4,8.4,8.2,7.4,8.2,8.0,8.4,8.4,8.9,8.6,8.0,9.0,8.0,8.4,8.0,7.6,8.1],
[1965,7.9,7.8,7.3,6.7,7.5,7.3,7.9,7.9,8.2,7.8,7.5,8.1,7.4,7.9,7.5,6.9,7.5],
[1966,8.8,8.8,8.5,7.9,8.6,8.2,8.7,8.7,9.2,8.9,8.2,9.2,8.5,8.8,8.5,8.0,8.5],
[1967,9.6,9.6,8.5,8.0,8.9,9.1,9.4,9.4,9.5,9.0,9.1,9.2,8.9,9.5,9.0,8.4,8.9],
[1968,8.7,8.7,7.9,7.3,8.1,8.3,8.6,8.6,8.8,8.3,8.4,8.6,8.0,8.6,8.1,7.5,8.1],
[1969,7.8,7.8,7.6,7.1,7.9,7.3,8.2,8.2,8.7,8.2,7.8,8.5,7.5,8.0,7.6,7.1,7.8],
[1970,7.9,7.9,7.8,7.1,7.8,7.3,8.1,8.1,8.6,8.2,7.6,8.5,7.4,8.0,7.6,7.1,7.7],
[1971,9.0,9.0,8.1,7.5,8.4,8.6,8.9,8.9,9.2,8.7,8.6,8.9,8.3,8.9,8.4,7.8,8.4],
[1972,8.3,8.3,7.5,7.0,7.7,7.9,8.2,8.2,8.5,8.0,8.0,8.3,7.8,8.2,7.8,7.2,7.8],
[1973,8.7,8.7,7.8,7.2,8.3,8.4,8.8,8.8,9.0,8.6,8.6,8.9,8.0,8.7,8.2,7.5,8.2],
[1974,9.3,9.3,8.6,8.0,8.8,8.8,9.3,9.3,9.4,9.1,8.9,9.4,8.7,9.4,8.8,8.2,8.8],
[1975,9.6,9.6,8.5,8.0,8.9,9.0,9.5,9.5,9.6,9.1,9.2,9.4,8.9,9.5,9.0,8.3,8.9],
[1976,8.6,8.6,8.4,7.7,8.7,8.0,8.8,8.8,9.4,9.2,8.4,9.6,8.1,8.8,8.4,7.9,8.5],
[1977,9.1,9.1,8.6,8.0,8.7,8.5,9.1,9.1,9.3,8.9,8.6,9.1,8.5,9.1,8.6,8.1,8.7],
[1978,8.4,8.4,7.5,6.9,7.7,7.8,8.3,8.3,8.5,8.0,8.0,8.1,7.6,8.3,7.8,7.2,7.8],
[1979,8.0,8.0,8.0,7.4,7.6,7.3,7.8,7.8,8.2,8.1,7.2,8.4,7.7,8.0,7.6,7.1,7.7],
[1980,7.7,7.7,7.5,6.9,7.7,7.3,8.2,8.2,8.6,8.1,7.7,8.3,7.2,7.9,7.5,7.0,7.6],
[1981,8.7,8.6,8.1,7.5,8.1,8.1,8.5,8.5,8.9,8.5,8.0,8.9,8.0,8.6,8.1,7.5,8.2],
[1982,9.5,9.4,8.6,8.1,8.8,8.7,9.3,9.3,9.7,9.1,8.7,9.5,9.0,9.6,9.1,8.5,8.9],
[1983,9.7,9.7,8.8,8.2,8.9,9.1,9.5,9.5,9.7,9.2,9.1,9.5,9.0,9.6,9.1,8.4,9.0],
[1984,8.4,8.4,7.7,7.1,7.9,8.0,8.5,8.5,8.9,8.3,8.2,8.7,7.7,8.4,7.9,7.3,8.0],
[1985,7.9,7.9,7.4,6.7,7.3,7.2,7.8,7.8,8.0,7.7,7.4,8.1,7.3,7.9,7.4,6.8,7.4],
[1986,8.3,8.2,7.9,7.3,7.9,7.7,8.2,8.2,8.6,8.3,7.8,8.6,7.8,8.2,7.8,7.3,7.9],
[1987,7.5,7.5,7.7,7.0,7.4,7.1,7.7,7.7,8.2,7.9,7.3,8.3,7.0,7.5,7.1,6.6,7.4],
[1988,9.5,9.5,8.9,8.3,9.0,9.0,9.5,9.5,9.7,9.4,9.1,9.6,8.8,9.6,9.1,8.5,9.1],
[1989,10.2,10.1,9.0,8.4,9.4,9.7,10.0,10.0,10.3,9.7,9.6,9.9,9.5,10.1,9.6,8.9,9.5],
[1990,10.1,10.1,9.1,8.4,9.4,9.8,10.1,10.1,10.2,9.7,9.7,10.0,9.4,10.1,9.5,8.8,9.5],
[1991,8.9,8.9,8.2,7.4,8.3,8.4,8.8,8.8,9.0,8.7,8.5,9.1,8.2,8.8,8.3,7.7,8.3],
[1992,9.9,9.9,9.1,8.6,9.2,9.3,9.9,9.9,10.0,9.5,9.5,9.8,9.3,9.9,9.4,8.7,9.4],
[1993,8.8,8.8,8.6,8.0,8.5,8.2,8.6,8.6,9.1,8.9,8.2,9.3,8.3,8.7,8.3,7.8,8.5],
[1994,9.9,9.9,9.9,9.4,9.7,9.2,9.8,9.8,10.3,10.1,9.3,10.5,9.4,10.0,9.6,9.1,9.7],
[1995,9.2,9.2,8.8,8.1,8.9,8.7,9.3,9.3,9.8,9.4,8.9,9.8,8.5,9.3,8.8,8.2,8.9],
[1996,7.4,7.3,7.4,6.7,7.2,6.9,7.5,7.5,7.9,7.8,7.2,8.3,6.6,7.3,6.9,6.4,7.2],
[1997,9.2,9.2,8.8,8.1,8.9,8.8,9.4,9.4,9.7,9.3,9.0,9.7,8.5,9.3,8.8,8.3,8.9],
[1998,9.5,9.5,8.9,8.4,9.0,8.9,9.5,9.5,9.7,9.3,9.0,9.5,8.9,9.6,9.1,8.5,9.1],
[1999,10.1,10.0,9.1,8.5,9.5,9.5,10.2,10.2,10.3,9.8,9.7,9.9,9.2,10.1,9.6,8.9,9.5],
[2000,10.4,10.4,9.7,9.1,9.8,9.7,10.3,10.3,10.5,10.1,9.8,10.3,9.8,10.4,9.9,9.4,9.9],
[2001,9.2,9.2,9.0,8.3,9.1,8.8,9.4,9.4,9.8,9.5,8.9,9.7,8.6,9.3,9.0,8.5,9.0],
[2002,9.8,9.7,9.5,9.0,9.6,9.4,9.9,9.9,10.3,10.0,9.6,10.3,9.2,9.7,9.3,8.8,9.6],
[2003,9.5,9.5,9.4,8.8,9.5,9.0,9.7,9.7,10.1,10.1,9.2,10.6,9.0,9.6,9.2,8.7,9.4],
[2004,9.3,9.3,8.7,8.2,8.9,9.0,9.5,9.5,9.6,9.2,9.1,9.5,8.6,9.3,8.9,8.3,8.9],
[2005,9.3,9.3,8.6,8.0,9.1,9.1,9.6,9.6,9.9,9.5,9.2,9.9,8.6,9.4,9.0,8.4,9.0],
[2006,10.0,10.0,9.2,8.5,9.5,9.7,10.2,10.2,10.3,9.9,9.9,10.3,9.2,10.0,9.5,8.9,9.5],
[2007,10.4,10.3,9.5,9.1,9.8,10.0,10.4,10.4,10.5,10.1,10.0,10.3,9.7,10.3,9.9,9.3,9.9],
[2008,10.1,10.1,9.1,8.7,9.3,9.7,10.0,10.0,9.9,9.6,9.7,9.7,9.4,10.0,9.5,8.9,9.5],
[2009,9.5,9.5,9.0,8.5,9.1,9.1,9.7,9.7,9.8,9.6,9.3,9.8,8.9,9.5,9.1,8.6,9.2],
[2010,8.1,8.1,7.9,7.3,7.9,7.7,8.1,8.1,8.4,8.4,7.7,8.7,7.5,8.0,7.6,7.2,7.8],
[2011,9.9,9.9,9.6,8.9,9.7,9.4,10.0,10.0,10.4,10.2,9.4,10.5,9.4,10.0,9.6,9.1,9.6],
[2012,9.4,9.3,9.1,8.5,9.1,8.8,9.5,9.5,9.7,9.5,8.8,9.7,8.9,9.4,9.1,8.6,9.1],
[2013,9.2,9.2,8.6,8.1,8.7,8.9,9.1,9.1,9.2,9.0,8.8,9.2,8.4,9.1,8.6,8.1,8.7],
[2014,10.7,10.7,10.1,9.6,10.3,10.2,10.8,10.8,11.0,10.7,10.5,10.9,10.1,10.7,10.3,9.8,10.3],
[2015,10.4,10.3,9.9,9.4,9.9,9.8,10.2,10.2,10.4,10.2,9.7,10.5,9.9,10.3,10.0,9.5,9.9],
[2016,10.0,10.0,9.3,8.9,9.4,9.6,9.9,9.9,10.1,9.8,9.6,9.9,9.4,10.1,9.6,9.0,9.5]
];
function NearestCity(latitude, longitude) {
var mindif = 99999;
var closest;
window.lat=latitude;
window.long=longitude;
for (index = 0; index < cities.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, cities[index][2], cities[index][3]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
city = cities[closest];
for (index = 0; index < weather.length; ++index) {
if (weather[index][0] == city[0]) {
tmp = weather[index][1];
jan = tmp[1];
feb = tmp[2];
mar = tmp[3];
apr = tmp[4];
mai = tmp[5];
jun = tmp[6];
jul = tmp[7];
aug = tmp[8];
sep = tmp[9];
okt = tmp[10];
nov = tmp[11];
dec = tmp[12];
}
}
// echo the nearest city
frame = document.getElementById('frame');
number = 16;
if (city[5] == "Berlin") {number=1;}
if (city[5] == "Brandenburg") {number=2;}
if (city[5] == "Baden-Württemberg") {number=3;}
if (city[5] == "Hessen") {number=5;}
if (city[5] == "Mecklenburg-Vorpommern") {number=6;}
if (city[5] == "Niedersachsen") {number=7;}
if (city[5] == "Hamburg") {number=8;}
if (city[5] == "Nordrhein-Westfalen") {number=9;}
if (city[5] == "Rheinland-Pfalz") {number=10;}
if (city[5] == "Schleswig-Holstein") {number=11;}
if (city[5] == "Saarland") {number=12;}
if (city[5] == "Sachsen") {number=13;}
if (city[5] == "Sachsen-Anhalt") {number=14;}
if (city[5] == "Thüringen") {number=15;}
if (city[5] == "Berlin") {number=1;}
html = '<h3>Your next weather centre is '+city[1]+" in "+city[5]+". It's located "+city[4]+" meters above normal.</h3>";
html = html+'<img style="max-width:80%;height:auto;" src="https://maps.googleapis.com/maps/api/staticmap?size=500x400&markers=color:blue|'+city[2]+', '+city[3]+'|'+window.lat+', '+window.long+'"><h4>Statistics of frozen days per month. (Average of 1881 to 2010)</h4>';
html = html+'<table>';
html = html+'<tr><td style="font-weight:bold;width:30%;">jan</td><td><div style="width:'+jan*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+jan+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">feb</td><td><div style="width:'+feb*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+feb+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">mar</td><td><div style="width:'+mar*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+mar+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">apr</td><td><div style="width:'+apr*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+apr+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">mai</td><td><div style="width:'+mai*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+mai+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">jun</td><td><div style="width:'+jun*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+jun+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">jul</td><td><div style="width:'+jul*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+jul+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">aug</td><td><div style="width:'+aug*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+aug+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">sep</td><td><div style="width:'+sep*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+sep+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">okt</td><td><div style="width:'+okt*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+okt+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">nov</td><td><div style="width:'+nov*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+nov+'</span></td></tr>';
html = html+'<tr><td style="font-weight:bold;width:30%;">dec</td><td><div style="width:'+dec*10+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+dec+'</span></td></tr>';
html = html+'</table>';
html = html+'<h4>Average temperature in '+city[5]+' (1881 to 2016)</h4>';
html = html+'<table>';
html = html+'<h4>The current average temperature is '+Math.round((temperature[temperature.length-1][0]/temperature[0][0])*10000)/100+'% of '+temperature[0][0]+'.</h4>';
for (index = temperature.length-1; index >= 0; index=index-1) {
html = html+'<tr><td style="font-weight:bold;width:30%;width:30%">'+temperature[index][0]+'</td><td><div style="width:'+temperature[index][number]*8+'%;height:30px;margin:-4px;margin-right:4px;margin-top:-2px;float:left;background:#FF3529;"></div><span>'+temperature[index][number]+'</span></td></tr>';
}
html = html+'</table>';
frame.innerHTML = html;
} |
/**
* 指示按钮
*/
Banner.prototype.btn = function() {
var s = this,
o = this.option,
$banner = this.$banner,
$btn;
for (var i = 0, item = ''; i < s.len; i++) {
item += '<a></a>';
}
$banner.append($('<div class="tb-btn"/>').append(item));
s.$btn = $btn = $('.tb-btn a', $banner);
$btn.first().addClass('active');
setTimeout(function() {
$btn.parent().css({
marginLeft: -($btn.outerWidth(true) * $btn.length / 2)
});
}, 0);
if (!Util.IS_MOBILE) {
$btn.on('click.terseBanner', function() {
if (s.isAnimated) return;
o.before.call(s, s.currentIndex);
s.currentIndex = $(this).index();
s.play();
});
}
};
|
'use strict';
var msb = require('msb');
var app = exports;
app.config = require('./lib/config');
app.start = function(cb) {
if (app.config.channelMonitorEnabled) msb.channelMonitorAgent.start();
var RouterWrapper = require('./lib/routerWrapper').RouterWrapper;
app.router = new RouterWrapper();
app.router.load(app.config.routes);
app.createServer()
.listen(app.config.port)
.once('listening', function() {
app.config.port = this.address().port;
if (cb) { cb(); }
console.log('http2bus listening on ' + app.config.port);
});
};
app.createServer = function() {
var http = require('http');
var finalhandler = require('finalhandler');
return http.createServer(function(req, res) {
app.router.middleware(req, res, finalhandler(req, res));
});
};
app.routesAgent = require('./lib/routesProvider/agent');
|
$(document).ready(function () {
console.log("ready!");
$("#subs").click(function () {
var name = $('#name').val();
var email = $('#email').val();
if (name != '' && email != '') {
$('#subs_err').html('');
var subs = {name: name, email: email};
var url = "/index.php/index/subscribe_user";
$.post(url, {subs: JSON.stringify(subs)}).done(function (data) {
$('#subscribe_content').html(data);
}); // end of post
} // end if
else {
$('#subs_err').html('Please provide name and email');
}
});
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var code = getUrlParameter('errorcode');
if (code == 3) {
$('#login_err').html('Invalid email address or password');
}
$("#contact_submit").click(function () {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var comment = $('#comment').val();
if (name != '' && email != '' && phone != '' && comment != '') {
$('#contact_err').html('');
var contact = {name: name, email: email, phone: phone, comment: comment};
var url = "/index.php/index/send_contact_request";
$.post(url, {contact: JSON.stringify(contact)}).done(function (data) {
$('#contact_container').html(data);
}); // end of post
} // end if
else {
$('#contact_err').html('Please provide all required fields');
}
});
}); |
/* global createNS */
/* exported filtersFactory */
var filtersFactory = (function () {
var ob = {};
ob.createFilter = createFilter;
ob.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter;
function createFilter(filId, skipCoordinates) {
var fil = createNS('filter');
fil.setAttribute('id', filId);
if (skipCoordinates !== true) {
fil.setAttribute('filterUnits', 'objectBoundingBox');
fil.setAttribute('x', '0%');
fil.setAttribute('y', '0%');
fil.setAttribute('width', '100%');
fil.setAttribute('height', '100%');
}
return fil;
}
function createAlphaToLuminanceFilter() {
var feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type', 'matrix');
feColorMatrix.setAttribute('color-interpolation-filters', 'sRGB');
feColorMatrix.setAttribute('values', '0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1');
return feColorMatrix;
}
return ob;
}());
|
'use strict';
angular.module('myApp.post', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/new-post', {
templateUrl: 'posts/new-post.html',
controller: 'PostCtrl'
});
}])
.controller('PostCtrl', ['$scope', '$firebaseArray', 'CommonProp', '$location', function($scope, $firebaseArray, CommonProp, $location) {
// if user is not logged in, redirect to sign in page
if (!CommonProp.getUser()) {
$location.path('/signin');
}
$scope.addPost = function() {
var firebaseObj = new Firebase("https://amber-heat-2147.firebaseio.com/articles");
var fb = $firebaseArray(firebaseObj);
var title = $scope.article.title;
var content = $scope.article.content;
fb.$add({
title: title,
content: content,
author: CommonProp.getUser()
}).then(function(ref) {
$location.path('/home');
}, function(error) {
console.log("Error:", error);
});
};
$scope.logout = function(){
CommonProp.logoutUser();
}
}]);
|
var WALKING_SPEED_RATIO = 30; // how many times faster than walking speed are you?
var FIRST_PERSON = false;
var RESET_CAMERA_POSITION = function() {camera.position.set(-168, 25, -17);}
var PATH_ANIMATION_RUNNING = false;
function endPathAnimation() {
PATH_ANIMATION_RUNNING = false;
}
function nextCameraTween(path, index, sf, ef) {
var start = convertVec(coords[path[index]]);
var end = convertVec(coords[path[index+1]]);
if (index === 0) {start = (new THREE.Vector3()).lerpVectors(start, end, sf);}
if (index+1 === path.length - 1) {end = (new THREE.Vector3()).lerpVectors(start, end, 1-ef);}
var tween = new TWEEN.Tween(start).to(end, 500+start.distanceTo(end)*1400/WALKING_SPEED_RATIO);
tween.easing(TWEEN.Easing.Quadratic.InOut);
var dir = (new THREE.Vector3()).subVectors(end, start).normalize();
tween.onUpdate(function(){
controls.target = start;
});
if (index === path.length - 2) {
tween.onComplete(endPathAnimation);
return tween;
} else {
return tween.chain(nextCameraTween(path,index+1, sf, ef));
}
} |
//! moment.js locale configuration
//! locale : Galician [gl]
//! author : Juan G. Hurtado : https://github.com/juanghurtado
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var gl = moment.defineLocale('gl', {
months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'),
monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'),
monthsParseExact: true,
weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'),
weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'),
weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'H:mm',
LTS : 'H:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D [de] MMMM [de] YYYY',
LLL : 'D [de] MMMM [de] YYYY H:mm',
LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm'
},
calendar : {
sameDay : function () {
return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
},
nextDay : function () {
return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
},
nextWeek : function () {
return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
},
lastDay : function () {
return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT';
},
lastWeek : function () {
return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
},
sameElse : 'L'
},
relativeTime : {
future : function (str) {
if (str.indexOf('un') === 0) {
return 'n' + str;
}
return 'en ' + str;
},
past : 'hai %s',
s : 'uns segundos',
m : 'un minuto',
mm : '%d minutos',
h : 'unha hora',
hh : '%d horas',
d : 'un día',
dd : '%d días',
M : 'un mes',
MM : '%d meses',
y : 'un ano',
yy : '%d anos'
},
ordinalParse : /\d{1,2}º/,
ordinal : '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return gl;
})); |
/*=========================================================================================
File Name: symbols.js
Description: Flot symbols chart
----------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 1.1
Author: PIXINVENT
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
// Symbols chart
// ------------------------------
$(window).on("load", function(){
function generate(offset, amplitude) {
var res = [];
var start = 0, end = 10;
for (var i = 0; i <= 50; ++i) {
var x = start + i / 50 * (end - start);
res.push([x, amplitude * Math.sin(x + offset)]);
}
return res;
}
var data = [
{ data: generate(2, 1.8), points: { symbol: "circle" } },
{ data: generate(3, 1.5), points: { symbol: "square" } },
{ data: generate(4, 0.9), points: { symbol: "diamond" } },
{ data: generate(6, 1.4), points: { symbol: "triangle" } },
{ data: generate(7, 1.1), points: { symbol: "cross" } }
];
$.plot("#symbols", data, {
series: {
points: {
show: true,
radius: 3
}
},
grid: {
borderWidth: 1,
borderColor: "#e9e9e9",
color: '#999',
minBorderMargin: 20,
labelMargin: 10,
margin: {
top: 8,
bottom: 20,
left: 20
},
hoverable: true
},
colors: ['#00A5A8', '#626E82', '#FF7D4D','#FF4558', '#1B2942']
});
}); |
/**
* Heldesks' code (Zendesk, etc..)
*/
App.helpdesk = {
init: function () {
// fetch template content from the extension
if (window.location.hostname.indexOf('zendesk.com') !== -1) {
App.helpdesk.zendesk.init();
}
},
zendesk: {
init: function () {
// inject the zendesk script into the dom
var script = document.createElement('script');
script.type = "text/javascript";
script.src = chrome.extension.getURL("pages/helpdesk/zendesk.js");
if (document.body) {
document.body.appendChild(script);
script.onload = function () {
document.body.removeChild(script);
};
}
// forward the message to the
window.addEventListener('message', function(event) {
if (event.data && event.data.request && event.data.request === 'suggestion-used') {
chrome.runtime.sendMessage({
'request': 'suggestion-used',
'data': {
'agent': {
'host': window.location.host,
'name': $('#face_box .name').text()
},
'url': window.location.href,
'template_id': event.data.template_id
}
});
}
});
var ticketUrl = "";
var ticketInterval = setInterval(function () {
if (window.location.pathname.indexOf('/agent/tickets/') !== -1) {
if (!ticketUrl || ticketUrl !== window.location.pathname) {
ticketUrl = window.location.pathname;
$('.macro-suggestions-container').remove();
var bodyInterval = setInterval(function () {
var subject = '';
var body = '';
$('.workspace').each(function (i, workspace) {
workspace = $(workspace);
if (workspace.css('display') !== 'none') {
var firstEvent = workspace.find('.event-container .event:first');
var isAgent = firstEvent.find('.user_photo').hasClass('agent');
// If it's an agent who has the last comment no point in suggesting anything
if (isAgent) {
return false;
}
subject = workspace.find('input[name=subject]').val();
body = firstEvent.find('.zd-comment').text();
}
});
if (!subject || !subject.length || !body.length) {
return;
}
clearInterval(bodyInterval);
chrome.runtime.sendMessage({
'request': 'suggestion',
'data': {
'agent': {
'host': window.location.host,
'name': $('#face_box .name').text()
},
'url': window.location.href,
'subject': subject,
'to': '',
'cc': '',
'bcc': '',
'from': '',
'body': body,
'helpdesk': 'zendesk'
}
}, function (macros) {
if (!_.size(macros)) {
return;
}
$('.macro-suggestions-container').remove();
var macroContainer = $("<div class='macro-suggestions-container'>");
for (var i in macros) {
var macro = macros[i];
var macroBtn = $("<a class='macro-suggestion'>");
var macroEl = $("<span class='macro-title'>");
/*
var scoreEl = $('<span class="macro-score"> </span>');
if (macro.score >= 0.9) {
scoreEl.addClass('macro-score-high');
}
if (macro.score >= 0.7 && macro.score < 0.9) {
scoreEl.addClass('macro-score-medium');
}
if (macro.score < 0.7) {
scoreEl.addClass('macro-score-low');
}
*/
macroBtn.attr('onclick', "gorgiasApplyMacroSuggestion(" + macro["external_id"] + ")");
macroBtn.attr('title', macro.body.replace(/\n/g, "<br />"));
macroBtn.attr('data-toggle', "tooltip");
macroBtn.attr('data-html', "true");
macroBtn.attr('data-placement', "bottom");
macroEl.html(macro.title);
macroBtn.append(macroEl);
//macroBtn.append(scoreEl);
macroContainer.append(macroBtn);
}
$('.comment_input .content .options').before(macroContainer);
});
}, 200);
}
} else {
ticketUrl = "";
}
}, 200);
}
}
};
|
/**
* Author: thegoldenmule
* Date: 3/17/13
*/
(function (global) {
"use strict";
var colorShaderVS = {
name: "color-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// calculate color
"vColor = uColor * aColor;" +
"}"
};
var colorShaderFS = {
name: "color-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"void main(void) {" +
"gl_FragColor = vColor;" +
"}"
};
var textureShaderVS = {
name: "texture-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// pass color + uv through
"vColor = aColor * uColor;" +
"vUV = aUV;" +
"}"
};
var textureShaderFS = {
name: "texture-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"uniform sampler2D uMainTextureSampler;" +
"void main(void) {" +
"gl_FragColor = texture2D(uMainTextureSampler, vUV) * vColor;" +
"}"
};
var spriteSheetShaderVS = {
name: "ss-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"varying vec4 vVertexColor;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// pass color + uv through
"vColor = uColor;" +
// note that in this shader, color.xy is the previous frame's uvs!
"vUV = aUV;" +
"vVertexColor = aColor;" +
"}"
};
var spriteSheetShaderFS = {
name: "ss-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"varying vec4 vVertexColor;" +
"varying vec2 vUV;" +
"uniform sampler2D uMainTextureSampler;" +
"uniform float uFutureBlendScalar;" +
"void main(void) {" +
"vec4 currentFrame = texture2D(uMainTextureSampler, vUV);" +
"vec4 futureFrame = texture2D(uMainTextureSampler, vec2(vVertexColor.xy));" +
"gl_FragColor = futureFrame * uFutureBlendScalar + currentFrame * (1.0 - uFutureBlendScalar);" +
"}"
};
var boundingBoxShaderVS = {
name: "bb-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 0.0, 1.0);" +
"vUV = aUV;" +
"}"
};
var boundingBoxShaderFS = {
name: "bb-shader-fs",
type: "x-shader/x-fragment",
body:
"varying vec2 vUV;" +
"void main(void) {" +
"gl_FragColor = vec4(1.0, 0.0, 0.0, 0.2);" +
"}"
};
var particleShaderVS = {
name: "particle-shader-vs",
type: "x-shader/x-vertex",
body:
"precision highp float;" +
"uniform mat4 uProjectionMatrix;" +
"uniform mat4 uModelViewMatrix;" +
"uniform vec4 uColor;" +
"uniform float uDepth;" +
"attribute vec2 aPosition;" +
"attribute vec2 aUV;" +
"attribute vec4 aColor;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"void main(void) {" +
// vertex transform
"gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, uDepth, 1.0);" +
// pass color + uv through
"vColor = aColor * uColor;" +
"vUV = aUV;" +
"}"
};
var particleShaderFS = {
name: "particle-shader-fs",
type: "x-shader/x-fragment",
body:
"precision highp float;" +
"varying vec4 vColor;" +
"varying vec2 vUV;" +
"uniform sampler2D uMainTextureSampler;" +
"void main(void) {" +
"gl_FragColor = texture2D(uMainTextureSampler, vUV) * vColor;" +
"}"
};
global.__DEFAULT_SHADERS = [
colorShaderVS,
colorShaderFS,
textureShaderVS,
textureShaderFS,
spriteSheetShaderFS,
spriteSheetShaderVS,
boundingBoxShaderVS,
boundingBoxShaderFS,
particleShaderVS,
particleShaderFS
];
})(this); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.