prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>no_answer.py<|end_file_name|><|fim▁begin|># encoding=utf-8 from courtesy import courtesy_reply from log_decorator import error_logging<|fim▁hole|>def response(com, answer, **kwargs): return courtesy_reply(('na',), **kwargs)<|fim▁end|>
@error_logging('na')
<|file_name|>acc_lib.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Acc Lib - Used by account contasis pre account line pre Created: 11 oct 2020 Last up: 29 mar 2021 """ import datetime class AccFuncs: @staticmethod def static_method(): # the static method gets passed nothing return "I am a static method" @classmethod def class_method(cls): # the class method gets passed the class (in this case ModCLass) return "I am a class method" def instance_method(self): # An instance method gets passed the instance of ModClass return "I am an instance method" #------------------------------------------------ Correct Time ----------------- # Used by Account Line # Correct Time # Format: 1876-10-10 00:00:00 @classmethod def correct_time(cls, date, delta): if date != False: year = int(date.split('-')[0]) if year >= 1900: DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT_sp = "%d/%m/%Y %H:%M" date_field1 = datetime.datetime.strptime(date, DATETIME_FORMAT) date_corr = date_field1 + datetime.timedelta(hours=delta,minutes=0) date_corr_sp = date_corr.strftime(DATETIME_FORMAT_sp) return date_corr, date_corr_sp # correct_time # ----------------------------------------------------- Get Orders Filter ------ # Provides sales between begin date and end date. # Sales and Cancelled also. @classmethod def get_orders_filter(cls, obj, date_bx, date_ex): # Dates #DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" DATETIME_FORMAT = "%Y-%m-%d" date_begin = date_bx + ' 05:00:00' date_end_dt = datetime.datetime.strptime(date_ex, DATETIME_FORMAT) + datetime.timedelta(hours=24) + datetime.timedelta(hours=5, minutes=0) date_end = date_end_dt.strftime('%Y-%m-%d %H:%M') #print date_end_dt # Search Orders orders = obj.env['sale.order'].search([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], order='x_serial_nr asc', #limit=1, ) # Count count = obj.env['sale.order'].search_count([ ('state', 'in', ['sale', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<', date_end), ], #order='x_serial_nr asc', #limit=1, )<|fim▁hole|> # ------------------------------------------------------ Get Net and Tax ------- # Get Net and Tax @classmethod def get_net_tax(cls, amount): # Net x = amount / 1.18 net = float("{0:.2f}".format(x)) # Tax x = amount * 0.18 tax = float("{0:.2f}".format(x)) return net, tax # get_net_tax<|fim▁end|>
return orders, count # get_orders_filter
<|file_name|>simple.rs<|end_file_name|><|fim▁begin|>extern crate pronghorn; use pronghorn::app::App; use pronghorn::{Context, Response}; fn root(_context: Context) -> Response { let mut res = Response::new(); res.set_body("/"); res } fn foo(_context: Context) -> Response { let mut res = Response::new(); res.set_body("/foo"); res } fn username(context: Context) -> Response { let username = context.params.get("username").unwrap(); println!("{:?}", username); return Response::new(); } <|fim▁hole|> let addr = "127.0.0.1:3000".parse().unwrap(); let mut app = App::new(); app.router.get("/", root); app.router.get("/foo", foo); app.router.get("/user/{username}", username); app.run(&addr); }<|fim▁end|>
fn main() {
<|file_name|>visualizer.js<|end_file_name|><|fim▁begin|>import Boolius from "./boolius"; // which in turn imports all the classes it depends upon import XMLius from "./xmlius"; import Mathius from "./mathius"; window.onload = function () { d3.select("#modeSelect").on("change", function (e) { var selectedMode = d3.select("#modeSelect").node().value.toLowerCase(); changeMode(selectedMode); }); function changeMode(newMode) { if (newMode.indexOf("arithmetic") > -1) { // the user wants to look at arithmetic expressions. // is boolius already loaded? if (!evaluator || !(evaluator instanceof Mathius)) { var grammarObject = [ [["NUMERIC", "^", "NUMERIC"], "NUMERIC"], [["NUMERIC", "*", "NUMERIC"], "NUMERIC"], [["NUMERIC", "+", "NUMERIC"], "NUMERIC", ["*", "/", "^"]], [["NUMERIC", "-", "NUMERIC"], "NUMERIC", ["*", "/", "^"]], [["NUM_LIT"], "NUMERIC"], [["(", "NUMERIC", ")"], "NUMERIC"], ]; let IGNORE = true; let tokenDefinitions = [ [/\s+/, "", IGNORE], // ignore whitespace [/\^/, "^"], // this is the escaped form of ^ [/\(/, "("], [/\)/, ")"], [/\+/, "+"], [/-/, "-"], [/\*/, "*"], [/\//, "/"], [/[-+]?[0-9]*\.?[0-9]+/, "NUM_LIT"], [/[a-zA-Z]+/, "IDENT"], [/.+/, "DIRTYTEXT"], ]; makeEvaluatorAndInitialize( new Mathius(tokenDefinitions, grammarObject), "1 + 2 ^ (5 - 2) * 3", "Click operators to expand or collapse." ); } } else if (newMode.indexOf("boolean") > -1) { // the user wants to look at boolean expressions. // is boolius already loaded? if (!evaluator || !(evaluator instanceof Boolius)) { var grammarObject = [ [["TRUE"], "BOOLEAN"], [["FALSE"], "BOOLEAN"], [["IDENT"], "BOOLEAN"], [["!", "BOOLEAN"], "BOOLEAN"], [["BOOLEAN", "&", "BOOLEAN"], "BOOLEAN"], [["BOOLEAN", "|", "BOOLEAN"], "BOOLEAN"], [["(", "BOOLEAN", ")"], "BOOLEAN"], ]; let IGNORE = true; let tokenDefinitions = [ [/\s+/, "", IGNORE], // ignore whitespace<|fim▁hole|> [/XOR/i, "^"], [/OR/i, "|"], [/\^/, "^"], // this is the escaped form of ^ [/\!/, "!"], // this is the escaped form of ! [/NOT/i, "!"], [/\(/, "("], [/\)/, ")"], [/(true)(?![a-zA-Z0-9])/i, "TRUE"], [/(false)(?![a-zA-Z0-9])/i, "FALSE"], [/[a-zA-Z]+/, "IDENT"], [/.+/, "DIRTYTEXT"], ]; makeEvaluatorAndInitialize( new Boolius(tokenDefinitions, grammarObject), "((d && c)) || (!b && a) && (!d || !a) && (!c || !b)", "Click operators to expand or collapse. Click leaf nodes to toggle true/false." ); } } else if (newMode.indexOf("xml") > -1) { // the user wants to look at boolean expressions. // is boolius already loaded? if (!evaluator || !(evaluator instanceof XMLius)) { let grammarObject = [ [["OPENCOMMENT", "WILDCARD", "CLOSECOMMENT"], "COMMENT"], // comments will be engulfed by the text of a node // and ignored when the node is asked for its text as a string [["COMMENT"], "#TEXT_NODE"], [["<", "/", "IDENT", ">"], "CLOSETAG"], [["<", "IDENT", ">"], "OPENTAG"], [["<", "IDENT", "/", ">"], "XMLNODE"], [["<", "IDENT", "IDENT", "=", '"', "WILDCARD", '"'], "OPENTAGSTART"], /* Some recursive self-nesting here */ [ ["OPENTAGSTART", "IDENT", "=", '"', "WILDCARD", '"'], "OPENTAGSTART", ], [["OPENTAGSTART", ">"], "OPENTAG"], // can't have two identifiers in a row, unless we're between an opening and closing tag // a/k/a node.text [["IDENT", "IDENT"], "#TEXT_NODE"], [["IDENT", "#TEXT_NODE"], "#TEXT_NODE"], [["#TEXT_NODE", "#TEXT_NODE"], "#TEXT_NODE"], // let's also have nested nodes engulfed in the NODETEXT [["XMLNODE", "#TEXT_NODE"], "#TEXT_NODE"], [["XMLNODES", "#TEXT_NODE"], "#TEXT_NODE"], [["#TEXT_NODE", "XMLNODE"], "#TEXT_NODE"], [["#TEXT_NODE", "XMLNODES"], "#TEXT_NODE"], [["OPENTAG", "CLOSETAG"], "XMLNODE"], [["OPENTAG", "#TEXT_NODE", "CLOSETAG"], "XMLNODE"], [["OPENTAG", "XMLNODE", "CLOSETAG"], "XMLNODE"], [["XMLNODE", "XMLNODE"], "XMLNODES"], [["OPENTAG", "XMLNODES", "CLOSETAG"], "XMLNODE"], ]; let IGNORE = true; let tokenDefinitions = [ [/\s+/, "", IGNORE], [/<!--/, "OPENCOMMENT"], [/-->/, "CLOSECOMMENT"], [/\//, "/"], [/>/, ">"], [/</, "<"], [/=/, "="], [/"/, '"'], [/'/, '"'], [/[-+]?[0-9]*\.?[0-9]+/, "NUM_LIT"], [/[a-zA-Z]+[a-zA-Z0-9-]*/, "IDENT"], // having trapped all these things, what's left is nodetext [/[^<]+/, "#TEXT_NODE"], ]; makeEvaluatorAndInitialize( new XMLius(tokenDefinitions, grammarObject), `<div class="hintwrapper"><div class="hint">Click operators to expand or collapse. Click leaf nodes to toggle true/false.</div><div class="styled-select green semi-square" style="bold"></div></div>`, "Mouseover nodes to see attributes. Click nodetext to see content." ); } } } function makeEvaluatorAndInitialize(newEvaluator, statement, hintText) { assignEvaluator(newEvaluator); d3.select("#statement").node().value = statement; d3.select("div.hint").text(hintText); evaluateStatement(); } function assignEvaluator(newEvaluator) { // don't change if the user wants what they already have if (evaluator && newEvaluator.constructor === evaluator.constructor) return; evaluator = newEvaluator; } var evaluator; var winWidth = Math.max(1000, window.innerWidth); let header = document.querySelector("header")[0]; var winHeight = Math.max(500, window.innerHeight - 240); var winWidth = Math.max(800, window.innerWidth); var m = [0, 120, 140, 120], w = winWidth - m[1] - m[3], h = winHeight - m[0] - m[2], i = 0, root; var tree = d3.layout.tree().size([h, w]); var diagonal = d3.svg.diagonal().projection(function (d) { return [d.y, d.x]; }); var vis = d3 .select("#body") .append("svg:svg") .attr("width", w + m[1] + m[3]) .attr("height", h + m[0] + m[2]) .append("svg:g") .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); vis .append("text") .attr("opacity", 1) .attr("y", 246) .attr("dy", "1.71em") .style("font-size", "34px") .style("text-anchor", "end") .attr("id", "result") .text(""); d3.select("#testbutton").on("click", function (e) { evaluateStatement(); }); d3.select("#statement").on("keyup", function () { if (d3.event.keyCode == 13) { d3.select("#testbutton").on("click")(); } }); var parseTree; function evaluateStatement() { var statement = d3.select("#statement").node().value; parseTree = evaluator.parse(statement); displayJSON(parseTree); } function displayJSON(json) { if (json == null) return; root = json; root.x0 = h / 2; root.y0 = 0; //d3.select("#statement").val( root.title ); d3.select("#statement").property("value", root.expressionString); d3.select("#result").text(root.value); function toggleAll(d, delay) { if (!delay) delay = 1; if (d.children) { toggle(d); } if (d._children) { toggle(d); } } // Initialize the display to show all nodes. root.children.forEach(toggleAll, 444); update(root); } // Toggle children. function toggle(d, showOverlay) { if (d == undefined) return; //boolean if (d.value === true || d.value === false) { if (d.children) { // hide the children by moving them into _children d._children = d.children; d.children = null; } else { // bring back the hidden children d.children = d._children; d._children = null; } var hasNoChildren = !d.children && !d._children; if (!hasNoChildren) { // has an array in d.children or d._children // but it might be empty! if (d.children && d.children.length == 0) hasNoChildren = true; if (d._children && d._children.length == 0) hasNoChildren = true; } if (hasNoChildren) { // it's a leaf // toggle true/false if (d.value === true || d.value === false) { d.value = !d.value; //var myInt = parseInt( d.name ); //conditionTruthValues[ myInt ] = d.value; var myVar = d.name; evaluator.state[myVar] = d.value; updateWithoutDeleting(root); } } } // you clicked something that isn't in a boolean flow else { if (showOverlay) { var attributeText = d.attributes ? JSON.stringify(d.attributes) : "None"; if (!d.children && !d._children) { // it's a leaf //showValueOverlay( d.value ); showValueOverlay( "Attributes: " + attributeText + "</br>Content: " + d.value ); } //oops, we wanted to collapse this thing else { //showValueOverlay( "Attributes: " + attributeText + "</br>Content: " + d.value ); if (d.children) { // hide the children by moving them into _children d._children = d.children; d.children = null; } else { // bring back the hidden children d.children = d._children; d._children = null; } } } } } function showValueOverlay(val) { $("#valueModalText").html(val); $("#valueModal").modal("show"); } function updateWithoutDeleting() { parseTree = evaluator.evaluateParseTree(); updateObjectAndItsChildren(parseTree, root); d3.select("#result").text(root.value); } function updateObjectAndItsChildren(newObjectTemp, rootTemp) { rootTemp.value = newObjectTemp.value; if (!newObjectTemp.children) return; for (var i = 0; i < newObjectTemp.children.length; i++) { if (rootTemp.children) { updateObjectAndItsChildren( newObjectTemp.children[i], rootTemp.children[i] ); } else { if (rootTemp._children) { updateObjectAndItsChildren( newObjectTemp.children[i], rootTemp._children[i] ); } } } } function update(source) { var duration = d3.event && d3.event.altKey ? 5000 : 500; // Compute the new tree layout. var nodes = tree.nodes(root).reverse(); // Normalize for fixed-depth. // OK -- why is d.y correlated with the horizontal position here??? widthPerNode = 110; var body = d3.select("body"); var svg = body.select("svg"); var widthInPixels = svg.style("width").replace("px", ""); widthInPixels = parseInt(widthInPixels); var widthPerNode = widthInPixels / nodes.length; nodes.forEach(function (d) { d.y = d.depth * widthPerNode; }); d3.select("#result") .transition() .duration(duration) .attr("x", nodes[nodes.length - 1].y - 40) .attr("y", function (d) { return nodes[nodes.length - 1].x - 48; }); // Update the nodes… var node = vis.selectAll("g.node").data(nodes, function (d) { return d.id || (d.id = ++i); }); var modalOverlayTimeout; // Enter any new nodes at the parent's previous position. var nodeEnter = node .enter() .append("svg:g") .attr("class", "node") .attr("transform", function (d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) .on("click", function (d) { if (modalOverlayTimeout != null) clearTimeout(modalOverlayTimeout); toggle(d, true); update(d); }) .on("mouseover", function (d) { var attributeText = d.attributes ? JSON.stringify(d.attributes) : ""; if (attributeText.length > 0) { if (modalOverlayTimeout != null) clearTimeout(modalOverlayTimeout); modalOverlayTimeout = setTimeout(() => { showValueOverlay( "Attributes: " + attributeText + "</br>Content: " + d.value ); }, 800); } }); nodeEnter .append("svg:circle") .attr("r", 1e-6) .style("stroke", function (d) { return d.value ? "green" : "red"; }) .style("fill", function (d) { return d._children ? "grey" : "#fff"; }); nodeEnter .append("svg:text") .attr("x", function (d) { return d.children || d._children ? -1 : 17; }) .attr("y", function (d) { return d.children || d._children ? 18 : -1; }) .attr("dy", ".35em") .attr("text-anchor", function (d) { return d.children || d._children ? "middle" : "left"; }) // .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) .text(function (d) { return d.name; }) .style("fill-opacity", 1e-6); // Transition nodes to their new position. var nodeUpdate = node .transition() .duration(duration) .style("stroke", function (d) { return d.value ? "green" : "red"; }) .attr("transform", function (d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate .select("circle") .attr("r", 8.5) .style("stroke", function (d) { return d.value ? "green" : "red"; }) .style("fill", function (d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeUpdate.select("text").style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node .exit() .transition() .duration(duration) .attr("transform", function (d) { return "translate(" + source.y + "," + source.x + ")"; }) .remove(); nodeExit.select("circle").attr("r", 1e-6); nodeExit.select("text").style("fill-opacity", 1e-6); // Update the links… var link = vis.selectAll("path.link").data(tree.links(nodes), function (d) { return d.target.id; }); // Enter any new links at the parent's previous position. link .enter() .insert("svg:path", "g") .attr("class", "link") .attr("d", function (d) { var o = { x: source.x0, y: source.y0 }; return diagonal({ source: o, target: o }); }) .transition() .duration(duration) .attr("d", diagonal); // Transition links to their new position. link.transition().duration(duration).attr("d", diagonal); // Transition exiting nodes to the parent's new position. link .exit() .transition() .duration(duration) .attr("d", function (d) { var o = { x: source.x, y: source.y }; return diagonal({ source: o, target: o }); }) .remove(); // Stash the old positions for transition. nodes.forEach(function (d) { d.x0 = d.x; d.y0 = d.y; }); } changeMode("boolean"); evaluateStatement(); };<|fim▁end|>
[/&&/, "&"], [/AND/i, "&"], [/\|\|/, "|"], // this is the escaped form of ||
<|file_name|>squirrelStartup.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2015-2016 Yuya Ochiai // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import AutoLaunch from 'auto-launch'; import {app} from 'electron'; function shouldQuitApp(cmd) { if (process.platform !== 'win32') { return false; } const squirrelCommands = ['--squirrel-install', '--squirrel-updated', '--squirrel-uninstall', '--squirrel-obsolete']; return squirrelCommands.includes(cmd); } async function setupAutoLaunch(cmd) { const appLauncher = new AutoLaunch({ name: app.getName(), isHidden: true, }); if (cmd === '--squirrel-uninstall') { // If we're uninstalling, make sure we also delete our auto launch registry key await appLauncher.disable(); } else if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') { // If we're updating and already have an registry entry for auto launch, make sure to update the path const enabled = await appLauncher.isEnabled(); if (enabled) { await appLauncher.enable(); }<|fim▁hole|> export default function squirrelStartup(callback) { if (process.platform === 'win32') { const cmd = process.argv[1]; setupAutoLaunch(cmd).then(() => { if (require('electron-squirrel-startup') && callback) { // eslint-disable-line global-require callback(); } }); return shouldQuitApp(cmd); } return false; }<|fim▁end|>
} }
<|file_name|>bge.texture.1.py<|end_file_name|><|fim▁begin|>""" Texture Replacement +++++++++++++++++++ Example of how to replace a texture in game with an external image. ``createTexture()`` and ``removeTexture()`` are to be called from a module Python Controller. """ from bge import logic from bge import texture def createTexture(cont): """Create a new Dynamic Texture""" obj = cont.owner # get the reference pointer (ID) of the internal texture ID = texture.materialID(obj, 'IMoriginal.png')<|fim▁hole|> # create a texture object object_texture = texture.Texture(obj, ID) # create a new source with an external image url = logic.expandPath("//newtexture.jpg") new_source = texture.ImageFFmpeg(url) # the texture has to be stored in a permanent Python object logic.texture = object_texture # update/replace the texture logic.texture.source = new_source logic.texture.refresh(False) def removeTexture(cont): """Delete the Dynamic Texture, reversing back the final to its original state.""" try: del logic.texture except: pass<|fim▁end|>
<|file_name|>BaseField.java<|end_file_name|><|fim▁begin|>package com.infox.sysmgr.entity.base; import java.io.Serializable; public class BaseField implements Serializable { private static final long serialVersionUID = 1L; private int hashCode = Integer.MIN_VALUE; // fields private java.lang.String name; private java.lang.String fieldType; private java.lang.String fieldDefault; private java.lang.String fieldProperty; private java.lang.String comment; private java.lang.String nullable; private java.lang.String extra; public int getHashCode() { return hashCode; } public void setHashCode(int hashCode) { this.hashCode = hashCode; } public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getFieldType() { return fieldType; } public void setFieldType(java.lang.String fieldType) { this.fieldType = fieldType; } public java.lang.String getFieldDefault() { return fieldDefault; } public void setFieldDefault(java.lang.String fieldDefault) { this.fieldDefault = fieldDefault; } public java.lang.String getFieldProperty() { return fieldProperty; } public void setFieldProperty(java.lang.String fieldProperty) { this.fieldProperty = fieldProperty; } public java.lang.String getComment() { return comment; } public void setComment(java.lang.String comment) { this.comment = comment; <|fim▁hole|> } public void setNullable(java.lang.String nullable) { this.nullable = nullable; } public java.lang.String getExtra() { return extra; } public void setExtra(java.lang.String extra) { this.extra = extra; } }<|fim▁end|>
} public java.lang.String getNullable() { return nullable;
<|file_name|>span_length.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::old_io::{File, Command}; use std::iter::repeat; use std::rand::{thread_rng, Rng}; use std::{char, env}; // creates a file with `fn main() { <random ident> }` and checks the // compiler emits a span of the appropriate length (for the // "unresolved name" message); currently just using the number of code // points, but should be the number of graphemes (FIXME #7043) fn random_char() -> char { let mut rng = thread_rng(); // a subset of the XID_start Unicode table (ensuring that the // compiler doesn't fail with an "unrecognised token" error) let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) { 1 => (0x41, 0x5a), 2 => (0xf8, 0x1ba), 3 => (0x1401, 0x166c), _ => (0x10400, 0x1044f) }; char::from_u32(rng.gen_range(lo, hi + 1)).unwrap() } fn main() { let args: Vec<String> = env::args().collect(); let rustc = &args[1]; let tmpdir = Path::new(&args[2]); let main_file = tmpdir.join("span_main.rs"); for _ in 0..100 { let n = thread_rng().gen_range(3, 20); { let _ = write!(&mut File::create(&main_file).unwrap(), "#![feature(non_ascii_idents)] fn main() {{ {} }}", // random string of length n (0..n).map(|_| random_char()).collect::<String>()); } // rustc is passed to us with --out-dir and -L etc., so we // can't exec it directly let result = Command::new("sh") .arg("-c") .arg(&format!("{} {}", rustc, main_file.as_str() .unwrap())) .output().unwrap(); let err = String::from_utf8_lossy(&result.error); // the span should end the line (e.g no extra ~'s) let expected_span = format!("^{}\n", repeat("~").take(n - 1) .collect::<String>()); assert!(err.contains(&expected_span)); } // Test multi-column characters and tabs { let _ = write!(&mut File::create(&main_file).unwrap(), r#"extern "路濫狼á́́" fn foo() {{}} extern "路濫狼á́" fn bar() {{}}"#); } // Extra characters. Every line is preceded by `filename:lineno <actual code>` let offset = main_file.as_str().unwrap().len() + 3; let result = Command::new("sh") .arg("-c") .arg(format!("{} {}", rustc, main_file.as_str() .unwrap())) .output().unwrap(); <|fim▁hole|> // First snake is 8 ~s long, with 7 preceding spaces (excluding file name/line offset) let expected_span = format!("\n{}^{}\n", repeat(" ").take(offset + 7).collect::<String>(), repeat("~").take(8).collect::<String>()); assert!(err.contains(expected_span.as_slice())); // Second snake is 8 ~s long, with 36 preceding spaces let expected_span = format!("\n{}^{}\n", repeat(" ").take(offset + 36).collect::<String>(), repeat("~").take(8).collect::<String>()); assert!(err.contains(expected_span.as_slice())); }<|fim▁end|>
let err = String::from_utf8_lossy(result.error.as_slice()); // Test both the length of the snake and the leading spaces up to it
<|file_name|>apihelper.go<|end_file_name|><|fim▁begin|>// Package apihelper contains some methods which make working with the http // package a bit nicer package apihelper import ( "encoding/json" "fmt" "io" "net/http" "github.com/mediocregopher/mediocre-api/common" "github.com/mediocregopher/mediocre-api/pickyjson" ) // ErrUnlessMethod checks that the given request is using one of the given // HTTP methods. If it is not than an error is sent back to the client and true // is returned func ErrUnlessMethod( w http.ResponseWriter, r *http.Request, methods ...string, ) bool { for i := range methods { if r.Method == methods[i] { return false } } http.Error(w, "invalid method", 400) return false } // Prepare takes in a request and its response, and performs the following // checks/enhancements: // // * If any methods are given, ensure the request is using one of them.<|fim▁hole|>// given bodySizeLimit // // * If params isn't nil attempt to json.Unmarshal the request body into it. If // that fails an error is sent to the client and false is returned // func Prepare( w http.ResponseWriter, r *http.Request, params interface{}, bodySizeLimit int64, ) bool { r.Body = http.MaxBytesReader(w, r.Body, bodySizeLimit) if params != nil { if err := json.NewDecoder(r.Body).Decode(params); err != nil { http.Error(w, err.Error(), 400) return false } if err := pickyjson.CheckRequired(params); err != nil { common.HTTPError(w, r, err) return false } if err := pickyjson.CheckRequired(&params); err != nil { common.HTTPError(w, r, err) return false } } return true } // JSONSuccess json encodes the given return value and writes that to the given // io.Writer (presumably an http.ResponseWriter) func JSONSuccess(w io.Writer, i interface{}) { json.NewEncoder(w).Encode(i) fmt.Fprintf(w, "\n") }<|fim▁end|>
// Otherwise send error to client and return false // // * Replace r.Body with a MaxBytesReader which will stop the reading at the
<|file_name|>custom_actions.py<|end_file_name|><|fim▁begin|>import pylogging import os # Logs Dir Absolute Path logs_path = os.path.dirname(os.path.abspath(__file__)) + '/logs/' # Create Logger Instance logger = pylogging.PyLogging(LOG_FILE_PATH = logs_path) def customAction1(type, msg): # Custom Action Goes Here pass # Add Action actionIden1 = logger.addAction(customAction1) def customAction2(type, msg): # Custom Action Goes Here pass<|fim▁hole|># Add Action actionIden2 = logger.addAction(customAction2) # To Remove Action1 logger.removeAction(actionIden1) # Log Info Message logger.info("Info Message") # Log Warning Message logger.warning("Warning Message.") # Log Error Message logger.error("Error Message.") # Log Critical Message logger.critical("Critical Message.") # Log Normal Message logger.log("Normal Log Message.")<|fim▁end|>
<|file_name|>group.js<|end_file_name|><|fim▁begin|>/*! * Copyright 2012 Sakai Foundation (SF) Licensed under the * Educational Community License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ require(['jquery', 'oae.core'], function($, oae) { // Get the group id from the URL. The expected URL is /group/<groupId> var groupId = document.location.pathname.split('/')[2]; if (!groupId) { oae.api.util.redirect().login(); } // Variable used to cache the requested user's profile var groupProfile = null; // Variable used to cache the group's base URL var baseUrl = '/group/' + groupId; /** * Get the group's basic profile and set up the screen. If the groups * can't be found or is private to the current user, the appropriate * error page will be shown */ var getGroupProfile = function() { oae.api.group.getGroup(groupId, function(err, profile) { if (err && err.code === 404) { oae.api.util.redirect().notfound(); } else if (err && err.code === 401) { oae.api.util.redirect().accessdenied(); } groupProfile = profile; setUpClip(); setUpNavigation(); // Set the browser title oae.api.util.setBrowserTitle(groupProfile.displayName); }); }; $(document).on('oae.context.get', function() { $(document).trigger('oae.context.send', groupProfile); }); $(document).trigger('oae.context.send', groupProfile); /** * Render the group's clip, containing the profile picture, display name as well as the * group's admin options */ var setUpClip = function() { oae.api.util.template().render($('#group-clip-template'), {'group': groupProfile}, $('#group-clip-container')); // Only show the create and upload clips to managers if (groupProfile.isManager) { $('#group-actions').show(); } }; /** * Set up the left hand navigation with the me space page structure */ var setUpNavigation = function() { // Structure that will be used to construct the left hand navigation var lhNavigation = [ { 'id': 'activity', 'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'), 'icon': 'icon-dashboard', 'layout': [ { 'width': 'span8', 'widgets': [ { 'id': 'activity', 'settings': {<|fim▁hole|> 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] }, { 'id': 'library', 'title': oae.api.i18n.translate('__MSG__LIBRARY__'), 'icon': 'icon-briefcase', 'layout': [ { 'width': 'span12', 'widgets': [ { 'id': 'library', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] }, { 'id': 'members', 'title': oae.api.i18n.translate('__MSG__MEMBERS__'), 'icon': 'icon-user', 'layout': [ { 'width': 'span12', 'widgets': [ { 'id': 'participants', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] } ]; $(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]); $(window).on('oae.ready.lhnavigation', function() { $(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]); }); }; getGroupProfile(); });<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|><% if (djangoVersion != '2.0') { %> from django.conf.urls import url, include <% } else { %> from django.urls import path, include<|fim▁hole|>from <%= appName %> import views <% if (includeLoginPage == true) { %> from <%= appName %>.forms import AuthenticationForm from django.contrib.auth.views import login, logout <% } %> <% if (djangoVersion != '2.0') { %> urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^', include('<%= appName %>.urls')), url(r'^admin/', include(admin.site.urls)), ] <% if (includeLoginPage == true) { %> urlpatterns += [ url(r'^accounts/login/$', login, { 'template_name': 'login.html', 'authentication_form': AuthenticationForm }, name='login'), url(r'^accounts/logout/$', logout, { 'next_page': '/' }, name='logout'), ] <% } %> <% } else { %> urlpatterns = [ path(r'', views.index, name="index"), path(r'', include('<%= appName %>.urls')), path(r'admin/', admin.site.urls), ] <% if (includeLoginPage == true) { %> urlpatterns += [ path(r'accounts/login', login, { 'template_name': 'login.html', 'authentication_form': AuthenticationForm }, name='login'), path(r'accounts/logout', logout, { 'next_page': '/' }, name='logout'), ] <% } %> <% } %><|fim▁end|>
<% } %> from django.contrib import admin
<|file_name|>initramfs.rs<|end_file_name|><|fim▁begin|>use std::process::Command; use ask; <|fim▁hole|>pub fn rebuild() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status().expect("Failed to run mkinitcpio"); if !status.success() { println!("Got an error from mkinitcpio. Sorry, but you have to fix this on your own."); } else { skip_ask = true; } } else { println!("Please run your initramfs generator now and verify that everything works."); } if !skip_ask { if !ask::yesno("Done?") { println!("Aborted."); return false; } } true }<|fim▁end|>
<|file_name|>cluster.py<|end_file_name|><|fim▁begin|>from changes.api.serializer import Crumbler, register from changes.models.node import Cluster @register(Cluster) class ClusterCrumbler(Crumbler):<|fim▁hole|> 'name': instance.label, 'dateCreated': instance.date_created, }<|fim▁end|>
def crumble(self, instance, attrs): return { 'id': instance.id.hex,
<|file_name|>main.js<|end_file_name|><|fim▁begin|>/*price range*/ $('#sl2').slider(); var RGBChange = function() { $('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')') }; /*scroll to top*/ $(document).ready(function(){ $(function () { $.scrollUp({ scrollName: 'scrollUp', // Element ID scrollDistance: 300, // Distance from top/bottom before showing element (px) scrollFrom: 'top', // 'top' or 'bottom' scrollSpeed: 300, // Speed back to top (ms) easingType: 'linear', // Scroll to top easing (see http://easings.net/) animation: 'fade', // Fade, slide, none animationSpeed: 200, // Animation in speed (ms) scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object //scrollTarget: false, // Set a custom target element for scrolling to the top<|fim▁hole|> activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF' zIndex: 2147483647 // Z-Index for the overlay }); }); }); // Returns a random integer between min and max // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Replace url parameter - WishlistItems function replaceUrlParam(url, paramName, paramValue) { var pattern = new RegExp('(' + paramName + '=).*?(&|$)') var newUrl = url if (url.search(pattern) >= 0) { newUrl = url.replace(pattern, '$1' + paramValue + '$2'); } else { newUrl = newUrl + (newUrl.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue } return newUrl } // Scroll back to selected wishlist item if (window.location.hash != '') { var target = window.location.hash; //var $target = $(target); $('html, body').stop().animate({ //'scrollTop': $target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }<|fim▁end|>
scrollText: '<i class="fa fa-angle-up"></i>', // Text for element, can contain HTML scrollTitle: false, // Set a custom <a> title if required. scrollImg: false, // Set true to use image
<|file_name|>test_bytes_can_uplink_converter.py<|end_file_name|><|fim▁begin|># Copyright 2020. ThingsBoard # # Licensed under the Apache License, Version 2.0 (the "License"]; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import _struct import unittest from math import isclose from random import randint, uniform, choice from string import ascii_lowercase from thingsboard_gateway.connectors.can.bytes_can_uplink_converter import BytesCanUplinkConverter class BytesCanUplinkConverterTests(unittest.TestCase): def setUp(self): self.converter = BytesCanUplinkConverter() def _has_no_data(self, data): return bool(data is None or not data.get("attributes", []) and not data.get("telemetry", [])) def test_wrong_type(self): can_data = [0, 1, 0, 0, 0] configs = [{ "key": "var", "is_ts": True, "type": "wrong_type" }] tb_data = self.converter.convert(configs, can_data) self.assertTrue(self._has_no_data(tb_data)) def test_bool_true(self): can_data = [0, 1, 0, 0, 0] configs = [{ "key": "boolVar", "is_ts": True, "type": "bool", "start": 1 }] tb_data = self.converter.convert(configs, can_data) self.assertTrue(tb_data["telemetry"]["boolVar"]) def test_bool_false(self): can_data = [1, 0, 1, 1, 1] configs = [{ "key": "boolVar", "is_ts": False, "type": "bool", "start": 1 }] tb_data = self.converter.convert(configs, can_data) self.assertFalse(tb_data["attributes"]["boolVar"]) def _test_int(self, type, byteorder): int_value = randint(-32768, 32767) int_size = 2 can_data = [0, 0] configs = [{ "key": type + "Var", "is_ts": True, "type": type, "start": len(can_data), "length": int_size, "byteorder": byteorder, "signed": int_value < 0 }] can_data.extend(int_value.to_bytes(int_size, byteorder, signed=(int_value < 0))) tb_data = self.converter.convert(configs, can_data) self.assertEqual(tb_data["telemetry"][type + "Var"], int_value) def test_int_big_byteorder(self): self._test_int("int", "big") def test_int_little_byteorder(self): self._test_int("int", "little") def test_long_big_byteorder(self): self._test_int("long", "big") def test_long_little_byteorder(self): self._test_int("long", "little") def _test_float_point_number(self, type, byteorder): float_value = uniform(-3.1415926535, 3.1415926535) can_data = [0, 0] configs = [{ "key": type + "Var", "is_ts": True, "type": type, "start": len(can_data), "length": 4 if type[0] == "f" else 8, "byteorder": byteorder }] can_data.extend(_struct.pack((">" if byteorder[0] == "b" else "<") + type[0], float_value)) tb_data = self.converter.convert(configs, can_data) self.assertTrue(isclose(tb_data["telemetry"][type + "Var"], float_value, rel_tol=1e-05)) def test_float_big_byteorder(self): self._test_float_point_number("float", "big") def test_float_little_byteorder(self): self._test_float_point_number("float", "little") def test_double_big_byteorder(self): self._test_float_point_number("double", "big") def test_double_little_byteorder(self): self._test_float_point_number("double", "little") def _test_string(self, encoding="ascii"): str_length = randint(1, 8) str_value = ''.join(choice(ascii_lowercase) for _ in range(str_length)) configs = [{ "key": "stringVar", "is_ts": True, "type": "string", "start": 0, "length": str_length, "encoding": encoding }] can_data = str_value.encode(encoding) tb_data = self.converter.convert(configs, can_data) self.assertEqual(tb_data["telemetry"]["stringVar"], str_value) def test_string_default_ascii_encoding(self): self._test_string() def test_string_utf_8_string(self): self._test_string("utf-8") def _test_eval_int(self, number, strict_eval, expression): can_data = number.to_bytes(1, "big", signed=(number < 0)) # By default the strictEval flag is True configs = [{ "key": "var", "is_ts": True, "type": "int", "start": 0, "length": 1, "byteorder": "big", "signed": number < 0, "expression": expression, "strictEval": strict_eval }] return self.converter.convert(configs, can_data) def test_strict_eval_violation(self): number = randint(-128, 256) tb_data = self._test_eval_int(number, True, "pow(value, 2)") self.assertTrue(self._has_no_data(tb_data)) def test_strict_eval(self): number = randint(-128, 256) tb_data = self._test_eval_int(number, True, "value * value") self.assertEqual(tb_data["telemetry"]["var"], number * number) def test_no_strict_eval(self): number = randint(-128, 256) tb_data = self._test_eval_int(number, False, "pow(value, 2)") self.assertEqual(tb_data["telemetry"]["var"], number * number) def test_multiple_valid_configs(self): bool_value = True int_value = randint(0, 256) can_data = [0, int(bool_value), int_value, 0, 0, 0] configs = [ { "key": "boolVar", "type": "boolean", "is_ts": True, "start": 1 }, { "key": "intVar", "type": "int", "is_ts": False, "start": 2, "length": 4, "byteorder": "little", "signed": False }<|fim▁hole|> self.assertEqual(tb_data["telemetry"]["boolVar"], bool_value) self.assertEqual(tb_data["attributes"]["intVar"], int_value) def test_multiple_configs_one_invalid(self): bool_value = True invalid_length = 3 # Float requires 4 bytes can_data = [0, int(bool_value), randint(0, 256), 0, 0, 0] configs = [ { "key": "validVar", "type": "boolean", "is_ts": True, "start": 1 }, { "key": "invalidVar", "type": "float", "is_ts": False, "start": 2, "length": invalid_length } ] tb_data = self.converter.convert(configs, can_data) self.assertEqual(tb_data["telemetry"]["validVar"], bool_value) self.assertIsNone(tb_data["attributes"].get("invalidVar")) if __name__ == '__main__': unittest.main()<|fim▁end|>
] tb_data = self.converter.convert(configs, can_data)
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url, include, patterns from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings urlpatterns = patterns('',<|fim▁hole|> url(r'^$', views.index, name='index'), )<|fim▁end|>
<|file_name|>agent0.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is a starting point for you. You will need to greatly # modify this code if you want to do anything useful. But this # should help you to know how to interact with BZRC in order to # get the information you need. # # After starting the bzrflag server, this is one way to start # this code: # python agent0.py [hostname] [port] # # Often this translates to something like the following (with the # port name being printed out by the bzrflag server): # python agent0.py localhost 49857 ################################################################# import sys import math import time from bzrc import BZRC, Command class Agent(object): """Class handles all command and control logic for a teams tanks.""" def __init__(self, bzrc): self.bzrc = bzrc self.constants = self.bzrc.get_constants() self.commands = [] def tick(self, time_diff): """Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots, obstacles = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.othertanks = othertanks self.flags = flags self.shots = shots self.enemies = [tank for tank in othertanks if tank.color != self.constants['team']] self.commands = [] for tank in mytanks: self.attack_enemies(tank) results = self.bzrc.do_commands(self.commands) def attack_enemies(self, tank): """Find the closest enemy and chase it, shooting as you go.""" best_enemy = None best_dist = 2 * float(self.constants['worldsize']) for enemy in self.enemies: if enemy.status != 'alive': continue dist = math.sqrt((enemy.x - tank.x)**2 + (enemy.y - tank.y)**2) if dist < best_dist: best_dist = dist best_enemy = enemy if best_enemy is None: command = Command(tank.index, 0, 0, False) self.commands.append(command) else: self.move_to_position(tank, best_enemy.x, best_enemy.y) def move_to_position(self, tank, target_x, target_y): """Set command to move to given coordinates.""" target_angle = math.atan2(target_y - tank.y, target_x - tank.x) relative_angle = self.normalize_angle(target_angle - tank.angle) command = Command(tank.index, 1, 2 * relative_angle, True) self.commands.append(command) def normalize_angle(self, angle): """Make any angle be between +/- pi.""" angle -= 2 * math.pi * int (angle / (2 * math.pi)) if angle <= -math.pi: angle += 2 * math.pi elif angle > math.pi: angle -= 2 * math.pi return angle def main(): # Process CLI arguments. try: execname, host, port = sys.argv except ValueError: execname = sys.argv[0] print >>sys.stderr, '%s: incorrect number of arguments' % execname print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0]<|fim▁hole|> #bzrc = BZRC(host, int(port), debug=True) bzrc = BZRC(host, int(port)) agent = Agent(bzrc) prev_time = time.time() # Run the agent try: while True: time_diff = time.time() - prev_time agent.tick(time_diff) except KeyboardInterrupt: print "Exiting due to keyboard interrupt." bzrc.close() if __name__ == '__main__': main() # vim: et sw=4 sts=4<|fim▁end|>
sys.exit(-1) # Connect.
<|file_name|>test_currency.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import pytest import six from sqlalchemy_utils import Currency, i18n @pytest.fixture def set_get_locale(): i18n.get_locale = lambda: i18n.babel.Locale('en') @pytest.mark.skipif('i18n.babel is None') @pytest.mark.usefixtures('set_get_locale') class TestCurrency(object): def test_init(self): assert Currency('USD') == Currency(Currency('USD')) def test_hashability(self): assert len(set([Currency('USD'), Currency('USD')])) == 1 def test_invalid_currency_code(self): with pytest.raises(ValueError): Currency('Unknown code') def test_invalid_currency_code_type(self): with pytest.raises(TypeError): Currency(None)<|fim▁hole|> @pytest.mark.parametrize( ('code', 'name'), ( ('USD', 'US Dollar'), ('EUR', 'Euro') ) ) def test_name_property(self, code, name): assert Currency(code).name == name @pytest.mark.parametrize( ('code', 'symbol'), ( ('USD', u'$'), ('EUR', u'€') ) ) def test_symbol_property(self, code, symbol): assert Currency(code).symbol == symbol def test_equality_operator(self): assert Currency('USD') == 'USD' assert 'USD' == Currency('USD') assert Currency('USD') == Currency('USD') def test_non_equality_operator(self): assert Currency('USD') != 'EUR' assert not (Currency('USD') != 'USD') def test_unicode(self): currency = Currency('USD') assert six.text_type(currency) == u'USD' def test_str(self): currency = Currency('USD') assert str(currency) == 'USD' def test_representation(self): currency = Currency('USD') assert repr(currency) == "Currency('USD')"<|fim▁end|>
<|file_name|>routes.rs<|end_file_name|><|fim▁begin|>macro_rules! define { ($name:ident, $value:expr) => ( pub const $name: &'static str = $value;<|fim▁hole|> define!(CONSUMER_HANDSHAKE, "/consumer/"); define!(CONSUMER_NOWPLAY, "/consumer/nowplay"); define!(CONSUMER_SUBMISSIONS, "/consumer/submissions"); define!(PROVIDER_ALBUM, "/provider/album/:album_id"); define!(PROVIDER_ARTIST, "/provider/artist/:artist_id"); define!(PROVIDER_ARTISTS, "/provider/artists"); define!(PROVIDER_COUNTERS, "/provider/counters"); define!(PROVIDER_FAVORITES, "/provider/favorites"); define!(PROVIDER_NOWPLAY, "/provider/nowplay"); define!(PROVIDER_OVERVIEW, "/provider/overview"); define!(PROVIDER_USERNAME, "/provider/username");<|fim▁end|>
); }
<|file_name|>generic-fn-box.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate debug; use std::gc::{Gc, GC}; fn f<T>(x: Gc<T>) -> Gc<T> { return x; } <|fim▁hole|><|fim▁end|>
pub fn main() { let x = f(box(GC) 3i); println!("{:?}", *x); }
<|file_name|>201611680890-5.10.py<|end_file_name|><|fim▁begin|># coding: utf-8 # In[ ]: #练习一:文本加密解密(先看有关ASCII码的相关知识以及码表,查维基百科或百度百科) #输入:一个txt文件(假设全是字母的英文词,每个单词之间用单个空格隔开,假设单词最长为10个字母) #加密:得到每个单词的长度 n ,随机生成一个9位的数字,将 n-1 与这个9位的数字连接,形成一个10位的数字, #作为密匙 key 。依照 key 中各个数字对单词中每一个对应位置的字母进行向后移位(例:如过 key 中某数字为 2 , #对应该位置的字母为 a ,加密则应移位成 c ,如果超过 z ,则回到 A 处继续移位),对长度不到10的单词,移位后, #将移位后的单词利用随机字母补全到10个,最终形成以10个字母为一个单词,并以单个空格分割的加密文本,存入文件。 #解密:给定该文本文件并给定key(10位数字),恢复原来的文本。 #(提示,利用 ord() 及 chr() 函数, ord(x) 是取得字符 x 的ASCII码, chr(n) 是取得整数n(代表ASCII码)对应的字符。 #例: ord(a) 的值为 97 , chr(97) 的值为 'a' ,因字母 a 的ASCII码值为 97 。) fh = open(r'd:\temp\words.txt')<|fim▁hole|> print(len(text)) print(text)<|fim▁end|>
text = fh.read() fh.close()
<|file_name|>gfx_font6x8.py<|end_file_name|><|fim▁begin|>import pygame<|fim▁hole|>sprite['height'] = 8 def Addr(): return sprite<|fim▁end|>
sprite = {} sprite['image'] = pygame.image.load("test/font6x8_normal_w.png") sprite['width'] = 6
<|file_name|>es7.object.entries.js<|end_file_name|><|fim▁begin|>/* */ var $def = require("./$.def"), $entries = require("./$.object-to-array")(true);<|fim▁hole|> }});<|fim▁end|>
$def($def.S, 'Object', {entries: function entries(it) { return $entries(it);
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import logging class BaseDebugInterface(object): def __init__(self, debuger): self.robotDebuger = debuger self.debugCtx = debuger.debugCtx self.logger = logging.getLogger("rbt.int") self.bp_id = 0 def start(self, settings): """start debug interface.""" pass def close(self): pass def go_steps(self, count): self.debugCtx.go_steps(int(count)) def go_into(self): self.debugCtx.go_into() def go_over(self): self.debugCtx.go_over() def go_on(self): self.debugCtx.go_on() def go_return(self): self.debugCtx.go_return() def go_pause(self): return self.debugCtx.go_pause() def add_breakpoint(self, bp): self.robotDebuger.add_breakpoint(bp) def watch_variable(self, name): return self.robotDebuger.watch_variable(name) def remove_variable(self, name): return self.robotDebuger.remove_variable(name) def run_keyword(self, name, *args): return self.robotDebuger.run_keyword(name, *args) def update_variable(self, name, value): from robot.running import NAMESPACES if NAMESPACES.current is not None: NAMESPACES.current.variables[name] = value def variable_value(self, var_list): from robot.running import NAMESPACES if NAMESPACES.current is None: return [(e, None) for e in var_list] robot_vars = NAMESPACES.current.variables val_list = [] for e in var_list: try: v = robot_vars.replace_scalar(e) except Exception, et: if "Non-existing" in str(et): v = None else: raise val_list.append((e, v)) return val_list @property def watching_variable(self):return self.robotDebuger.watching_variable @property def callstack(self): """Return a runtime list""" return list(self.debugCtx.call_stack)<|fim▁hole|> """Return list of breakpoint""" return list(self.debugCtx.break_points) @property def active_breakpoint(self):return self.debugCtx.active_break_point def disable_breakpoint(self, name, match_kw=False): bp = self._get_breakpoint(name, match_kw) if bp: bp.active = False def enable_breakpoint(self, name, match_kw=False): bp = self._get_breakpoint(name, match_kw) if bp: bp.active = True def update_breakpoint(self, name, match_kw=False): bp = self._get_breakpoint(name, match_kw) if bp: bp.active = not bp.active def _get_breakpoint(self, name, match_kw): for e in self.debugCtx.break_points: if match_kw and hasattr(e, 'kw_name') and e.kw_name == name: return e elif not match_kw and e.name == name: return e return None def add_telnet_monitor(self, monitor): """this is IPAMml special feature.""" self.robotDebuger.add_telnet_monitor(monitor) def add_debug_listener(self, l): self.debugCtx.add_listener(l) def remove_debug_listener(self, l): self.debugCtx.remove_listener(l) class Listener: def __init__(self): pass def pause(self, breakpoint): pass def go_on(self): pass def start_keyword(self, keyword): pass def end_keyword(self, keyword): pass<|fim▁end|>
@property def breakpoints(self):
<|file_name|>SliderTransparency.js<|end_file_name|><|fim▁begin|>import React from 'react'; import Slider from 'material-ui/Slider'; /** * The `defaultValue` property sets the initial position of the slider. * The slider appearance changes when not at the starting position. */ const SliderTransparency = (props) => ( <Slider defaultValue={props.transparency} onChange={props.update} sliderStyle={{margin:'auto',pointerEvents:'all'}} axis='y' style={{height:'400px', paddingTop:"30px"}} data-tip={`Opacity`} data-offset="{'top': -30}"<|fim▁hole|> /> ); export default SliderTransparency;<|fim▁end|>
<|file_name|>GuiFactory.java<|end_file_name|><|fim▁begin|>package net.infernalized.infernalutils.client.gui; import cpw.mods.fml.client.IModGuiFactory; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import java.util.Set; public class GuiFactory implements IModGuiFactory { @Override public void initialize(Minecraft minecraftInstance) { } <|fim▁hole|> public Class<? extends GuiScreen> mainConfigGuiClass() { return null; } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } @Override public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { return null; } }<|fim▁end|>
@Override
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod cell; mod formula; mod operations;<|fim▁hole|>mod spreadsheet; pub use cell::{Cell, CellRef}; pub use formula::{Application, Formula, Formulas, Number, Range, Textual}; pub use spreadsheet::Spreadsheet;<|fim▁end|>
<|file_name|>issue-3177-mutable-struct.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test // error-pattern: instantiating a type parameter with an incompatible type struct S<T:Const> { s: T, cant_nest: () } <|fim▁hole|> let _a2 = ~S{ s: a1, cant_nest: () }; }<|fim▁end|>
fn main() { let a1 = ~S{ s: true, cant_nest: () };
<|file_name|>ImageAddrMap.cpp<|end_file_name|><|fim▁begin|>/* Copyright (c) 2010 Aldo J. Nunez Licensed under the Apache License, Version 2.0. See the LICENSE text file for details. */ #include "Common.h" #include "ImageAddrMap.h" <|fim▁hole|> namespace MagoST { ImageAddrMap::ImageAddrMap() : mRefCount( 0 ), mSecCount( 0 ) { } void ImageAddrMap::AddRef() { InterlockedIncrement( &mRefCount ); } void ImageAddrMap::Release() { long newRef = InterlockedDecrement( &mRefCount ); _ASSERT( newRef >= 0 ); if ( newRef == 0 ) { delete this; } } uint32_t ImageAddrMap::MapSecOffsetToRVA( uint16_t secIndex, uint32_t offset ) { if ( (secIndex == 0) || (secIndex > mSecCount) ) return 0; uint16_t zSec = secIndex - 1; // zero-based section index return mSections[zSec].RVA + offset; } uint16_t ImageAddrMap::MapRVAToSecOffset( uint32_t rva, uint32_t& offset ) { uint16_t closestSec = USHRT_MAX; uint32_t closestOff = ULONG_MAX; for ( uint16_t i = 0; i < mSecCount; i++ ) { if ( rva >= mSections[i].RVA ) { uint32_t curOff = rva - mSections[i].RVA; if ( curOff < closestOff ) { closestOff = curOff; closestSec = i; } } } if ( closestSec < USHRT_MAX ) { offset = closestOff; return closestSec + 1; // remember it's 1-based } return 0; } uint16_t ImageAddrMap::FindSection( const char* name ) { for ( uint16_t i = 0; i < mSecCount; i++ ) if( strncmp( name, mSections[i].Name, sizeof( mSections[i].Name ) ) == 0 ) return i + 1; // remember it's 1-based return 0; } HRESULT ImageAddrMap::LoadFromSections( uint16_t count, const IMAGE_SECTION_HEADER* secHeaders ) { _ASSERT( secHeaders != NULL ); _ASSERT( mSections.Get() == NULL ); _ASSERT( count != USHRT_MAX ); if ( count == USHRT_MAX ) return E_INVALIDARG; mSections.Attach( new Section[ count ] ); if ( mSections.Get() == NULL ) return E_OUTOFMEMORY; mSecCount = count; for ( uint16_t i = 0; i < count; i++ ) { DWORD size = secHeaders[i].SizeOfRawData; if ( secHeaders[i].Misc.VirtualSize > 0 ) size = secHeaders[i].Misc.VirtualSize; mSections[i].RVA = secHeaders[i].VirtualAddress; mSections[i].Size = size; memcpy( mSections[i].Name, (const char*) secHeaders[i].Name, sizeof( mSections[i].Name ) ); } return S_OK; } }<|fim▁end|>
<|file_name|>listeners.py<|end_file_name|><|fim▁begin|>import io from molotov.api import get_fixture _UNREADABLE = "***WARNING: Molotov can't display this body***" _BINARY = "**** Binary content ****" _FILE = "**** File content ****" _COMPRESSED = ('gzip', 'compress', 'deflate', 'identity', 'br') class BaseListener(object): async def __call__(self, event, **options): attr = getattr(self, 'on_' + event, None) if attr is not None: await attr(**options) class StdoutListener(BaseListener): def __init__(self, **options): self.verbose = options.get('verbose', 0) self.console = options['console'] def _body2str(self, body):<|fim▁hole|> from aiohttp.payload import Payload except ImportError: Payload = None if Payload is not None and isinstance(body, Payload): body = body._value if isinstance(body, io.IOBase): return _FILE if not isinstance(body, str): try: body = str(body, 'utf8') except UnicodeDecodeError: return _UNREADABLE return body async def on_sending_request(self, session, request): if self.verbose < 2: return raw = '>' * 45 raw += '\n' + request.method + ' ' + str(request.url) if len(request.headers) > 0: headers = '\n'.join('%s: %s' % (k, v) for k, v in request.headers.items()) raw += '\n' + headers if request.headers.get('Content-Encoding') in _COMPRESSED: raw += '\n\n' + _BINARY + '\n' elif request.body: raw += '\n\n' + self._body2str(request.body) + '\n' self.console.print(raw) async def on_response_received(self, session, response, request): if self.verbose < 2: return raw = '\n' + '=' * 45 + '\n' raw += 'HTTP/1.1 %d %s\n' % (response.status, response.reason) items = response.headers.items() headers = '\n'.join('{}: {}'.format(k, v) for k, v in items) raw += headers if response.headers.get('Content-Encoding') in _COMPRESSED: raw += '\n\n' + _BINARY elif response.content: content = await response.content.read() if len(content) > 0: # put back the data in the content response.content.unread_data(content) try: raw += '\n\n' + content.decode() except UnicodeDecodeError: raw += '\n\n' + _UNREADABLE else: raw += '\n\n' raw += '\n' + '<' * 45 + '\n' self.console.print(raw) class CustomListener(object): def __init__(self, fixture): self.fixture = fixture async def __call__(self, event, **options): await self.fixture(event, **options) class EventSender(object): def __init__(self, console, listeners=None): self.console = console if listeners is None: listeners = [] self._listeners = listeners self._stopped = False fixture_listeners = get_fixture('events') if fixture_listeners is not None: for listener in fixture_listeners: self.add_listener(CustomListener(listener)) def add_listener(self, listener): self._listeners.append(listener) async def stop(self): self._stopped = True def stopped(self): return self._stopped async def send_event(self, event, **options): for listener in self._listeners: try: await listener(event, **options) except Exception as e: self.console.print_error(e)<|fim▁end|>
try:
<|file_name|>value.rs<|end_file_name|><|fim▁begin|>//! Deserialization of a `Value<T>` type which tracks where it was deserialized //! from. //! //! Often Cargo wants to report semantic error information or other sorts of //! error information about configuration keys but it also may wish to indicate //! as an error context where the key was defined as well (to help user //! debugging). The `Value<T>` type here can be used to deserialize a `T` value //! from configuration, but also record where it was deserialized from when it //! was read. use crate::util::config::Config; use serde::de; use std::fmt; use std::marker; use std::mem; use std::path::{Path, PathBuf}; /// A type which can be deserialized as a configuration value which records /// where it was deserialized from. #[derive(Debug, PartialEq, Clone)] pub struct Value<T> { /// The inner value that was deserialized. pub val: T, /// The location where `val` was defined in configuration (e.g. file it was /// defined in, env var etc). pub definition: Definition, } pub type OptValue<T> = Option<Value<T>>; // Deserializing `Value<T>` is pretty special, and serde doesn't have built-in // support for this operation. To implement this we extend serde's "data model" // a bit. We configure deserialization of `Value<T>` to basically only work with // our one deserializer using configuration. // // We define that `Value<T>` deserialization asks the deserializer for a very // special struct name and struct field names. In doing so the deserializer will // recognize this and synthesize a magical value for the `definition` field when // we deserialize it. This protocol is how we're able to have a channel of // information flowing from the configuration deserializer into the // deserialization implementation here. // // You'll want to also check out the implementation of `ValueDeserializer` in // `de.rs`. Also note that the names below are intended to be invalid Rust // identifiers to avoid how they might conflict with other valid structures. // Finally the `definition` field is transmitted as a tuple of i32/string, which // is effectively a tagged union of `Definition` itself. pub(crate) const VALUE_FIELD: &str = "$__cargo_private_value"; pub(crate) const DEFINITION_FIELD: &str = "$__cargo_private_definition"; pub(crate) const NAME: &str = "$__cargo_private_Value"; pub(crate) static FIELDS: [&str; 2] = [VALUE_FIELD, DEFINITION_FIELD]; /// Location where a config value is defined. #[derive(Clone, Debug, Eq)] pub enum Definition { /// Defined in a `.cargo/config`, includes the path to the file. Path(PathBuf), /// Defined in an environment variable, includes the environment key. Environment(String), /// Passed in on the command line. Cli, } impl Definition { /// Root directory where this is defined. /// /// If from a file, it is the directory above `.cargo/config`. /// CLI and env are the current working directory. pub fn root<'a>(&'a self, config: &'a Config) -> &'a Path { match self { Definition::Path(p) => p.parent().unwrap().parent().unwrap(), Definition::Environment(_) | Definition::Cli => config.cwd(), } } /// Returns true if self is a higher priority to other.<|fim▁hole|> (Definition::Cli, Definition::Environment(_)) => true, (Definition::Cli, Definition::Path(_)) => true, (Definition::Environment(_), Definition::Path(_)) => true, _ => false, } } } impl PartialEq for Definition { fn eq(&self, other: &Definition) -> bool { // configuration values are equivalent no matter where they're defined, // but they need to be defined in the same location. For example if // they're defined in the environment that's different than being // defined in a file due to path interpretations. mem::discriminant(self) == mem::discriminant(other) } } impl fmt::Display for Definition { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Definition::Path(p) => p.display().fmt(f), Definition::Environment(key) => write!(f, "environment variable `{}`", key), Definition::Cli => write!(f, "--config cli option"), } } } impl<'de, T> de::Deserialize<'de> for Value<T> where T: de::Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Value<T>, D::Error> where D: de::Deserializer<'de>, { struct ValueVisitor<T> { _marker: marker::PhantomData<T>, } impl<'de, T> de::Visitor<'de> for ValueVisitor<T> where T: de::Deserialize<'de>, { type Value = Value<T>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a value") } fn visit_map<V>(self, mut visitor: V) -> Result<Value<T>, V::Error> where V: de::MapAccess<'de>, { let value = visitor.next_key::<ValueKey>()?; if value.is_none() { return Err(de::Error::custom("value not found")); } let val: T = visitor.next_value()?; let definition = visitor.next_key::<DefinitionKey>()?; if definition.is_none() { return Err(de::Error::custom("definition not found")); } let definition: Definition = visitor.next_value()?; Ok(Value { val, definition }) } } deserializer.deserialize_struct( NAME, &FIELDS, ValueVisitor { _marker: marker::PhantomData, }, ) } } struct FieldVisitor { expected: &'static str, } impl<'de> de::Visitor<'de> for FieldVisitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a valid value field") } fn visit_str<E>(self, s: &str) -> Result<(), E> where E: de::Error, { if s == self.expected { Ok(()) } else { Err(de::Error::custom("expected field with custom name")) } } } struct ValueKey; impl<'de> de::Deserialize<'de> for ValueKey { fn deserialize<D>(deserializer: D) -> Result<ValueKey, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_identifier(FieldVisitor { expected: VALUE_FIELD, })?; Ok(ValueKey) } } struct DefinitionKey; impl<'de> de::Deserialize<'de> for DefinitionKey { fn deserialize<D>(deserializer: D) -> Result<DefinitionKey, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_identifier(FieldVisitor { expected: DEFINITION_FIELD, })?; Ok(DefinitionKey) } } impl<'de> de::Deserialize<'de> for Definition { fn deserialize<D>(deserializer: D) -> Result<Definition, D::Error> where D: de::Deserializer<'de>, { let (discr, value) = <(u32, String)>::deserialize(deserializer)?; match discr { 0 => Ok(Definition::Path(value.into())), 1 => Ok(Definition::Environment(value)), 2 => Ok(Definition::Cli), _ => panic!("unexpected discriminant {} value {}", discr, value), } } }<|fim▁end|>
/// /// CLI is preferred over environment, which is preferred over files. pub fn is_higher_priority(&self, other: &Definition) -> bool { match (self, other) {
<|file_name|>GenericBytecode.py<|end_file_name|><|fim▁begin|>#!C:\Python27\python.exe # Filename: GenericBytecode.py # -*- coding: utf-8 -*- import os import Settings ''' Generic Bytecode Simply add, remove or modify bytecode for use in KHMS ''' createFrame = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', 'aload_0', 'getfield', \ 'invokevirtual', 'iadd', 'i2b', 'bastore', 'return'] writeDWord = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \ 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \ 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ 'bipush', 'ishr', 'i2b', 'bastore', 'aload_0', 'getfield', \ 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \ 'putfield', 'iload_1', 'bipush', 'ishr', 'i2b', 'bastore', \ 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', 'return'] # writeWordBigEndian = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \ # 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ # 'i2b', 'bastore', 'return', 'aload_0', 'dup', 'getfield', \ # 'iconst_3', 'iadd', 'putfield', 'sipush', 'aload_0', \ # 'getfield', 'aload_0', 'getfield', 'iconst_3', 'isub', \ # 'baload', 'bipush', 'ishl', 'iand', 'sipush', 'aload_0', \ # 'getfield', 'aload_0', 'getfield', 'iconst_2', 'isub', \ # 'baload', 'bipush', 'ishl', 'iand', 'iadd', 'sipush', \ # 'aload_0', 'getfield', 'aload_0', 'getfield', 'iconst_1', \ # 'isub', 'baload', 'iand', 'iadd', 'ireturn'] writeWordBigEndian = ['aload_0', 'getfield Stream/buffer [B', 'aload_0', 'dup', 'getfield Stream/currentOffset I', 'dup_x1', 'iconst_1', 'iadd', 'putfield Stream/currentOffset I', 'iload_1', 'i2b', 'bastore', 'return'] writeWord = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \ 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \ 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ 'i2b', 'bastore', 'return'] writeDWordBigEndian = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \ 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ 'bipush', 'ishr', 'i2b', 'bastore', 'aload_0', \ 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', \ 'ishr', 'i2b', 'bastore', 'aload_0', 'getfield', \ 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', \ 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', 'return'] method403 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', \ 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \ 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \ 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ 'bipush', 'ishr', 'i2b', 'bastore', 'aload_0', 'getfield', \ 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \ 'putfield', 'iload_1', 'bipush', 'ishr', 'i2b', 'bastore', 'return'] writeQWord = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'lload_1', 'bipush', 'lshr', \ 'l2i', 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', \ 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', \ 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', 'bastore', 'aload_0', \ 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', \ 'iadd', 'putfield', 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', \ 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \ 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'lload_1', 'bipush', \ 'lshr', 'l2i', 'i2b', 'bastore', 'aload_0', 'getfield', \ 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \ 'putfield', 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', \ 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \ 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'lload_1', 'bipush', \ 'lshr', 'l2i', 'i2b', 'bastore', 'aload_0', 'getfield', \ 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \ 'putfield', 'lload_1', 'bipush', 'lshr', 'l2i', 'i2b', \ 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', \ 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'lload_1', 'l2i', \ 'i2b', 'bastore', 'goto', 'astore_3', 'new', 'dup', \ 'invokespecial', 'ldc', 'invokevirtual', 'lload_1', \ 'invokevirtual', 'ldc', 'invokevirtual', 'aload_3', \ 'invokevirtual', 'invokevirtual', 'invokevirtual', \ 'invokestatic', 'new', 'dup', 'invokespecial', 'athrow', 'return'] writeString = ['aload_1', 'invokevirtual', 'iconst_0', 'aload_0', 'getfield', \ 'aload_0', 'getfield', 'aload_1', 'invokevirtual', \ 'invokestatic', 'aload_0', 'dup', 'getfield', 'aload_1', \ 'invokevirtual', 'iadd', 'putfield', 'aload_0', 'getfield', \ 'aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'iadd', \ 'putfield', 'bipush', 'bastore', 'return'] method424 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'ineg', 'i2b', \ 'bastore', 'return'] method425 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'sipush', 'iload_1', 'isub', \ 'i2b', 'bastore', 'return'] method431 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'i2b', 'bastore', \ 'aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \ 'i2b', 'bastore', 'return'] method432 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'bipush', 'ishr', \ 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \ 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ 'sipush', 'iadd', 'i2b', 'bastore', 'return'] method433 = ['aload_0', 'getfield', 'aload_0', 'dup', 'getfield', 'dup_x1', \ 'iconst_1', 'iadd', 'putfield', 'iload_1', 'sipush', 'iadd', \ 'i2b', 'bastore', 'aload_0', 'getfield', 'aload_0', 'dup', \ 'getfield', 'dup_x1', 'iconst_1', 'iadd', 'putfield', 'iload_1', \ 'bipush', 'ishr', 'i2b', 'bastore', 'return'] getNextKey = ['aload_0', 'dup', 'getfield', 'dup_x1', 'iconst_1', 'isub', \ 'putfield', 'ifne', 'aload_0', 'invokespecial', 'aload_0', \ 'sipush', 'putfield', 'aload_0', 'getfield', 'aload_0', \ 'getfield', 'iaload', 'ireturn'] isaac = ['aload_0', 'dup', 'getfield', 'aload_0', 'dup', 'getfield', \ 'iconst_1', 'iadd', 'dup_x1', 'putfield', 'iadd', 'putfield', \ 'iconst_0', 'istore_1', 'goto', 'aload_0', 'getfield', 'iload_1', \ 'iaload', 'istore_2', 'iload_1', 'iconst_3', 'iand', 'ifne', \ 'aload_0', 'dup', 'getfield', 'aload_0', 'getfield', 'bipush', \ 'ishl', 'ixor', 'putfield', 'goto', 'iload_1', 'iconst_3', 'iand', \ 'iconst_1', 'if_icmpne', 'aload_0', 'dup', 'getfield', 'aload_0', \ 'getfield', 'bipush', 'iushr', 'ixor', 'putfield', 'goto', \ 'iload_1', 'iconst_3', 'iand', 'iconst_2', 'if_icmpne', 'aload_0', \ 'dup', 'getfield', 'aload_0', 'getfield', 'iconst_2', 'ishl', \ 'ixor', 'putfield', 'goto', 'iload_1', 'iconst_3', 'iand', \ 'iconst_3', 'if_icmpne', 'aload_0', 'dup', 'getfield', 'aload_0', \ 'getfield', 'bipush', 'iushr', 'ixor', 'putfield', 'aload_0', \ 'dup', 'getfield', 'aload_0', 'getfield', 'iload_1', 'sipush', \ 'iadd', 'sipush', 'iand', 'iaload', 'iadd', 'putfield', 'aload_0', \ 'getfield', 'iload_1', 'aload_0', 'getfield', 'iload_2', 'sipush', \ 'iand', 'iconst_2', 'ishr', 'iaload', 'aload_0', 'getfield', \ 'iadd', 'aload_0', 'getfield', 'iadd', 'dup', 'istore_3', \ 'iastore', 'aload_0', 'getfield', 'iload_1', 'aload_0', 'aload_0', \ 'getfield', 'iload_3', 'bipush', 'ishr', 'sipush', 'iand', \ 'iconst_2', 'ishr', 'iaload', 'iload_2', 'iadd', 'dup_x1', \ 'putfield', 'iastore', 'iinc', 'iload_1', 'sipush', \ 'if_icmplt', 'return'] initializeKeySet2 = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', 'istore', \ 'dup', 'istore', 'dup', 'istore_3', 'dup', 'istore_2', \ 'dup', 'istore_1', 'istore', 'iconst_0', 'istore', \ 'iload', 'iconst_4', 'if_icmpge', 'iload', 'iload_1', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload_3', 'iload', \ 'iadd', 'istore_3', 'iload_1', 'iload_2', 'iadd', \ 'istore_1', 'iload_1', 'iload_2', 'iconst_2', 'iushr', \ 'ixor', 'istore_1', 'iload', 'iload_1', 'iadd', 'istore', \ 'iload_2', 'iload_3', 'iadd', 'istore_2', 'iload_2', \ 'iload_3', 'bipush', 'ishl', 'ixor', 'istore_2', \ 'iload', 'iload_2', 'iadd', 'istore', 'iload_3', \ 'iload', 'iadd', 'istore_3', 'iload_3', 'iload', \ 'bipush', 'iushr', 'ixor', 'istore_3', 'iload', \ 'iload_3', 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'iconst_4', 'iushr', 'ixor', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload_1', 'iload', 'iadd', 'istore_1', \ 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore', \ 'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \ 'iload_1', 'iadd', 'istore', 'iinc', 'goto', \ 'iconst_0', 'istore', 'iload', 'sipush', 'if_icmpge', \ 'iload', 'aload_0', 'getfield', 'iload', 'iaload', \ 'iadd', 'istore', 'iload_1', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iaload', 'iadd', \ 'istore_1', 'iload_2', 'aload_0', 'getfield', \ 'iload', 'iconst_2', 'iadd', 'iaload', 'iadd', \ 'istore_2', 'iload_3', 'aload_0', 'getfield', \ 'iload', 'iconst_3', 'iadd', 'iaload', 'iadd', \ 'istore_3', 'iload', 'aload_0', 'getfield', \ 'iload', 'iconst_4', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'aload_0', 'getfield', 'iload', \ 'iconst_5', 'iadd', 'iaload', 'iadd', 'istore', \ 'iload', 'aload_0', 'getfield', 'iload', 'bipush', \ 'iadd', 'iaload', 'iadd', 'istore', 'iload', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'iload_1', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload_3', 'iload', 'iadd', 'istore_3', \ 'iload_1', 'iload_2', 'iadd', 'istore_1', 'iload_1', \ 'iload_2', 'iconst_2', 'iushr', 'ixor', 'istore_1', \ 'iload', 'iload_1', 'iadd', 'istore', 'iload_2', \ 'iload_3', 'iadd', 'istore_2', 'iload_2', 'iload_3', \ 'bipush', 'ishl', 'ixor', 'istore_2', 'iload', \ 'iload_2', 'iadd', 'istore', 'iload_3', 'iload', \ 'iadd', 'istore_3', 'iload_3', 'iload', 'bipush', \ 'iushr', 'ixor', 'istore_3', 'iload', 'iload_3', \ 'iadd', 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'iconst_4', \ 'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload_1', 'iload', 'iadd', 'istore_1', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'bipush', 'iushr', 'ixor', 'istore', 'iload_2', \ 'iload', 'iadd', 'istore_2', 'iload', 'iload_1', \ 'iadd', 'istore', 'aload_0', 'getfield', 'iload', \ 'iload', 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_1', 'iadd', 'iload_1', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_2', 'iadd', 'iload_2', \ 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'iconst_5', \ 'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iload', 'iastore', \ 'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \ 'iload', 'iastore', 'iinc', 'goto', 'iconst_0', \ 'istore', 'iload', 'sipush', 'if_icmpge', 'iload', \ 'aload_0', 'getfield', 'iload', 'iaload', 'iadd', \ 'istore', 'iload_1', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iaload', 'iadd', \ 'istore_1', 'iload_2', 'aload_0', 'getfield', \ 'iload', 'iconst_2', 'iadd', 'iaload', 'iadd', \ 'istore_2', 'iload_3', 'aload_0', 'getfield', \ 'iload', 'iconst_3', 'iadd', 'iaload', 'iadd', \ 'istore_3', 'iload', 'aload_0', 'getfield', \ 'iload', 'iconst_4', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'aload_0', 'getfield', 'iload', \ 'iconst_5', 'iadd', 'iaload', 'iadd', 'istore', \ 'iload', 'aload_0', 'getfield', 'iload', 'bipush', \ 'iadd', 'iaload', 'iadd', 'istore', 'iload', \ 'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', 'iload_1', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload_3', \ 'iload', 'iadd', 'istore_3', 'iload_1', 'iload_2', \ 'iadd', 'istore_1', 'iload_1', 'iload_2', \ 'iconst_2', 'iushr', 'ixor', 'istore_1', 'iload', \ 'iload_1', 'iadd', 'istore', 'iload_2', 'iload_3', \ 'iadd', 'istore_2', 'iload_2', 'iload_3', 'bipush', \ 'ishl', 'ixor', 'istore_2', 'iload', 'iload_2', \ 'iadd', 'istore', 'iload_3', 'iload', 'iadd', \ 'istore_3', 'iload_3', 'iload', 'bipush', 'iushr', \ 'ixor', 'istore_3', 'iload', 'iload_3', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'ishl', 'ixor', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iconst_4', 'iushr', 'ixor', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', 'bipush', \ 'ishl', 'ixor', 'istore', 'iload_1', 'iload', 'iadd', \ 'istore_1', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore', 'iload_2', \ 'iload', 'iadd', 'istore_2', 'iload', 'iload_1', 'iadd', \ 'istore', 'aload_0', 'getfield', 'iload', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'iconst_1', \ 'iadd', 'iload_1', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_2', 'iadd', 'iload_2', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_3', 'iadd', \ 'iload_3', 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_4', 'iadd', 'iload', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_5', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'bipush', \ 'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iload', 'iastore', 'iinc', \ 'goto', 'aload_0', 'invokespecial', 'aload_0', \ 'sipush', 'putfield', 'return'] initializeKeySet3 = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', 'istore', \ 'dup', 'istore', 'dup', 'istore_3', 'dup', 'istore_2', \ 'dup', 'istore_1', 'istore', 'iconst_0', 'istore', \ 'goto', 'iload', 'iload_1', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload_3', 'iload', 'iadd', 'istore_3', \ 'iload_1', 'iload_2', 'iadd', 'dup', 'istore_1', \ 'iload_2', 'iconst_2', 'iushr', 'ixor', 'istore_1', \ 'iload', 'iload_1', 'iadd', 'istore', 'iload_2', \ 'iload_3', 'iadd', 'dup', 'istore_2', 'iload_3', \ 'bipush', 'ishl', 'ixor', 'istore_2', 'iload', \ 'iload_2', 'iadd', 'istore', 'iload_3', 'iload', \ 'iadd', 'dup', 'istore_3', 'iload', 'bipush', \ 'iushr', 'ixor', 'istore_3', 'iload', \ 'iload_3', 'iadd', 'istore', 'iload', 'iload', \ 'iadd', 'dup', 'istore', 'iload', 'bipush', \ 'ishl', 'ixor', 'istore', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'dup', 'istore', 'iload', 'iconst_4', \ 'iushr', 'ixor', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'iadd', 'dup', 'istore', 'iload', 'bipush', \ 'ishl', 'ixor', 'istore', 'iload_1', 'iload', \ 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \ 'dup', 'istore', 'iload', 'bipush', 'iushr', \ 'ixor', 'istore', 'iload_2', 'iload', 'iadd', \ 'istore_2', 'iload', 'iload_1', 'iadd', \ 'istore', 'iinc', 'iload', 'iconst_4', 'if_icmplt', \ 'iconst_0', 'istore', 'goto', 'iload', 'aload_0', \ 'getfield', 'iload', 'iaload', 'iadd', 'istore', \ 'iload_1', 'aload_0', 'getfield', 'iload', \ 'iconst_1', 'iadd', 'iaload', 'iadd', 'istore_1', \ 'iload_2', 'aload_0', 'getfield', 'iload', \ 'iconst_2', 'iadd', 'iaload', 'iadd', 'istore_2', \ 'iload_3', 'aload_0', 'getfield', 'iload', 'iconst_3', \ 'iadd', 'iaload', 'iadd', 'istore_3', 'iload', \ 'aload_0', 'getfield', 'iload', 'iconst_4', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', 'aload_0', \ 'getfield', 'iload', 'iconst_5', 'iadd', 'iaload', \ 'iadd', 'istore', 'iload', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'aload_0', 'getfield', 'iload', \ 'bipush', 'iadd', 'iaload', 'iadd', 'istore', 'iload', \ 'iload_1', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload_3', 'iload', 'iadd', 'istore_3', 'iload_1', \ 'iload_2', 'iadd', 'dup', 'istore_1', 'iload_2', \ 'iconst_2', 'iushr', 'ixor', 'istore_1', 'iload', \ 'iload_1', 'iadd', 'istore', 'iload_2', 'iload_3', \ 'iadd', 'dup', 'istore_2', 'iload_3', 'bipush', \ 'ishl', 'ixor', 'istore_2', 'iload', 'iload_2', \ 'iadd', 'istore', 'iload_3', 'iload', 'iadd', 'dup', \ 'istore_3', 'iload', 'bipush', 'iushr', 'ixor', \ 'istore_3', 'iload', 'iload_3', 'iadd', 'istore', \ 'iload', 'iload', 'iadd', 'dup', 'istore', 'iload', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'iadd', 'dup', \ 'istore', 'iload', 'iconst_4', 'iushr', 'ixor', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'dup', 'istore', 'iload', 'bipush', \ 'ishl', 'ixor', 'istore', 'iload_1', 'iload', 'iadd', \ 'istore_1', 'iload', 'iload', 'iadd', 'dup', 'istore', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore', \ 'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \ 'iload_1', 'iadd', 'istore', 'aload_0', 'getfield', \ 'iload', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \ 'iload_2', 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'iconst_5', \ 'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iload', 'iastore', \ 'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \ 'iload', 'iastore', 'iinc', 'iload', 'sipush', \ 'if_icmplt', 'iconst_0', 'istore', 'goto', 'iload', \ 'aload_0', 'getfield', 'iload', 'iaload', 'iadd', \ 'istore', 'iload_1', 'aload_0', 'getfield', 'iload', \ 'iconst_1', 'iadd', 'iaload', 'iadd', 'istore_1', \ 'iload_2', 'aload_0', 'getfield', 'iload', 'iconst_2', \ 'iadd', 'iaload', 'iadd', 'istore_2', 'iload_3', \ 'aload_0', 'getfield', 'iload', 'iconst_3', 'iadd', \ 'iaload', 'iadd', 'istore_3', 'iload', 'aload_0', \ 'getfield', 'iload', 'iconst_4', 'iadd', 'iaload', \ 'iadd', 'istore', 'iload', 'aload_0', 'getfield', \ 'iload', 'iconst_5', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'aload_0', 'getfield', 'iload', \ 'bipush', 'iadd', 'iaload', 'iadd', 'istore', 'iload', \ 'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', 'iload_1', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload_3', \ 'iload', 'iadd', 'istore_3', 'iload_1', 'iload_2', \ 'iadd', 'dup', 'istore_1', 'iload_2', 'iconst_2', \ 'iushr', 'ixor', 'istore_1', 'iload', 'iload_1', \ 'iadd', 'istore', 'iload_2', 'iload_3', 'iadd', 'dup', \ 'istore_2', 'iload_3', 'bipush', 'ishl', 'ixor', \ 'istore_2', 'iload', 'iload_2', 'iadd', 'istore', \ 'iload_3', 'iload', 'iadd', 'dup', 'istore_3', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore_3', \ 'iload', 'iload_3', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'dup', 'istore', 'iload', 'bipush', \ 'ishl', 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'dup', 'istore', \ 'iload', 'iconst_4', 'iushr', 'ixor', 'istore', \ 'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'iadd', 'dup', 'istore', 'iload', 'bipush', 'ishl', \ 'ixor', 'istore', 'iload_1', 'iload', 'iadd', \ 'istore_1', 'iload', 'iload', 'iadd', 'dup', 'istore', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore', \ 'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \ 'iload_1', 'iadd', 'istore', 'aload_0', 'getfield', \ 'iload', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \ 'iload_2', 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'iconst_5', \ 'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iload', 'iastore', \ 'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \ 'iload', 'iastore', 'iinc', 'iload', 'sipush', \ 'if_icmplt', 'aload_0', 'invokespecial', \ 'aload_0', 'sipush', 'putfield', 'return'] initializeKeySet4 = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', \ 'istore', 'dup', 'istore', 'dup', 'istore_3', 'dup', \ 'istore_2', 'dup', 'istore_1', 'istore', 'iconst_0', \ 'istore', 'iload', 'iconst_4', 'if_icmpge', \ 'iload', 'iload_1', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload_3', 'iload', 'iadd', 'istore_3', \ 'iload_1', 'iload_2', 'iadd', 'istore_1', 'iload_1', \ 'iload_2', 'iconst_2', 'iushr', 'ixor', \ 'istore_1', 'iload', 'iload_1', 'iadd', 'istore', \ 'iload_2', 'iload_3', 'iadd', 'istore_2', 'iload_2', \ 'iload_3', 'bipush', 'ishl', 'ixor', 'istore_2', \ 'iload', 'iload_2', 'iadd', 'istore', 'iload_3', \ 'iload', 'iadd', 'istore_3', 'iload_3', 'iload', \ 'bipush', 'iushr', 'ixor', 'istore_3', 'iload', \ 'iload_3', 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', 'iconst_4', \ 'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \ 'iload', 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'bipush', 'iushr', 'ixor', \ 'istore', 'iload_2', 'iload', 'iadd', 'istore_2', \ 'iload', 'iload_1', 'iadd', 'istore', 'iinc', 'goto', \ 'iconst_0', 'istore', 'iload', 'sipush', 'if_icmpge', \ 'iload', 'aload_0', 'getfield', 'iload', 'iaload', \ 'iadd', 'istore', 'iload_1', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iaload', 'iadd', \ 'istore_1', 'iload_2', 'aload_0', 'getfield', 'iload', \ 'iconst_2', 'iadd', 'iaload', 'iadd', 'istore_2', \ 'iload_3', 'aload_0', 'getfield', 'iload', 'iconst_3', \ 'iadd', 'iaload', 'iadd', 'istore_3', 'iload', \ 'aload_0', 'getfield', 'iload', 'iconst_4', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', 'aload_0', \ 'getfield', 'iload', 'iconst_5', 'iadd', 'iaload', \ 'iadd', 'istore', 'iload', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iaload', 'iadd', 'istore', \ 'iload', 'aload_0', 'getfield', 'iload', 'bipush', \ 'iadd', 'iaload', 'iadd', 'istore', 'iload', 'iload_1', \<|fim▁hole|> 'bipush', 'ishl', 'ixor', 'istore', 'iload_3', 'iload', \ 'iadd', 'istore_3', 'iload_1', 'iload_2', 'iadd', \ 'istore_1', 'iload_1', 'iload_2', 'iconst_2', 'iushr', \ 'ixor', 'istore_1', 'iload', 'iload_1', 'iadd', \ 'istore', 'iload_2', 'iload_3', 'iadd', 'istore_2', \ 'iload_2', 'iload_3', 'bipush', 'ishl', 'ixor', \ 'istore_2', 'iload', 'iload_2', 'iadd', 'istore', \ 'iload_3', 'iload', 'iadd', 'istore_3', 'iload_3', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore_3', \ 'iload', 'iload_3', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iconst_4', 'iushr', \ 'ixor', 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \ 'iload', 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'bipush', 'iushr', 'ixor', \ 'istore', 'iload_2', 'iload', 'iadd', 'istore_2', \ 'iload', 'iload_1', 'iadd', 'istore', 'aload_0', \ 'getfield', 'iload', 'iload', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_1', 'iadd', 'iload_1', \ 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_2', 'iadd', 'iload_2', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_3', 'iadd', 'iload_3', \ 'iastore', 'aload_0', 'getfield', 'iload', 'iconst_4', \ 'iadd', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_5', 'iadd', 'iload', 'iastore', \ 'aload_0', 'getfield', 'iload', 'bipush', 'iadd', \ 'iload', 'iastore', 'aload_0', 'getfield', 'iload', \ 'bipush', 'iadd', 'iload', 'iastore', 'iinc', \ 'goto', 'iconst_0', 'istore', 'iload', 'sipush', \ 'if_icmpge', 'iload', 'aload_0', 'getfield', 'iload', \ 'iaload', 'iadd', 'istore', 'iload_1', 'aload_0', \ 'getfield', 'iload', 'iconst_1', 'iadd', 'iaload', \ 'iadd', 'istore_1', 'iload_2', 'aload_0', 'getfield', \ 'iload', 'iconst_2', 'iadd', 'iaload', 'iadd', \ 'istore_2', 'iload_3', 'aload_0', 'getfield', 'iload', \ 'iconst_3', 'iadd', 'iaload', 'iadd', 'istore_3', \ 'iload', 'aload_0', 'getfield', 'iload', 'iconst_4', \ 'iadd', 'iaload', 'iadd', 'istore', 'iload', \ 'aload_0', 'getfield', 'iload', 'iconst_5', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', 'iaload', \ 'iadd', 'istore', 'iload', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iaload', 'iadd', 'istore', \ 'iload', 'iload_1', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload_3', 'iload', 'iadd', 'istore_3', 'iload_1', \ 'iload_2', 'iadd', 'istore_1', 'iload_1', 'iload_2', \ 'iconst_2', 'iushr', 'ixor', 'istore_1', 'iload', \ 'iload_1', 'iadd', 'istore', 'iload_2', 'iload_3', \ 'iadd', 'istore_2', 'iload_2', 'iload_3', 'bipush', \ 'ishl', 'ixor', 'istore_2', 'iload', 'iload_2', \ 'iadd', 'istore', 'iload_3', 'iload', 'iadd', \ 'istore_3', 'iload_3', 'iload', 'bipush', 'iushr', \ 'ixor', 'istore_3', 'iload', 'iload_3', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload', 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'iconst_4', \ 'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload_1', 'iload', 'iadd', 'istore_1', \ 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'iushr', 'ixor', 'istore', \ 'iload_2', 'iload', 'iadd', 'istore_2', 'iload', \ 'iload_1', 'iadd', 'istore', 'aload_0', 'getfield', \ 'iload', 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \ 'iload_2', 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_3', 'iadd', 'iload_3', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_4', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_5', 'iadd', 'iload', 'iastore', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'bipush', \ 'iadd', 'iload', 'iastore', 'iinc', 'goto', 'aload_0', \ 'invokespecial', 'aload_0', 'sipush', 'putfield', 'return'] initializeKeySet = ['ldc', 'dup', 'istore', 'dup', 'istore', 'dup', \ 'istore', 'dup', 'istore', 'dup', 'istore_3', \ 'dup', 'istore_2', 'dup', 'istore_1', 'istore', \ 'iconst_0', 'istore', 'goto', 'iload', 'iload_1', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload_3', \ 'iload', 'iadd', 'istore_3', 'iload_1', \ 'iload_2', 'iadd', 'istore_1', 'iload_1', \ 'iload_2', 'iconst_2', 'iushr', 'ixor', \ 'istore_1', 'iload', 'iload_1', 'iadd', 'istore', \ 'iload_2', 'iload_3', 'iadd', 'istore_2', \ 'iload_2', 'iload_3', 'bipush', 'ishl', 'ixor', \ 'istore_2', 'iload', 'iload_2', 'iadd', 'istore', \ 'iload_3', 'iload', 'iadd', 'istore_3', \ 'iload_3', 'iload', 'bipush', 'iushr', 'ixor', \ 'istore_3', 'iload', 'iload_3', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'iconst_4', 'iushr', 'ixor', 'istore', \ 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \ 'iload', 'iadd', 'istore_1', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'bipush', \ 'iushr', 'ixor', 'istore', 'iload_2', 'iload', \ 'iadd', 'istore_2', 'iload', 'iload_1', 'iadd', \ 'istore', 'iinc', 'iload', 'iconst_4', \ 'if_icmplt', 'iconst_0', 'istore', 'goto', \ 'iload', 'aload_0', 'getfield', 'iload', \ 'iaload', 'iadd', 'istore', 'iload_1', \ 'aload_0', 'getfield', 'iload', 'iconst_1', \ 'iadd', 'iaload', 'iadd', 'istore_1', \ 'iload_2', 'aload_0', 'getfield', 'iload', \ 'iconst_2', 'iadd', 'iaload', 'iadd', \ 'istore_2', 'iload_3', 'aload_0', \ 'getfield', 'iload', 'iconst_3', 'iadd', \ 'iaload', 'iadd', 'istore_3', 'iload', \ 'aload_0', 'getfield', 'iload', 'iconst_4', \ 'iadd', 'iaload', 'iadd', 'istore', \ 'iload', 'aload_0', 'getfield', 'iload', \ 'iconst_5', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iaload', \ 'iadd', 'istore', 'iload', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', \ 'iload_1', 'bipush', 'ishl', 'ixor', \ 'istore', 'iload_3', 'iload', 'iadd', \ 'istore_3', 'iload_1', 'iload_2', 'iadd', \ 'istore_1', 'iload_1', 'iload_2', \ 'iconst_2', 'iushr', 'ixor', 'istore_1', \ 'iload', 'iload_1', 'iadd', 'istore', \ 'iload_2', 'iload_3', 'iadd', 'istore_2', \ 'iload_2', 'iload_3', 'bipush', 'ishl', \ 'ixor', 'istore_2', 'iload', 'iload_2', \ 'iadd', 'istore', 'iload_3', 'iload', \ 'iadd', 'istore_3', 'iload_3', 'iload', \ 'bipush', 'iushr', 'ixor', 'istore_3', \ 'iload', 'iload_3', 'iadd', 'istore', \ 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'bipush', 'ishl', \ 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', \ 'iload', 'iload', 'iconst_4', \ 'iushr', 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload_1', 'iload', 'iadd', 'istore_1', 'iload', \ 'iload', 'iadd', 'istore', 'iload', 'iload', \ 'bipush', 'iushr', 'ixor', 'istore', 'iload_2', \ 'iload', 'iadd', 'istore_2', 'iload', 'iload_1', \ 'iadd', 'istore', 'aload_0', 'getfield', 'iload', \ 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_2', \ 'iadd', 'iload_2', 'iastore', 'aload_0', \ 'getfield', 'iload', 'iconst_3', 'iadd', 'iload_3', \ 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_4', 'iadd', 'iload', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_5', 'iadd', \ 'iload', 'iastore', 'aload_0', 'getfield', 'iload', \ 'bipush', 'iadd', 'iload', 'iastore', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', 'iload', \ 'iastore', 'iinc', 'iload', 'sipush', \ 'if_icmplt', 'iconst_0', 'istore', 'goto', \ 'iload', 'aload_0', 'getfield', 'iload', 'iaload', \ 'iadd', 'istore', 'iload_1', 'aload_0', \ 'getfield', 'iload', 'iconst_1', 'iadd', \ 'iaload', 'iadd', 'istore_1', 'iload_2', \ 'aload_0', 'getfield', 'iload', 'iconst_2', \ 'iadd', 'iaload', 'iadd', 'istore_2', \ 'iload_3', 'aload_0', 'getfield', 'iload', \ 'iconst_3', 'iadd', 'iaload', 'iadd', 'istore_3', \ 'iload', 'aload_0', 'getfield', 'iload', \ 'iconst_4', 'iadd', 'iaload', 'iadd', 'istore', \ 'iload', 'aload_0', 'getfield', 'iload', \ 'iconst_5', 'iadd', 'iaload', 'iadd', \ 'istore', 'iload', 'aload_0', 'getfield', \ 'iload', 'bipush', 'iadd', 'iaload', \ 'iadd', 'istore', 'iload', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', \ 'iaload', 'iadd', 'istore', 'iload', \ 'iload_1', 'bipush', 'ishl', 'ixor', 'istore', \ 'iload_3', 'iload', 'iadd', 'istore_3', \ 'iload_1', 'iload_2', 'iadd', 'istore_1', \ 'iload_1', 'iload_2', 'iconst_2', 'iushr', \ 'ixor', 'istore_1', 'iload', 'iload_1', \ 'iadd', 'istore', 'iload_2', 'iload_3', \ 'iadd', 'istore_2', 'iload_2', 'iload_3', \ 'bipush', 'ishl', 'ixor', 'istore_2', \ 'iload', 'iload_2', 'iadd', 'istore', \ 'iload_3', 'iload', 'iadd', 'istore_3', \ 'iload_3', 'iload', 'bipush', 'iushr', \ 'ixor', 'istore_3', 'iload', 'iload_3', \ 'iadd', 'istore', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'bipush', \ 'ishl', 'ixor', 'istore', 'iload', 'iload', \ 'iadd', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iconst_4', 'iushr', \ 'ixor', 'istore', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'iadd', 'istore', 'iload', \ 'iload', 'bipush', 'ishl', 'ixor', 'istore', 'iload_1', \ 'iload', 'iadd', 'istore_1', 'iload', 'iload', 'iadd', \ 'istore', 'iload', 'iload', 'bipush', 'iushr', 'ixor', \ 'istore', 'iload_2', 'iload', \ 'iadd', 'istore_2', 'iload', 'iload_1', \ 'iadd', 'istore', 'aload_0', 'getfield', 'iload', \ 'iload', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_1', 'iadd', 'iload_1', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_2', 'iadd', \ 'iload_2', 'iastore', 'aload_0', 'getfield', \ 'iload', 'iconst_3', 'iadd', 'iload_3', 'iastore', \ 'aload_0', 'getfield', 'iload', 'iconst_4', 'iadd', \ 'iload', 'iastore', 'aload_0', 'getfield', 'iload', \ 'iconst_5', 'iadd', 'iload', 'iastore', 'aload_0', \ 'getfield', 'iload', 'bipush', 'iadd', 'iload', \ 'iastore', 'aload_0', 'getfield', 'iload', 'bipush', \ 'iadd', 'iload', 'iastore', 'iinc', 'iload', \ 'sipush', 'if_icmplt', 'aload_0', 'invokespecial', \ 'aload_0', 'sipush', 'putfield', 'return'] Generic_Methods = [ ['createFrame', createFrame], ['writeDWord', writeDWord], ['writeWordBigEndian', writeWordBigEndian], ['writeWord', writeWord], ['writeDWordBigEndian', writeDWordBigEndian], ['method403', method403], ['writeQWord', writeQWord], ['writeString', writeString], ['method424', method424], ['method425', method425], ['method431', method431], ['method432', method432], ['method433', method433], ['getNextKey', getNextKey], ['isaac', isaac], ['initializeKeySet', initializeKeySet], ['initializeKeySet3', initializeKeySet3], ['initializeKeySet4', initializeKeySet4], ['initializeKeySet2', initializeKeySet2] ]<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2007, 2008, 2009 VIFF Development Team. # # This file is part of VIFF, the Virtual Ideal Functionality Framework. #<|fim▁hole|># VIFF is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License (LGPL) as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # VIFF is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with VIFF. If not, see <http://www.gnu.org/licenses/>.<|fim▁end|>
<|file_name|>oven.py<|end_file_name|><|fim▁begin|>import RPi.GPIO as gpio from datetime import datetime import time import controller gpio.setmode(gpio.BOARD) # switch_pins = [10, 40, 38] switch = 10 gpio.setup(switch, gpio.OUT, initial=False) # gpio.setup(switch_pins, gpio.OUT, initial=False) def switch_on(): gpio.output(switch, True) print "Oven switched ON at " + str(datetime.now()) def switch_off(): gpio.output(switch, False) print "Oven switched OFF at " + str(datetime.now()) def status(): return gpio.input(switch) <|fim▁hole|>print status() time.sleep(3) switch_off() print status() # gpio.cleanup()<|fim▁end|>
switch_on()
<|file_name|>pure_py.py<|end_file_name|><|fim▁begin|>import cython def test_sizeof(): """ >>> test_sizeof() True True True True True """ x = cython.declare(cython.bint) print(cython.sizeof(x) == cython.sizeof(cython.bint)) print(cython.sizeof(cython.char) <= cython.sizeof(cython.short) <= cython.sizeof(cython.int) <= cython.sizeof(cython.long) <= cython.sizeof(cython.longlong)) print(cython.sizeof(cython.uint) == cython.sizeof(cython.int)) print(cython.sizeof(cython.p_int) == cython.sizeof(cython.p_double)) if cython.compiled: print(cython.sizeof(cython.char) < cython.sizeof(cython.longlong)) else: print(cython.sizeof(cython.char) == 1) ## CURRENTLY BROKEN - FIXME!! ## def test_declare(n): ## """ ## >>> test_declare(100) ## (100, 100) ## >>> test_declare(100.5) ## (100, 100) ## >>> test_declare(None) ## Traceback (most recent call last): ## ... ## TypeError: an integer is required ## """ ## x = cython.declare(cython.int) ## y = cython.declare(cython.int, n) ## if cython.compiled: ## cython.declare(xx=cython.int, yy=cython.long) ## i = sizeof(xx) ## ptr = cython.declare(cython.p_int, cython.address(y)) ## return y, ptr[0] @cython.locals(x=cython.double, n=cython.int) def test_cast(x): """ >>> test_cast(1.5) 1 """ n = cython.cast(cython.int, x) return n @cython.locals(x=cython.int, y=cython.p_int) def test_address(x): """ >>> test_address(39) 39 """ y = cython.address(x) return y[0] ## CURRENTLY BROKEN - FIXME!! ## @cython.locals(x=cython.int) ## @cython.locals(y=cython.bint) ## def test_locals(x): ## """ ## >>> test_locals(5) ## True ## """<|fim▁hole|>## y = x ## return y def test_with_nogil(nogil): """ >>> raised = [] >>> class nogil(object): ... def __enter__(self): ... pass ... def __exit__(self, exc_class, exc, tb): ... raised.append(exc) ... return exc_class is None >>> test_with_nogil(nogil()) WORKS True >>> raised [None] """ result = False with nogil: print("WORKS") with cython.nogil: result = True return result ## CURRENTLY BROKEN - FIXME!! ## MyUnion = cython.union(n=cython.int, x=cython.double) ## MyStruct = cython.struct(is_integral=cython.bint, data=MyUnion) ## MyStruct2 = cython.typedef(MyStruct[2]) ## def test_struct(n, x): ## """ ## >>> test_struct(389, 1.64493) ## (389, 1.64493) ## """ ## a = cython.declare(MyStruct2) ## a[0] = MyStruct(True, data=MyUnion(n=n)) ## a[1] = MyStruct(is_integral=False, data={'x': x}) ## return a[0].data.n, a[1].data.x import cython as cy from cython import declare, cast, locals, address, typedef, p_void, compiled from cython import declare as my_declare, locals as my_locals, p_void as my_void_star, typedef as my_typedef, compiled as my_compiled @my_locals(a=cython.p_void) def test_imports(): """ >>> test_imports() # (True, True) True """ a = cython.NULL b = declare(p_void, cython.NULL) c = my_declare(my_void_star, cython.NULL) d = cy.declare(cy.p_void, cython.NULL) ## CURRENTLY BROKEN - FIXME!! #return a == d, compiled == my_compiled return compiled == my_compiled ## CURRENTLY BROKEN - FIXME!! ## MyStruct3 = typedef(MyStruct[3]) ## MyStruct4 = my_typedef(MyStruct[4]) ## MyStruct5 = cy.typedef(MyStruct[5]) def test_declare_c_types(n): """ >>> test_declare_c_types(0) >>> test_declare_c_types(1) >>> test_declare_c_types(2) """ # b00 = cython.declare(cython.bint, 0) b01 = cython.declare(cython.bint, 1) b02 = cython.declare(cython.bint, 2) # i00 = cython.declare(cython.uchar, n) i01 = cython.declare(cython.char, n) i02 = cython.declare(cython.schar, n) i03 = cython.declare(cython.ushort, n) i04 = cython.declare(cython.short, n) i05 = cython.declare(cython.sshort, n) i06 = cython.declare(cython.uint, n) i07 = cython.declare(cython.int, n) i08 = cython.declare(cython.sint, n) i09 = cython.declare(cython.slong, n) i10 = cython.declare(cython.long, n) i11 = cython.declare(cython.ulong, n) i12 = cython.declare(cython.slonglong, n) i13 = cython.declare(cython.longlong, n) i14 = cython.declare(cython.ulonglong, n) i20 = cython.declare(cython.Py_ssize_t, n) i21 = cython.declare(cython.size_t, n) # f00 = cython.declare(cython.float, n) f01 = cython.declare(cython.double, n) f02 = cython.declare(cython.longdouble, n) # #z00 = cython.declare(cython.complex, n+1j) #z01 = cython.declare(cython.floatcomplex, n+1j) #z02 = cython.declare(cython.doublecomplex, n+1j) #z03 = cython.declare(cython.longdoublecomplex, n+1j)<|fim▁end|>
<|file_name|>run-tests-exp.py<|end_file_name|><|fim▁begin|># # This is minimal MicroPython variant of run-tests script, which uses # .exp files as generated by run-tests --write-exp. It is useful to run # testsuite on systems which have neither CPython3 nor unix shell. # This script is intended to be run by the same interpreter executable # which is to be tested, so should use minimal language functionality. # import sys import uos as os tests = [ "basics", "micropython", "float", "import", "io", " misc", "unicode", "extmod", "unix" ] if sys.platform == 'win32': MICROPYTHON = "micropython.exe" else: MICROPYTHON = "micropython" def should_skip(test): if test.startswith("native"): return True if test.startswith("viper"): return True test_count = 0 passed_count = 0 skip_count = 0 for suite in tests: #print("Running in: %s" % suite) if sys.platform == 'win32': # dir /b prints only contained filenames, one on a line # http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/dir.mspx r = os.system("dir /b %s/*.py >tests.lst" % suite) else: r = os.system("ls %s/*.py | xargs -n1 basename >tests.lst" % suite) assert r == 0 with open("tests.lst") as f: testcases = f.readlines() testcases = [l[:-1] for l in testcases] assert testcases, "No tests found in dir '%s', which is implausible" % suite #print(testcases) for t in testcases: if t == "native_check.py": continue qtest = "%s/%s" % (suite, t) if should_skip(t): print("skip " + qtest) skip_count += 1 continue exp = None try: f = open(qtest + ".exp") exp = f.read() f.close() except OSError: pass if exp is not None: #print("run " + qtest) r = os.system(MICROPYTHON + " %s >.tst.out" % qtest)<|fim▁hole|> out = f.read() f.close() else: out = "CRASH" if out == "SKIP\n": print("skip " + qtest) skip_count += 1 else: if out == exp: print("pass " + qtest) passed_count += 1 else: print("FAIL " + qtest) test_count += 1 else: skip_count += 1 print("%s tests performed" % test_count) print("%s tests passed" % passed_count) if test_count != passed_count: print("%s tests failed" % (test_count - passed_count)) if skip_count: print("%s tests skipped" % skip_count)<|fim▁end|>
if r == 0: f = open(".tst.out")
<|file_name|>attr-before-view-item2.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unused_attributes)] // pretty-expanded FIXME #23616 #![feature(custom_attribute, test)] mod m { #[foo = "bar"] extern crate test; } pub fn main() { }<|fim▁end|>
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
<|file_name|>ReactIcon.js<|end_file_name|><|fim▁begin|>import { IconPathDetails } from '../config'; class ReactIcon { constructor(name, component) { this.name = name; this.file = `${IconPathDetails.iconDir}${name}.jsx`; this.component = component; }<|fim▁hole|>} export default ReactIcon;<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// (c) 2015-2017 Productize SPRL <[email protected]> //! symbolic-expressions parsing and generating library #![warn(missing_docs)] pub use error::*; pub use sexp::*; mod error; mod formatter; mod sexp; /// symbolic-expression parser code: data -> symbolic-expression pub mod parser; /// symbolic-expression serialization code: symbolic-expression -> data pub mod ser; /// high-level API for deconstructing symbolic-expressions pub mod iteratom; pub use formatter::Rules; pub use formatter::Formatter; pub use iteratom::from_sexp;<|fim▁hole|><|fim▁end|>
#[cfg(test)] mod test;
<|file_name|>kinetic-v5.1.0.js<|end_file_name|><|fim▁begin|>/* * KineticJS JavaScript Framework v5.1.0 * http://www.kineticjs.com/ * Copyright 2013, Eric Rowell * Licensed under the MIT or GPL Version 2 licenses. * Date: 2014-03-27 * * Copyright (C) 2011 - 2013 by Eric Rowell * * 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. */ /** * @namespace Kinetic */ /*jshint -W079, -W020*/ var Kinetic = {}; (function(root) { var PI_OVER_180 = Math.PI / 180; Kinetic = { // public version: '5.1.0', // private stages: [], idCounter: 0, ids: {}, names: {}, shapes: {}, listenClickTap: false, inDblClickWindow: false, // configurations enableTrace: false, traceArrMax: 100, dblClickWindow: 400, pixelRatio: undefined, dragDistance : 0, angleDeg: true, // user agent UA: (function() { var userAgent = (root.navigator && root.navigator.userAgent) || ''; var ua = userAgent.toLowerCase(), // jQuery UA regex match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || [], // adding mobile flag as well mobile = !!(userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)); return { browser: match[ 1 ] || '', version: match[ 2 ] || '0', // adding mobile flab mobile: mobile }; })(), /** * @namespace Filters * @memberof Kinetic */ Filters: {}, /** * Node constructor. Nodes are entities that can be transformed, layered, * and have bound events. The stage, layers, groups, and shapes all extend Node. * @constructor * @memberof Kinetic * @abstract * @param {Object} config * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] */ Node: function(config) { this._init(config); }, /** * Shape constructor. Shapes are primitive objects such as rectangles, * circles, text, lines, etc. * @constructor * @memberof Kinetic * @augments Kinetic.Node * @param {Object} config * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var customShape = new Kinetic.Shape({<br> * x: 5,<br> * y: 10,<br> * fill: 'red',<br> * // a Kinetic.Canvas renderer is passed into the drawFunc function<br> * drawFunc: function(context) {<br> * context.beginPath();<br> * context.moveTo(200, 50);<br> * context.lineTo(420, 80);<br> * context.quadraticCurveTo(300, 100, 260, 170);<br> * context.closePath();<br> * context.fillStrokeShape(this);<br> * }<br> *}); */ Shape: function(config) { this.__init(config); }, /** * Container constructor.&nbsp; Containers are used to contain nodes or other containers * @constructor * @memberof Kinetic * @augments Kinetic.Node * @abstract * @param {Object} config * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @param {Function} [config.clipFunc] clipping function */ Container: function(config) { this.__init(config); }, /** * Stage constructor. A stage is used to contain multiple layers * @constructor * @memberof Kinetic * @augments Kinetic.Container * @param {Object} config * @param {String|DomElement} config.container Container id or DOM element * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @param {Function} [config.clipFunc] clipping function * @example * var stage = new Kinetic.Stage({<br> * width: 500,<br> * height: 800,<br> * container: 'containerId'<br> * }); */ Stage: function(config) { this.___init(config); }, /** * BaseLayer constructor. * @constructor * @memberof Kinetic * @augments Kinetic.Container * @param {Object} config * @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want * to clear the canvas before each layer draw. The default value is true. * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @param {Function} [config.clipFunc] clipping function * @example * var layer = new Kinetic.Layer(); */ BaseLayer: function(config) { this.___init(config); }, /** * Layer constructor. Layers are tied to their own canvas element and are used * to contain groups or shapes * @constructor * @memberof Kinetic * @augments Kinetic.Container * @param {Object} config * @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want * to clear the canvas before each layer draw. The default value is true. * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @param {Function} [config.clipFunc] clipping function * @example * var layer = new Kinetic.Layer(); */ Layer: function(config) { this.____init(config); }, /** * FastLayer constructor. Layers are tied to their own canvas element and are used * to contain groups or shapes * @constructor * @memberof Kinetic * @augments Kinetic.Container * @param {Object} config * @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want * to clear the canvas before each layer draw. The default value is true. * @example * var layer = new Kinetic.FastLayer(); */ FastLayer: function(config) { this.____init(config); }, /** * Group constructor. Groups are used to contain shapes or other groups. * @constructor * @memberof Kinetic * @augments Kinetic.Container * @param {Object} config * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @param {Function} [config.clipFunc] clipping function * @example * var group = new Kinetic.Group(); */ Group: function(config) { this.___init(config); }, /** * returns whether or not drag and drop is currently active * @method * @memberof Kinetic */ isDragging: function() { var dd = Kinetic.DD; // if DD is not included with the build, then // drag and drop is not even possible if (!dd) { return false; } // if DD is included with the build else { return dd.isDragging; } }, /** * returns whether or not a drag and drop operation is ready, but may * not necessarily have started * @method * @memberof Kinetic */ isDragReady: function() { var dd = Kinetic.DD; // if DD is not included with the build, then // drag and drop is not even possible if (!dd) { return false; } // if DD is included with the build else { return !!dd.node; } }, _addId: function(node, id) { if(id !== undefined) { this.ids[id] = node; } }, _removeId: function(id) { if(id !== undefined) { delete this.ids[id]; } }, _addName: function(node, name) { if(name !== undefined) { if(this.names[name] === undefined) { this.names[name] = []; } this.names[name].push(node); } }, _removeName: function(name, _id) { if(name !== undefined) { var nodes = this.names[name]; if(nodes !== undefined) { for(var n = 0; n < nodes.length; n++) { var no = nodes[n]; if(no._id === _id) { nodes.splice(n, 1); } } if(nodes.length === 0) { delete this.names[name]; } } } }, getAngle: function(angle) { return this.angleDeg ? angle * PI_OVER_180 : angle; } }; })(this); // Uses Node, AMD or browser globals to create a module. // If you want something that will work in other stricter CommonJS environments, // or if you need to create a circular dependency, see commonJsStrict.js // Defines a module "returnExports" that depends another module called "b". // Note that the name of the module is implied by the file name. It is best // if the file name and the exported global have matching names. // If the 'b' module also uses this type of boilerplate, then // in the browser, it will create a global .b that is used below. // If you do not want to support the browser global path, then you // can remove the `root` use and the passing `this` as the first arg to // the top function. // if the module has no dependencies, the above pattern can be simplified to ( function(root, factory) { if( typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. var Canvas = require('canvas'); var jsdom = require('jsdom').jsdom; var doc = jsdom('<!DOCTYPE html><html><head></head><body></body></html>'); var KineticJS = factory(); Kinetic.document = doc; Kinetic.window = Kinetic.document.createWindow(); Kinetic.window.Image = Canvas.Image; Kinetic.root = root; Kinetic._nodeCanvas = Canvas; module.exports = KineticJS; return; } else if( typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } Kinetic.document = document; Kinetic.window = window; Kinetic.root = root; }((1, eval)('this'), function() { // Just return a value to define the module export. // This example returns an object, but the module // can return a function as the exported value. return Kinetic; })); ;(function() { /** * Collection constructor. Collection extends * Array. This class is used in conjunction with {@link Kinetic.Container#get} * @constructor * @memberof Kinetic */ Kinetic.Collection = function() { var args = [].slice.call(arguments), length = args.length, i = 0; this.length = length; for(; i < length; i++) { this[i] = args[i]; } return this; }; Kinetic.Collection.prototype = []; /** * iterate through node array and run a function for each node. * The node and index is passed into the function * @method * @memberof Kinetic.Collection.prototype * @param {Function} func * @example * // get all nodes with name foo inside layer, and set x to 10 for each * layer.get('.foo').each(function(shape, n) {<br> * shape.setX(10);<br> * }); */ Kinetic.Collection.prototype.each = function(func) { for(var n = 0; n < this.length; n++) { func(this[n], n); } }; /** * convert collection into an array * @method * @memberof Kinetic.Collection.prototype */ Kinetic.Collection.prototype.toArray = function() { var arr = [], len = this.length, n; for(n = 0; n < len; n++) { arr.push(this[n]); } return arr; }; /** * convert array into a collection * @method * @memberof Kinetic.Collection * @param {Array} arr */ Kinetic.Collection.toCollection = function(arr) { var collection = new Kinetic.Collection(), len = arr.length, n; for(n = 0; n < len; n++) { collection.push(arr[n]); } return collection; }; // map one method by it's name Kinetic.Collection._mapMethod = function(methodName) { Kinetic.Collection.prototype[methodName] = function() { var len = this.length, i; var args = [].slice.call(arguments); for(i = 0; i < len; i++) { this[i][methodName].apply(this[i], args); } return this; }; }; Kinetic.Collection.mapMethods = function(constructor) { var prot = constructor.prototype; for(var methodName in prot) { Kinetic.Collection._mapMethod(methodName); } }; /* * Last updated November 2011 * By Simon Sarris * www.simonsarris.com * [email protected] * * Free to use and distribute at will * So long as you are nice to people, etc */ /* * The usage of this class was inspired by some of the work done by a forked * project, KineticJS-Ext by Wappworks, which is based on Simon's Transform * class. Modified by Eric Rowell */ /** * Transform constructor * @constructor * @param {Array} Optional six-element matrix * @memberof Kinetic */ Kinetic.Transform = function(m) { this.m = (m && m.slice()) || [1, 0, 0, 1, 0, 0]; }; Kinetic.Transform.prototype = { /** * Copy Kinetic.Transform object * @method * @memberof Kinetic.Transform.prototype * @returns {Kinetic.Transform} */ copy: function() { return new Kinetic.Transform(this.m); }, /** * Transform point * @method * @memberof Kinetic.Transform.prototype * @param {Object} 2D point(x, y) * @returns {Object} 2D point(x, y) */ point: function(p) { var m = this.m; return { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] }; }, /** * Apply translation * @method * @memberof Kinetic.Transform.prototype * @param {Number} x * @param {Number} y * @returns {Kinetic.Transform} */ translate: function(x, y) { this.m[4] += this.m[0] * x + this.m[2] * y; this.m[5] += this.m[1] * x + this.m[3] * y; return this; }, /** * Apply scale * @method * @memberof Kinetic.Transform.prototype * @param {Number} sx * @param {Number} sy * @returns {Kinetic.Transform} */ scale: function(sx, sy) { this.m[0] *= sx; this.m[1] *= sx; this.m[2] *= sy; this.m[3] *= sy; return this; }, /** * Apply rotation * @method * @memberof Kinetic.Transform.prototype * @param {Number} rad Angle in radians * @returns {Kinetic.Transform} */ rotate: function(rad) { var c = Math.cos(rad); var s = Math.sin(rad); var m11 = this.m[0] * c + this.m[2] * s; var m12 = this.m[1] * c + this.m[3] * s; var m21 = this.m[0] * -s + this.m[2] * c; var m22 = this.m[1] * -s + this.m[3] * c; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; this.m[3] = m22; return this; }, /** * Returns the translation * @method * @memberof Kinetic.Transform.prototype * @returns {Object} 2D point(x, y) */ getTranslation: function() { return { x: this.m[4], y: this.m[5] }; }, /** * Apply skew * @method * @memberof Kinetic.Transform.prototype * @param {Number} sx * @param {Number} sy * @returns {Kinetic.Transform} */ skew: function(sx, sy) { var m11 = this.m[0] + this.m[2] * sy; var m12 = this.m[1] + this.m[3] * sy; var m21 = this.m[2] + this.m[0] * sx; var m22 = this.m[3] + this.m[1] * sx; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; this.m[3] = m22; return this; }, /** * Transform multiplication * @method * @memberof Kinetic.Transform.prototype * @param {Kinetic.Transform} matrix * @returns {Kinetic.Transform} */ multiply: function(matrix) { var m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1]; var m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1]; var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3]; var m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3]; var dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4]; var dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5]; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; this.m[3] = m22; this.m[4] = dx; this.m[5] = dy; return this; }, /** * Invert the matrix * @method * @memberof Kinetic.Transform.prototype * @returns {Kinetic.Transform} */ invert: function() { var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]); var m0 = this.m[3] * d; var m1 = -this.m[1] * d; var m2 = -this.m[2] * d; var m3 = this.m[0] * d; var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]); var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]); this.m[0] = m0; this.m[1] = m1; this.m[2] = m2; this.m[3] = m3; this.m[4] = m4; this.m[5] = m5; return this; }, /** * return matrix * @method * @memberof Kinetic.Transform.prototype */ getMatrix: function() { return this.m; }, /** * set to absolute position via translation * @method * @memberof Kinetic.Transform.prototype * @returns {Kinetic.Transform} * @author ericdrowell */ setAbsolutePosition: function(x, y) { var m0 = this.m[0], m1 = this.m[1], m2 = this.m[2], m3 = this.m[3], m4 = this.m[4], m5 = this.m[5], yt = ((m0 * (y - m5)) - (m1 * (x - m4))) / ((m0 * m3) - (m1 * m2)), xt = (x - m4 - (m2 * yt)) / m0; return this.translate(xt, yt); } }; // CONSTANTS var CANVAS = 'canvas', CONTEXT_2D = '2d', OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH = '#', EMPTY_STRING = '', ZERO = '0', KINETIC_WARNING = 'Kinetic warning: ', KINETIC_ERROR = 'Kinetic error: ', RGB_PAREN = 'rgb(', COLORS = { aqua: [0,255,255], lime: [0,255,0], silver: [192,192,192], black: [0,0,0], maroon: [128,0,0], teal: [0,128,128], blue: [0,0,255], navy: [0,0,128], white: [255,255,255], fuchsia: [255,0,255], olive:[128,128,0], yellow: [255,255,0], orange: [255,165,0], gray: [128,128,128], purple: [128,0,128], green: [0,128,0], red: [255,0,0], pink: [255,192,203], cyan: [0,255,255], transparent: [255,255,255,0] }, RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/; /** * @namespace Util * @memberof Kinetic */ Kinetic.Util = { /* * cherry-picked utilities from underscore.js */ _isElement: function(obj) { return !!(obj && obj.nodeType == 1); }, _isFunction: function(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, _isObject: function(obj) { return (!!obj && obj.constructor == Object); }, _isArray: function(obj) { return Object.prototype.toString.call(obj) == OBJECT_ARRAY; }, _isNumber: function(obj) { return Object.prototype.toString.call(obj) == OBJECT_NUMBER; }, _isString: function(obj) { return Object.prototype.toString.call(obj) == OBJECT_STRING; }, // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : new Date().getTime(); timeout = null; result = func.apply(context, args); context = args = null; }; return function() { var now = new Date().getTime(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }, /* * other utils */ _hasMethods: function(obj) { var names = [], key; for(key in obj) { if(this._isFunction(obj[key])) { names.push(key); } } return names.length > 0; }, createCanvasElement: function() { var canvas = Kinetic.document.createElement('canvas'); canvas.style = canvas.style || {}; return canvas; }, isBrowser: function() { return (typeof exports !== 'object'); }, _isInDocument: function(el) { while(el = el.parentNode) { if(el == Kinetic.document) { return true; } } return false; }, _simplifyArray: function(arr) { var retArr = [], len = arr.length, util = Kinetic.Util, n, val; for (n=0; n<len; n++) { val = arr[n]; if (util._isNumber(val)) { val = Math.round(val * 1000) / 1000; } else if (!util._isString(val)) { val = val.toString(); } retArr.push(val); } return retArr; }, /* * arg can be an image object or image data */ _getImage: function(arg, callback) { var imageObj, canvas; // if arg is null or undefined if(!arg) { callback(null); } // if arg is already an image object else if(this._isElement(arg)) { callback(arg); } // if arg is a string, then it's a data url else if(this._isString(arg)) { imageObj = new Kinetic.window.Image(); imageObj.onload = function() { callback(imageObj); }; imageObj.src = arg; } //if arg is an object that contains the data property, it's an image object else if(arg.data) { canvas = Kinetic.Util.createCanvasElement(); canvas.width = arg.width; canvas.height = arg.height; var _context = canvas.getContext(CONTEXT_2D); _context.putImageData(arg, 0, 0); this._getImage(canvas.toDataURL(), callback); } else { callback(null); } }, _getRGBAString: function(obj) { var red = obj.red || 0, green = obj.green || 0, blue = obj.blue || 0, alpha = obj.alpha || 1; return [ 'rgba(', red, ',', green, ',', blue, ',', alpha, ')' ].join(EMPTY_STRING); }, _rgbToHex: function(r, g, b) { return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }, _hexToRgb: function(hex) { hex = hex.replace(HASH, EMPTY_STRING); var bigint = parseInt(hex, 16); return { r: (bigint >> 16) & 255, g: (bigint >> 8) & 255, b: bigint & 255 }; }, /** * return random hex color * @method * @memberof Kinetic.Util.prototype */ getRandomColor: function() { var randColor = (Math.random() * 0xFFFFFF << 0).toString(16); while (randColor.length < 6) { randColor = ZERO + randColor; } return HASH + randColor; }, /** * return value with default fallback * @method * @memberof Kinetic.Util.prototype */ get: function(val, def) { if (val === undefined) { return def; } else { return val; } }, /** * get RGB components of a color * @method * @memberof Kinetic.Util.prototype * @param {String} color * @example * // each of the following examples return {r:0, g:0, b:255}<br> * var rgb = Kinetic.Util.getRGB('blue');<br> * var rgb = Kinetic.Util.getRGB('#0000ff');<br> * var rgb = Kinetic.Util.getRGB('rgb(0,0,255)'); */ getRGB: function(color) { var rgb; // color string if (color in COLORS) { rgb = COLORS[color]; return { r: rgb[0], g: rgb[1], b: rgb[2] }; } // hex else if (color[0] === HASH) { return this._hexToRgb(color.substring(1)); } // rgb string else if (color.substr(0, 4) === RGB_PAREN) { rgb = RGB_REGEX.exec(color.replace(/ /g,'')); return { r: parseInt(rgb[1], 10), g: parseInt(rgb[2], 10), b: parseInt(rgb[3], 10) }; } // default else { return { r: 0, g: 0, b: 0 }; } }, // o1 takes precedence over o2 _merge: function(o1, o2) { var retObj = this._clone(o2); for(var key in o1) { if(this._isObject(o1[key])) { retObj[key] = this._merge(o1[key], retObj[key]); } else { retObj[key] = o1[key]; } } return retObj; }, cloneObject: function(obj) { var retObj = {}; for(var key in obj) { if(this._isObject(obj[key])) { retObj[key] = this.cloneObject(obj[key]); } else if (this._isArray(obj[key])) { retObj[key] = this.cloneArray(obj[key]); } else { retObj[key] = obj[key]; } } return retObj; }, cloneArray: function(arr) { return arr.slice(0); }, _degToRad: function(deg) { return deg * PI_OVER_DEG180; }, _radToDeg: function(rad) { return rad * DEG180_OVER_PI; }, _capitalize: function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }, error: function(str) { throw new Error(KINETIC_ERROR + str); }, warn: function(str) { /* * IE9 on Windows7 64bit will throw a JS error * if we don't use window.console in the conditional */ if(Kinetic.root.console && console.warn) { console.warn(KINETIC_WARNING + str); } }, extend: function(c1, c2) { for(var key in c2.prototype) { if(!( key in c1.prototype)) { c1.prototype[key] = c2.prototype[key]; } } }, /** * adds methods to a constructor prototype * @method * @memberof Kinetic.Util.prototype * @param {Function} constructor * @param {Object} methods */ addMethods: function(constructor, methods) { var key; for (key in methods) { constructor.prototype[key] = methods[key]; } }, _getControlPoints: function(x0, y0, x1, y1, x2, y2, t) { var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), fa = t * d01 / (d01 + d12), fb = t * d12 / (d01 + d12), p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0); return [p1x ,p1y, p2x, p2y]; }, _expandPoints: function(p, tension) { var len = p.length, allPoints = [], n, cp; for (n=2; n<len-2; n+=2) { cp = Kinetic.Util._getControlPoints(p[n-2], p[n-1], p[n], p[n+1], p[n+2], p[n+3], tension); allPoints.push(cp[0]); allPoints.push(cp[1]); allPoints.push(p[n]); allPoints.push(p[n+1]); allPoints.push(cp[2]); allPoints.push(cp[3]); } return allPoints; }, _removeLastLetter: function(str) { return str.substring(0, str.length - 1); } }; })(); ;(function() { // calculate pixel ratio var canvas = Kinetic.Util.createCanvasElement(), context = canvas.getContext('2d'), // if using a mobile device, calculate the pixel ratio. Otherwise, just use // 1. For desktop browsers, if the user has zoom enabled, it affects the pixel ratio // and causes artifacts on the canvas. As of 02/26/2014, there doesn't seem to be a way // to reliably calculate the browser zoom for modern browsers, which is why we just set // the pixel ratio to 1 for desktops _pixelRatio = Kinetic.UA.mobile ? (function() { var devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return devicePixelRatio / backingStoreRatio; })() : 1; /** * Canvas Renderer constructor * @constructor * @abstract * @memberof Kinetic * @param {Number} width * @param {Number} height * @param {Number} pixelRatio KineticJS automatically handles pixel ratio adustments in order to render crisp drawings * on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios * of 1. Some high end tablets and phones, like iPhones and iPads (not the mini) have a device pixel ratio * of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel * ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise * specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel * ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1. */ Kinetic.Canvas = function(config) { this.init(config); }; Kinetic.Canvas.prototype = { init: function(config) { config = config || {}; var pixelRatio = config.pixelRatio || Kinetic.pixelRatio || _pixelRatio; this.pixelRatio = pixelRatio; this._canvas = Kinetic.Util.createCanvasElement(); // set inline styles this._canvas.style.padding = 0; this._canvas.style.margin = 0; this._canvas.style.border = 0; this._canvas.style.background = 'transparent'; this._canvas.style.position = 'absolute'; this._canvas.style.top = 0; this._canvas.style.left = 0; }, /** * get canvas context * @method * @memberof Kinetic.Canvas.prototype * @returns {CanvasContext} context */ getContext: function() { return this.context; }, /** * get pixel ratio * @method * @memberof Kinetic.Canvas.prototype * @returns {Number} pixel ratio */ getPixelRatio: function() { return this.pixelRatio; }, /** * get pixel ratio * @method * @memberof Kinetic.Canvas.prototype * @param {Number} pixelRatio KineticJS automatically handles pixel ratio adustments in order to render crisp drawings * on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios * of 1. Some high end tablets and phones, like iPhones and iPads (not the mini) have a device pixel ratio * of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel * ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise * specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel * ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1. */ setPixelRatio: function(pixelRatio) { this.pixelRatio = pixelRatio; this.setSize(this.getWidth(), this.getHeight()); }, /** * set width * @method * @memberof Kinetic.Canvas.prototype * @param {Number} width */ setWidth: function(width) { // take into account pixel ratio this.width = this._canvas.width = width * this.pixelRatio; this._canvas.style.width = width + 'px'; }, /** * set height * @method * @memberof Kinetic.Canvas.prototype * @param {Number} height */ setHeight: function(height) { // take into account pixel ratio this.height = this._canvas.height = height * this.pixelRatio; this._canvas.style.height = height + 'px'; }, /** * get width * @method * @memberof Kinetic.Canvas.prototype * @returns {Number} width */ getWidth: function() { return this.width; }, /** * get height * @method * @memberof Kinetic.Canvas.prototype * @returns {Number} height */ getHeight: function() { return this.height; }, /** * set size * @method * @memberof Kinetic.Canvas.prototype * @param {Number} width * @param {Number} height */ setSize: function(width, height) { this.setWidth(width); this.setHeight(height); }, /** * to data url * @method * @memberof Kinetic.Canvas.prototype * @param {String} mimeType * @param {Number} quality between 0 and 1 for jpg mime types * @returns {String} data url string */ toDataURL: function(mimeType, quality) { try { // If this call fails (due to browser bug, like in Firefox 3.6), // then revert to previous no-parameter image/png behavior return this._canvas.toDataURL(mimeType, quality); } catch(e) { try { return this._canvas.toDataURL(); } catch(err) { Kinetic.Util.warn('Unable to get data URL. ' + err.message); return ''; } } } }; Kinetic.SceneCanvas = function(config) { config = config || {}; var width = config.width || 0, height = config.height || 0; Kinetic.Canvas.call(this, config); this.context = new Kinetic.SceneContext(this); this.setSize(width, height); }; Kinetic.SceneCanvas.prototype = { setWidth: function(width) { var pixelRatio = this.pixelRatio, _context = this.getContext()._context; Kinetic.Canvas.prototype.setWidth.call(this, width); _context.scale(pixelRatio, pixelRatio); }, setHeight: function(height) { var pixelRatio = this.pixelRatio, _context = this.getContext()._context; Kinetic.Canvas.prototype.setHeight.call(this, height); _context.scale(pixelRatio, pixelRatio); } }; Kinetic.Util.extend(Kinetic.SceneCanvas, Kinetic.Canvas); Kinetic.HitCanvas = function(config) { config = config || {}; var width = config.width || 0, height = config.height || 0; Kinetic.Canvas.call(this, config); this.context = new Kinetic.HitContext(this); this.setSize(width, height); }; Kinetic.Util.extend(Kinetic.HitCanvas, Kinetic.Canvas); })(); ;(function() { var COMMA = ',', OPEN_PAREN = '(', CLOSE_PAREN = ')', OPEN_PAREN_BRACKET = '([', CLOSE_BRACKET_PAREN = '])', SEMICOLON = ';', DOUBLE_PAREN = '()', // EMPTY_STRING = '', EQUALS = '=', // SET = 'set', CONTEXT_METHODS = [ 'arc', 'arcTo', 'beginPath', 'bezierCurveTo', 'clearRect', 'clip', 'closePath', 'createLinearGradient', 'createPattern', 'createRadialGradient', 'drawImage', 'fill', 'fillText', 'getImageData', 'createImageData', 'lineTo', 'moveTo', 'putImageData', 'quadraticCurveTo', 'rect', 'restore', 'rotate', 'save', 'scale', 'setLineDash', 'setTransform', 'stroke', 'strokeText', 'transform', 'translate' ]; /** * Canvas Context constructor * @constructor * @abstract * @memberof Kinetic */ Kinetic.Context = function(canvas) { this.init(canvas); }; Kinetic.Context.prototype = { init: function(canvas) { this.canvas = canvas; this._context = canvas._canvas.getContext('2d'); if (Kinetic.enableTrace) { this.traceArr = []; this._enableTrace(); } }, /** * fill shape * @method * @memberof Kinetic.Context.prototype * @param {Kinetic.Shape} shape */ fillShape: function(shape) { if(shape.getFillEnabled()) { this._fill(shape); } }, /** * stroke shape * @method * @memberof Kinetic.Context.prototype * @param {Kinetic.Shape} shape */ strokeShape: function(shape) { if(shape.getStrokeEnabled()) { this._stroke(shape); } }, /** * fill then stroke * @method * @memberof Kinetic.Context.prototype * @param {Kinetic.Shape} shape */ fillStrokeShape: function(shape) { var fillEnabled = shape.getFillEnabled(); if(fillEnabled) { this._fill(shape); } if(shape.getStrokeEnabled()) { this._stroke(shape); } }, /** * get context trace if trace is enabled * @method * @memberof Kinetic.Context.prototype * @param {Boolean} relaxed if false, return strict context trace, which includes method names, method parameters * properties, and property values. If true, return relaxed context trace, which only returns method names and * properites. * @returns {String} */ getTrace: function(relaxed) { var traceArr = this.traceArr, len = traceArr.length, str = '', n, trace, method, args; for (n=0; n<len; n++) { trace = traceArr[n]; method = trace.method; // methods if (method) { args = trace.args; str += method; if (relaxed) { str += DOUBLE_PAREN; } else { if (Kinetic.Util._isArray(args[0])) { str += OPEN_PAREN_BRACKET + args.join(COMMA) + CLOSE_BRACKET_PAREN; } else { str += OPEN_PAREN + args.join(COMMA) + CLOSE_PAREN; } } } // properties else { str += trace.property; if (!relaxed) { str += EQUALS + trace.val; } } str += SEMICOLON; } return str; }, /** * clear trace if trace is enabled * @method * @memberof Kinetic.Context.prototype */ clearTrace: function() { this.traceArr = []; }, _trace: function(str) { var traceArr = this.traceArr, len; traceArr.push(str); len = traceArr.length; if (len >= Kinetic.traceArrMax) { traceArr.shift(); } }, /** * reset canvas context transform * @method * @memberof Kinetic.Context.prototype */ reset: function() { var pixelRatio = this.getCanvas().getPixelRatio(); this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0); }, /** * get canvas * @method * @memberof Kinetic.Context.prototype * @returns {Kinetic.Canvas} */ getCanvas: function() { return this.canvas; }, /** * clear canvas * @method * @memberof Kinetic.Context.prototype * @param {Object} [bounds] * @param {Number} [bounds.x] * @param {Number} [bounds.y] * @param {Number} [bounds.width] * @param {Number} [bounds.height] */ clear: function(bounds) { var canvas = this.getCanvas(); if (bounds) { this.clearRect(bounds.x || 0, bounds.y || 0, bounds.width || 0, bounds.height || 0); } else { this.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); } }, _applyLineCap: function(shape) { var lineCap = shape.getLineCap(); if(lineCap) { this.setAttr('lineCap', lineCap); } }, _applyOpacity: function(shape) { var absOpacity = shape.getAbsoluteOpacity(); if(absOpacity !== 1) { this.setAttr('globalAlpha', absOpacity); } }, _applyLineJoin: function(shape) { var lineJoin = shape.getLineJoin(); if(lineJoin) { this.setAttr('lineJoin', lineJoin); } }, setAttr: function(attr, val) { this._context[attr] = val; }, // context pass through methods arc: function() { var a = arguments; this._context.arc(a[0], a[1], a[2], a[3], a[4], a[5]); }, beginPath: function() { this._context.beginPath(); }, bezierCurveTo: function() { var a = arguments; this._context.bezierCurveTo(a[0], a[1], a[2], a[3], a[4], a[5]); }, clearRect: function() { var a = arguments; this._context.clearRect(a[0], a[1], a[2], a[3]); }, clip: function() { this._context.clip(); }, closePath: function() { this._context.closePath(); }, createImageData: function() { var a = arguments; if(a.length === 2) { return this._context.createImageData(a[0], a[1]); } else if(a.length === 1) { return this._context.createImageData(a[0]); } }, createLinearGradient: function() { var a = arguments; return this._context.createLinearGradient(a[0], a[1], a[2], a[3]); }, createPattern: function() { var a = arguments; return this._context.createPattern(a[0], a[1]); }, createRadialGradient: function() { var a = arguments; return this._context.createRadialGradient(a[0], a[1], a[2], a[3], a[4], a[5]); }, drawImage: function() { var a = arguments, _context = this._context; if(a.length === 3) { _context.drawImage(a[0], a[1], a[2]); } else if(a.length === 5) { _context.drawImage(a[0], a[1], a[2], a[3], a[4]); } else if(a.length === 9) { _context.drawImage(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); } }, fill: function() { this._context.fill(); }, fillText: function() { var a = arguments; this._context.fillText(a[0], a[1], a[2]); }, getImageData: function() { var a = arguments; return this._context.getImageData(a[0], a[1], a[2], a[3]); }, lineTo: function() { var a = arguments; this._context.lineTo(a[0], a[1]); }, moveTo: function() { var a = arguments; this._context.moveTo(a[0], a[1]); }, rect: function() { var a = arguments; this._context.rect(a[0], a[1], a[2], a[3]); }, putImageData: function() { var a = arguments; this._context.putImageData(a[0], a[1], a[2]); }, quadraticCurveTo: function() { var a = arguments; this._context.quadraticCurveTo(a[0], a[1], a[2], a[3]); }, restore: function() { this._context.restore(); }, rotate: function() { var a = arguments; this._context.rotate(a[0]); }, save: function() { this._context.save(); }, scale: function() { var a = arguments; this._context.scale(a[0], a[1]); }, setLineDash: function() { var a = arguments, _context = this._context; // works for Chrome and IE11 if(this._context.setLineDash) { _context.setLineDash(a[0]); } // verified that this works in firefox else if('mozDash' in _context) { _context.mozDash = a[0]; } // does not currently work for Safari else if('webkitLineDash' in _context) { _context.webkitLineDash = a[0]; } // no support for IE9 and IE10 }, setTransform: function() { var a = arguments; this._context.setTransform(a[0], a[1], a[2], a[3], a[4], a[5]); }, stroke: function() { this._context.stroke(); }, strokeText: function() { var a = arguments; this._context.strokeText(a[0], a[1], a[2]); }, transform: function() { var a = arguments; this._context.transform(a[0], a[1], a[2], a[3], a[4], a[5]); }, translate: function() { var a = arguments; this._context.translate(a[0], a[1]); }, _enableTrace: function() { var that = this, len = CONTEXT_METHODS.length, _simplifyArray = Kinetic.Util._simplifyArray, origSetter = this.setAttr, n, args; // to prevent creating scope function at each loop var func = function(methodName) { var origMethod = that[methodName], ret; that[methodName] = function() { args = _simplifyArray(Array.prototype.slice.call(arguments, 0)); ret = origMethod.apply(that, arguments); that._trace({ method: methodName, args: args }); return ret; }; }; // methods for (n=0; n<len; n++) { func(CONTEXT_METHODS[n]); } // attrs that.setAttr = function() { origSetter.apply(that, arguments); that._trace({ property: arguments[0], val: arguments[1] }); }; } }; Kinetic.SceneContext = function(canvas) { Kinetic.Context.call(this, canvas); }; Kinetic.SceneContext.prototype = { _fillColor: function(shape) { var fill = shape.fill() || Kinetic.Util._getRGBAString({ red: shape.fillRed(), green: shape.fillGreen(), blue: shape.fillBlue(), alpha: shape.fillAlpha() }); this.setAttr('fillStyle', fill); shape._fillFunc(this); }, _fillPattern: function(shape) { var fillPatternImage = shape.getFillPatternImage(), fillPatternX = shape.getFillPatternX(), fillPatternY = shape.getFillPatternY(), fillPatternScale = shape.getFillPatternScale(), fillPatternRotation = Kinetic.getAngle(shape.getFillPatternRotation()), fillPatternOffset = shape.getFillPatternOffset(), fillPatternRepeat = shape.getFillPatternRepeat(); if(fillPatternX || fillPatternY) { this.translate(fillPatternX || 0, fillPatternY || 0); } if(fillPatternRotation) { this.rotate(fillPatternRotation); } if(fillPatternScale) { this.scale(fillPatternScale.x, fillPatternScale.y); } if(fillPatternOffset) { this.translate(-1 * fillPatternOffset.x, -1 * fillPatternOffset.y); } this.setAttr('fillStyle', this.createPattern(fillPatternImage, fillPatternRepeat || 'repeat')); this.fill(); }, _fillLinearGradient: function(shape) { var start = shape.getFillLinearGradientStartPoint(), end = shape.getFillLinearGradientEndPoint(), colorStops = shape.getFillLinearGradientColorStops(), grd = this.createLinearGradient(start.x, start.y, end.x, end.y); if (colorStops) { // build color stops for(var n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n], colorStops[n + 1]); } this.setAttr('fillStyle', grd); this.fill(); } }, _fillRadialGradient: function(shape) { var start = shape.getFillRadialGradientStartPoint(), end = shape.getFillRadialGradientEndPoint(), startRadius = shape.getFillRadialGradientStartRadius(), endRadius = shape.getFillRadialGradientEndRadius(), colorStops = shape.getFillRadialGradientColorStops(), grd = this.createRadialGradient(start.x, start.y, startRadius, end.x, end.y, endRadius); // build color stops for(var n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n], colorStops[n + 1]); } this.setAttr('fillStyle', grd); this.fill(); }, _fill: function(shape) { var hasColor = shape.fill() || shape.fillRed() || shape.fillGreen() || shape.fillBlue(), hasPattern = shape.getFillPatternImage(), hasLinearGradient = shape.getFillLinearGradientColorStops(), hasRadialGradient = shape.getFillRadialGradientColorStops(), fillPriority = shape.getFillPriority(); // priority fills if(hasColor && fillPriority === 'color') { this._fillColor(shape); } else if(hasPattern && fillPriority === 'pattern') { this._fillPattern(shape); } else if(hasLinearGradient && fillPriority === 'linear-gradient') { this._fillLinearGradient(shape); } else if(hasRadialGradient && fillPriority === 'radial-gradient') { this._fillRadialGradient(shape); } // now just try and fill with whatever is available else if(hasColor) { this._fillColor(shape); } else if(hasPattern) { this._fillPattern(shape); } else if(hasLinearGradient) { this._fillLinearGradient(shape); } else if(hasRadialGradient) { this._fillRadialGradient(shape); } }, _stroke: function(shape) { var dash = shape.dash(), strokeScaleEnabled = shape.getStrokeScaleEnabled(); if(shape.hasStroke()) { if (!strokeScaleEnabled) { this.save(); this.setTransform(1, 0, 0, 1, 0, 0); } this._applyLineCap(shape); if(dash && shape.dashEnabled()) { this.setLineDash(dash); } this.setAttr('lineWidth', shape.strokeWidth()); this.setAttr('strokeStyle', shape.stroke() || Kinetic.Util._getRGBAString({ red: shape.strokeRed(), green: shape.strokeGreen(), blue: shape.strokeBlue(), alpha: shape.strokeAlpha() })); shape._strokeFunc(this); if (!strokeScaleEnabled) { this.restore(); } } }, _applyShadow: function(shape) { var util = Kinetic.Util, absOpacity = shape.getAbsoluteOpacity(), color = util.get(shape.getShadowColor(), 'black'), blur = util.get(shape.getShadowBlur(), 5), shadowOpacity = util.get(shape.getShadowOpacity(), 1), offset = util.get(shape.getShadowOffset(), { x: 0, y: 0 }); if(shadowOpacity) { this.setAttr('globalAlpha', shadowOpacity * absOpacity); } this.setAttr('shadowColor', color); this.setAttr('shadowBlur', blur); this.setAttr('shadowOffsetX', offset.x); this.setAttr('shadowOffsetY', offset.y); } }; Kinetic.Util.extend(Kinetic.SceneContext, Kinetic.Context); Kinetic.HitContext = function(canvas) { Kinetic.Context.call(this, canvas); }; Kinetic.HitContext.prototype = { _fill: function(shape) { this.save(); this.setAttr('fillStyle', shape.colorKey); shape._fillFuncHit(this); this.restore(); }, _stroke: function(shape) { if(shape.hasStroke()) { this._applyLineCap(shape); this.setAttr('lineWidth', shape.strokeWidth()); this.setAttr('strokeStyle', shape.colorKey); shape._strokeFuncHit(this); } } }; Kinetic.Util.extend(Kinetic.HitContext, Kinetic.Context); })(); ;/*jshint unused:false */ (function() { // CONSTANTS var ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransform', ADD = 'add', B = 'b', BEFORE = 'before', BLACK = 'black', CHANGE = 'Change', CHILDREN = 'children', DEG = 'Deg', DOT = '.', EMPTY_STRING = '', G = 'g', GET = 'get', HASH = '#', ID = 'id', KINETIC = 'kinetic', LISTENING = 'listening', MOUSEENTER = 'mouseenter', MOUSELEAVE = 'mouseleave', NAME = 'name', OFF = 'off', ON = 'on', PRIVATE_GET = '_get', R = 'r', RGB = 'RGB', SET = 'set', SHAPE = 'Shape', SPACE = ' ', STAGE = 'Stage', TRANSFORM = 'transform', UPPER_B = 'B', UPPER_G = 'G', UPPER_HEIGHT = 'Height', UPPER_R = 'R', UPPER_WIDTH = 'Width', UPPER_X = 'X', UPPER_Y = 'Y', VISIBLE = 'visible', X = 'x', Y = 'y'; Kinetic.Factory = { addGetterSetter: function(constructor, attr, def, validator, after) { this.addGetter(constructor, attr, def); this.addSetter(constructor, attr, validator, after); this.addOverloadedGetterSetter(constructor, attr); }, addGetter: function(constructor, attr, def) { var method = GET + Kinetic.Util._capitalize(attr); constructor.prototype[method] = function() { var val = this.attrs[attr]; return val === undefined ? def : val; }; }, addSetter: function(constructor, attr, validator, after) { var method = SET + Kinetic.Util._capitalize(attr); constructor.prototype[method] = function(val) { if (validator) { val = validator.call(this, val); } this._setAttr(attr, val); if (after) { after.call(this); } return this; }; }, addComponentsGetterSetter: function(constructor, attr, components, validator, after) { var len = components.length, capitalize = Kinetic.Util._capitalize, getter = GET + capitalize(attr), setter = SET + capitalize(attr), n, component; // getter constructor.prototype[getter] = function() { var ret = {}; for (n=0; n<len; n++) { component = components[n]; ret[component] = this.getAttr(attr + capitalize(component)); } return ret; }; // setter constructor.prototype[setter] = function(val) { var oldVal = this.attrs[attr], key; if (validator) { val = validator.call(this, val); } for (key in val) { this._setAttr(attr + capitalize(key), val[key]); } this._fireChangeEvent(attr, oldVal, val); if (after) { after.call(this); } return this; }; this.addOverloadedGetterSetter(constructor, attr); }, addOverloadedGetterSetter: function(constructor, attr) { var capitalizedAttr = Kinetic.Util._capitalize(attr), setter = SET + capitalizedAttr, getter = GET + capitalizedAttr; constructor.prototype[attr] = function() { // setting if (arguments.length) { this[setter](arguments[0]); return this; } // getting else { return this[getter](); } }; }, backCompat: function(constructor, methods) { var key; for (key in methods) { constructor.prototype[key] = constructor.prototype[methods[key]]; } }, afterSetFilter: function() { this._filterUpToDate = false; } }; Kinetic.Validators = { RGBComponent: function(val) { if (val > 255) { return 255; } else if (val < 0) { return 0; } else { return Math.round(val); } }, alphaComponent: function(val) { if (val > 1) { return 1; } // chrome does not honor alpha values of 0 else if (val < 0.0001) { return 0.0001; } else { return val; } } }; })();;(function() { // CONSTANTS var ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransform', BEFORE = 'before', CHANGE = 'Change', CHILDREN = 'children', DOT = '.', EMPTY_STRING = '', GET = 'get', ID = 'id', KINETIC = 'kinetic', LISTENING = 'listening', MOUSEENTER = 'mouseenter', MOUSELEAVE = 'mouseleave', NAME = 'name', SET = 'set', SHAPE = 'Shape', SPACE = ' ', STAGE = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', CLONE_BLACK_LIST = ['id'], TRANSFORM_CHANGE_STR = [ 'xChange.kinetic', 'yChange.kinetic', 'scaleXChange.kinetic', 'scaleYChange.kinetic', 'skewXChange.kinetic', 'skewYChange.kinetic', 'rotationChange.kinetic', 'offsetXChange.kinetic', 'offsetYChange.kinetic', 'transformsEnabledChange.kinetic' ].join(SPACE); Kinetic.Util.addMethods(Kinetic.Node, { _init: function(config) { var that = this; this._id = Kinetic.idCounter++; this.eventListeners = {}; this.attrs = {}; this._cache = {}; this._filterUpToDate = false; this.setAttrs(config); // event bindings for cache handling this.on(TRANSFORM_CHANGE_STR, function() { this._clearCache(TRANSFORM); that._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); }); this.on('visibleChange.kinetic', function() { that._clearSelfAndDescendantCache(VISIBLE); }); this.on('listeningChange.kinetic', function() { that._clearSelfAndDescendantCache(LISTENING); }); this.on('opacityChange.kinetic', function() { that._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); }); }, _clearCache: function(attr){ if (attr) { delete this._cache[attr]; } else { this._cache = {}; } }, _getCache: function(attr, privateGetter){ var cache = this._cache[attr]; // if not cached, we need to set it using the private getter method. if (cache === undefined) { this._cache[attr] = privateGetter.call(this); } return this._cache[attr]; }, /* * when the logic for a cached result depends on ancestor propagation, use this * method to clear self and children cache */ _clearSelfAndDescendantCache: function(attr) { this._clearCache(attr); if (this.children) { this.getChildren().each(function(node) { node._clearSelfAndDescendantCache(attr); }); } }, /** * clear cached canvas * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Node} * @example * node.clearCache(); */ clearCache: function() { delete this._cache.canvas; this._filterUpToDate = false; return this; }, /** * cache node to improve drawing performance, apply filters, or create more accurate * hit regions * @method * @memberof Kinetic.Node.prototype * @param {Object} config * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.drawBorder] when set to true, a red border will be drawn around the cached * region for debugging purposes * @returns {Kinetic.Node} * @example * // cache a shape with the x,y position of the bounding box at the center and<br> * // the width and height of the bounding box equal to the width and height of<br> * // the shape obtained from shape.width() and shape.height()<br> * image.cache();<br><br> * * // cache a node and define the bounding box position and size<br> * node.cache({<br> * x: -30,<br> * y: -30,<br> * width: 100,<br> * height: 200<br> * });<br><br> * * // cache a node and draw a red border around the bounding box<br> * // for debugging purposes<br> * node.cache({<br> * x: -30,<br> * y: -30,<br> * width: 100,<br> * height: 200,<br> * drawBorder: true<br> * }); */ cache: function(config) { var conf = config || {}, x = conf.x || 0, y = conf.y || 0, width = conf.width || this.width(), height = conf.height || this.height(), drawBorder = conf.drawBorder || false, layer = this.getLayer(); if (width === 0 || height === 0) { Kinetic.Util.warn('Width or height of caching configuration equals 0. Cache is ignored.'); return; } var cachedSceneCanvas = new Kinetic.SceneCanvas({ pixelRatio: 1, width: width, height: height }), cachedFilterCanvas = new Kinetic.SceneCanvas({ pixelRatio: 1, width: width, height: height }), cachedHitCanvas = new Kinetic.HitCanvas({ width: width, height: height }), origTransEnabled = this.transformsEnabled(), origX = this.x(), origY = this.y(), sceneContext = cachedSceneCanvas.getContext(), hitContext = cachedHitCanvas.getContext(); this.clearCache(); sceneContext.save(); hitContext.save(); // this will draw a red border around the cached box for // debugging purposes if (drawBorder) { sceneContext.save(); sceneContext.beginPath(); sceneContext.rect(0, 0, width, height); sceneContext.closePath(); sceneContext.setAttr('strokeStyle', 'red'); sceneContext.setAttr('lineWidth', 5); sceneContext.stroke(); sceneContext.restore(); } sceneContext.translate(x * -1, y * -1); hitContext.translate(x * -1, y * -1); if (this.nodeType === 'Shape') { sceneContext.translate(this.x() * -1, this.y() * -1); hitContext.translate(this.x() * -1, this.y() * -1); } this.drawScene(cachedSceneCanvas, this); this.drawHit(cachedHitCanvas, this); sceneContext.restore(); hitContext.restore(); this._cache.canvas = { scene: cachedSceneCanvas, filter: cachedFilterCanvas, hit: cachedHitCanvas }; return this; }, _drawCachedSceneCanvas: function(context) { context.save(); this.getLayer()._applyTransform(this, context); context.drawImage(this._getCachedSceneCanvas()._canvas, 0, 0); context.restore(); }, _getCachedSceneCanvas: function() { var filters = this.filters(), cachedCanvas = this._cache.canvas, sceneCanvas = cachedCanvas.scene, filterCanvas = cachedCanvas.filter, filterContext = filterCanvas.getContext(), len, imageData, n, filter; if (filters) { if (!this._filterUpToDate) { try { len = filters.length; filterContext.clear(); // copy cached canvas onto filter context filterContext.drawImage(sceneCanvas._canvas, 0, 0); imageData = filterContext.getImageData(0, 0, filterCanvas.getWidth(), filterCanvas.getHeight()); // apply filters to filter context for (n=0; n<len; n++) { filter = filters[n]; filter.call(this, imageData); filterContext.putImageData(imageData, 0, 0); } } catch(e) { Kinetic.Util.warn('Unable to apply filter. ' + e.message); } this._filterUpToDate = true; } return filterCanvas; } else { return sceneCanvas; } }, _drawCachedHitCanvas: function(context) { var cachedCanvas = this._cache.canvas, hitCanvas = cachedCanvas.hit; context.save(); this.getLayer()._applyTransform(this, context); context.drawImage(hitCanvas._canvas, 0, 0); context.restore(); }, /** * bind events to the node. KineticJS supports mouseover, mousemove, * mouseout, mouseenter, mouseleave, mousedown, mouseup, click, dblclick, touchstart, touchmove, * touchend, tap, dbltap, dragstart, dragmove, and dragend events. The Kinetic Stage supports * contentMouseover, contentMousemove, contentMouseout, contentMousedown, contentMouseup, * contentClick, contentDblclick, contentTouchstart, contentTouchmove, contentTouchend, contentTap, * and contentDblTap. Pass in a string of events delimmited by a space to bind multiple events at once * such as 'mousedown mouseup mousemove'. Include a namespace to bind an * event by name such as 'click.foobar'. * @method * @memberof Kinetic.Node.prototype * @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo' * @param {Function} handler The handler function is passed an event object * @returns {Kinetic.Node} * @example * // add click listener<br> * node.on('click', function() {<br> * console.log('you clicked me!');<br> * });<br><br> * * // get the target node<br> * node.on('click', function(evt) {<br> * console.log(evt.target);<br> * });<br><br> * * // stop event propagation<br> * node.on('click', function(evt) {<br> * evt.cancelBubble = true;<br> * });<br><br> * * // bind multiple listeners<br> * node.on('click touchstart', function() {<br> * console.log('you clicked/touched me!');<br> * });<br><br> * * // namespace listener<br> * node.on('click.foo', function() {<br> * console.log('you clicked/touched me!');<br> * });<br><br> * * // get the event type<br> * node.on('click tap', function(evt) {<br> * var eventType = evt.type;<br> * });<br><br> * * // get native event object<br> * node.on('click tap', function(evt) {<br> * var nativeEvent = evt.evt;<br> * });<br><br> * * // for change events, get the old and new val<br> * node.on('xChange', function(evt) {<br> * var oldVal = evt.oldVal;<br> * var newVal = evt.newVal;<br> * }); */ on: function(evtStr, handler) { var events = evtStr.split(SPACE), len = events.length, n, event, parts, baseEvent, name; /* * loop through types and attach event listeners to * each one. eg. 'click mouseover.namespace mouseout' * will create three event bindings */ for(n = 0; n < len; n++) { event = events[n]; parts = event.split(DOT); baseEvent = parts[0]; name = parts[1] || EMPTY_STRING; // create events array if it doesn't exist if(!this.eventListeners[baseEvent]) { this.eventListeners[baseEvent] = []; } this.eventListeners[baseEvent].push({ name: name, handler: handler }); // NOTE: this flag is set to true when any event handler is added, even non // mouse or touch gesture events. This improves performance for most // cases where users aren't using events, but is still very light weight. // To ensure perfect accuracy, devs can explicitly set listening to false. /* if (name !== KINETIC) { this._listeningEnabled = true; this._clearSelfAndAncestorCache(LISTENING_ENABLED); } */ } return this; }, /** * remove event bindings from the node. Pass in a string of * event types delimmited by a space to remove multiple event * bindings at once such as 'mousedown mouseup mousemove'. * include a namespace to remove an event binding by name * such as 'click.foobar'. If you only give a name like '.foobar', * all events in that namespace will be removed. * @method * @memberof Kinetic.Node.prototype * @param {String} evtStr e.g. 'click', 'mousedown touchstart', '.foobar' * @returns {Kinetic.Node} * @example * // remove listener<br> * node.off('click');<br><br> * * // remove multiple listeners<br> * node.off('click touchstart');<br><br> * * // remove listener by name<br> * node.off('click.foo'); */ off: function(evtStr) { var events = evtStr.split(SPACE), len = events.length, n, t, event, parts, baseEvent, name; for(n = 0; n < len; n++) { event = events[n]; parts = event.split(DOT); baseEvent = parts[0]; name = parts[1]; if(baseEvent) { if(this.eventListeners[baseEvent]) { this._off(baseEvent, name); } } else { for(t in this.eventListeners) { this._off(t, name); } } } return this; }, // some event aliases for third party integration like HammerJS dispatchEvent: function(evt) { var e = { target: this, type: evt.type, evt: evt }; this.fire(evt.type, e); }, addEventListener: function(type, handler) { // we to pass native event to handler this.on(type, function(evt){ handler.call(this, evt.evt); }); }, /** * remove self from parent, but don't destroy * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Node} * @example * node.remove(); */ remove: function() { var parent = this.getParent(); if(parent && parent.children) { parent.children.splice(this.index, 1); parent._setChildrenIndices(); delete this.parent; } // every cached attr that is calculated via node tree // traversal must be cleared when removing a node this._clearSelfAndDescendantCache(STAGE); this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); this._clearSelfAndDescendantCache(VISIBLE); this._clearSelfAndDescendantCache(LISTENING); this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); return this; }, /** * remove and destroy self * @method * @memberof Kinetic.Node.prototype * @example * node.destroy(); */ destroy: function() { // remove from ids and names hashes Kinetic._removeId(this.getId()); Kinetic._removeName(this.getName(), this._id); this.remove(); }, /** * get attr * @method * @memberof Kinetic.Node.prototype * @param {String} attr * @returns {Integer|String|Object|Array} * @example * var x = node.getAttr('x'); */ getAttr: function(attr) { var method = GET + Kinetic.Util._capitalize(attr); if(Kinetic.Util._isFunction(this[method])) { return this[method](); } // otherwise get directly else { return this.attrs[attr]; } }, /** * get ancestors * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Collection} * @example * shape.getAncestors().each(function(node) { * console.log(node.getId()); * }) */ getAncestors: function() { var parent = this.getParent(), ancestors = new Kinetic.Collection(); while (parent) { ancestors.push(parent); parent = parent.getParent(); } return ancestors; }, /** * get attrs object literal * @method * @memberof Kinetic.Node.prototype * @returns {Object} */ getAttrs: function() { return this.attrs || {}; }, /** * set multiple attrs at once using an object literal * @method * @memberof Kinetic.Node.prototype * @param {Object} config object containing key value pairs * @returns {Kinetic.Node} * @example * node.setAttrs({<br> * x: 5,<br> * fill: 'red'<br> * });<br> */ setAttrs: function(config) { var key, method; if(config) { for(key in config) { if (key === CHILDREN) { } else { method = SET + Kinetic.Util._capitalize(key); // use setter if available if(Kinetic.Util._isFunction(this[method])) { this[method](config[key]); } // otherwise set directly else { this._setAttr(key, config[key]); } } } } return this; }, /** * determine if node is listening for events by taking into account ancestors. * * Parent | Self | isListening * listening | listening | * ----------+-----------+------------ * T | T | T * T | F | F * F | T | T * F | F | F * ----------+-----------+------------ * T | I | T * F | I | F * I | I | T * * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ isListening: function() { return this._getCache(LISTENING, this._isListening); }, _isListening: function() { var listening = this.getListening(), parent = this.getParent(); // the following conditions are a simplification of the truth table above. // please modify carefully if (listening === 'inherit') { if (parent) { return parent.isListening(); } else { return true; } } else { return listening; } }, /** * determine if node is visible by taking into account ancestors. * * Parent | Self | isVisible * visible | visible | * ----------+-----------+------------ * T | T | T * T | F | F * F | T | T * F | F | F * ----------+-----------+------------ * T | I | T * F | I | F * I | I | T * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ isVisible: function() { return this._getCache(VISIBLE, this._isVisible); }, _isVisible: function() { var visible = this.getVisible(), parent = this.getParent(); // the following conditions are a simplification of the truth table above. // please modify carefully if (visible === 'inherit') { if (parent) { return parent.isVisible(); } else { return true; } } else { return visible; } }, /** * determine if listening is enabled by taking into account descendants. If self or any children * have _isListeningEnabled set to true, then self also has listening enabled. * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ shouldDrawHit: function() { var layer = this.getLayer(); return layer && layer.hitGraphEnabled() && this.isListening() && this.isVisible() && !Kinetic.isDragging(); }, /** * show node * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Node} */ show: function() { this.setVisible(true); return this; }, /** * hide node. Hidden nodes are no longer detectable * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Node} */ hide: function() { this.setVisible(false); return this; }, /** * get zIndex relative to the node's siblings who share the same parent * @method * @memberof Kinetic.Node.prototype * @returns {Integer} */ getZIndex: function() { return this.index || 0; }, /** * get absolute z-index which takes into account sibling * and ancestor indices * @method * @memberof Kinetic.Node.prototype * @returns {Integer} */ getAbsoluteZIndex: function() { var depth = this.getDepth(), that = this, index = 0, nodes, len, n, child; function addChildren(children) { nodes = []; len = children.length; for(n = 0; n < len; n++) { child = children[n]; index++; if(child.nodeType !== SHAPE) { nodes = nodes.concat(child.getChildren().toArray()); } if(child._id === that._id) { n = len; } } if(nodes.length > 0 && nodes[0].getDepth() <= depth) { addChildren(nodes); } } if(that.nodeType !== UPPER_STAGE) { addChildren(that.getStage().getChildren()); } return index; }, /** * get node depth in node tree. Returns an integer.<br><br> * e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always * be >= 2 * @method * @memberof Kinetic.Node.prototype * @returns {Integer} */ getDepth: function() { var depth = 0, parent = this.parent; while(parent) { depth++; parent = parent.parent; } return depth; }, setPosition: function(pos) { this.setX(pos.x); this.setY(pos.y); return this; }, getPosition: function() { return { x: this.getX(), y: this.getY() }; }, /** * get absolute position relative to the top left corner of the stage container div * @method * @memberof Kinetic.Node.prototype * @returns {Object} */ getAbsolutePosition: function() { var absoluteMatrix = this.getAbsoluteTransform().getMatrix(), absoluteTransform = new Kinetic.Transform(), offset = this.offset(); // clone the matrix array absoluteTransform.m = absoluteMatrix.slice(); absoluteTransform.translate(offset.x, offset.y); return absoluteTransform.getTranslation(); }, /** * set absolute position * @method * @memberof Kinetic.Node.prototype * @param {Object} pos * @param {Number} pos.x * @param {Number} pos.y * @returns {Kinetic.Node} */ setAbsolutePosition: function(pos) { var origTrans = this._clearTransform(), it; // don't clear translation this.attrs.x = origTrans.x; this.attrs.y = origTrans.y; delete origTrans.x; delete origTrans.y; // unravel transform it = this.getAbsoluteTransform(); it.invert(); it.translate(pos.x, pos.y); pos = { x: this.attrs.x + it.getTranslation().x, y: this.attrs.y + it.getTranslation().y }; this.setPosition({x:pos.x, y:pos.y}); this._setTransform(origTrans); return this; }, _setTransform: function(trans) { var key; for(key in trans) { this.attrs[key] = trans[key]; } this._clearCache(TRANSFORM); this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); }, _clearTransform: function() { var trans = { x: this.getX(), y: this.getY(), rotation: this.getRotation(), scaleX: this.getScaleX(), scaleY: this.getScaleY(), offsetX: this.getOffsetX(), offsetY: this.getOffsetY(), skewX: this.getSkewX(), skewY: this.getSkewY() }; this.attrs.x = 0; this.attrs.y = 0; this.attrs.rotation = 0; this.attrs.scaleX = 1; this.attrs.scaleY = 1; this.attrs.offsetX = 0; this.attrs.offsetY = 0; this.attrs.skewX = 0; this.attrs.skewY = 0; this._clearCache(TRANSFORM); this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); // return original transform return trans; }, /** * move node by an amount relative to its current position * @method * @memberof Kinetic.Node.prototype * @param {Object} change * @param {Number} change.x * @param {Number} change.y * @returns {Kinetic.Node} * @example * // move node in x direction by 1px and y direction by 2px<br> * node.move({<br> * x: 1,<br> * y: 2)<br> * }); */ move: function(change) { var changeX = change.x, changeY = change.y, x = this.getX(), y = this.getY(); if(changeX !== undefined) { x += changeX; } if(changeY !== undefined) { y += changeY; } this.setPosition({x:x, y:y}); return this; }, _eachAncestorReverse: function(func, top) { var family = [], parent = this.getParent(), len, n; // if top node is defined, and this node is top node, // there's no need to build a family tree. just execute // func with this because it will be the only node if (top && top._id === this._id) { func(this); return true; } family.unshift(this); while(parent && (!top || parent._id !== top._id)) { family.unshift(parent); parent = parent.parent; } len = family.length; for(n = 0; n < len; n++) { func(family[n]); } }, /** * rotate node by an amount in degrees relative to its current rotation * @method * @memberof Kinetic.Node.prototype * @param {Number} theta * @returns {Kinetic.Node} */ rotate: function(theta) { this.setRotation(this.getRotation() + theta); return this; }, /** * move node to the top of its siblings * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ moveToTop: function() { if (!this.parent) { Kinetic.Util.warn('Node has no parent. moveToTop function is ignored.'); return; } var index = this.index; this.parent.children.splice(index, 1); this.parent.children.push(this); this.parent._setChildrenIndices(); return true; }, /** * move node up * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ moveUp: function() { if (!this.parent) { Kinetic.Util.warn('Node has no parent. moveUp function is ignored.'); return; } var index = this.index, len = this.parent.getChildren().length; if(index < len - 1) { this.parent.children.splice(index, 1); this.parent.children.splice(index + 1, 0, this); this.parent._setChildrenIndices(); return true; } return false; }, /** * move node down * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ moveDown: function() { if (!this.parent) { Kinetic.Util.warn('Node has no parent. moveDown function is ignored.'); return; } var index = this.index; if(index > 0) { this.parent.children.splice(index, 1); this.parent.children.splice(index - 1, 0, this); this.parent._setChildrenIndices(); return true; } return false; }, /** * move node to the bottom of its siblings * @method * @memberof Kinetic.Node.prototype * @returns {Boolean} */ moveToBottom: function() { if (!this.parent) { Kinetic.Util.warn('Node has no parent. moveToBottom function is ignored.'); return; } var index = this.index; if(index > 0) { this.parent.children.splice(index, 1); this.parent.children.unshift(this); this.parent._setChildrenIndices(); return true; } return false; }, /** * set zIndex relative to siblings * @method * @memberof Kinetic.Node.prototype * @param {Integer} zIndex * @returns {Kinetic.Node} */ setZIndex: function(zIndex) { if (!this.parent) { Kinetic.Util.warn('Node has no parent. zIndex parameter is ignored.'); return; } var index = this.index; this.parent.children.splice(index, 1); this.parent.children.splice(zIndex, 0, this); this.parent._setChildrenIndices(); return this; }, /** * get absolute opacity * @method * @memberof Kinetic.Node.prototype * @returns {Number} */ getAbsoluteOpacity: function() { return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity); }, _getAbsoluteOpacity: function() { var absOpacity = this.getOpacity(); if(this.getParent()) { absOpacity *= this.getParent().getAbsoluteOpacity(); } return absOpacity; }, /** * move node to another container * @method * @memberof Kinetic.Node.prototype * @param {Container} newContainer * @returns {Kinetic.Node} * @example * // move node from current layer into layer2<br> * node.moveTo(layer2); */ moveTo: function(newContainer) { Kinetic.Node.prototype.remove.call(this); newContainer.add(this); return this; }, /** * convert Node into an object for serialization. Returns an object. * @method * @memberof Kinetic.Node.prototype * @returns {Object} */ toObject: function() { var type = Kinetic.Util, obj = {}, attrs = this.getAttrs(), key, val, getter, defaultValue; obj.attrs = {}; // serialize only attributes that are not function, image, DOM, or objects with methods for(key in attrs) { val = attrs[key]; if (!type._isFunction(val) && !type._isElement(val) && !(type._isObject(val) && type._hasMethods(val))) { getter = this[key]; // remove attr value so that we can extract the default value from the getter delete attrs[key]; defaultValue = getter ? getter.call(this) : null; // restore attr value attrs[key] = val; if (defaultValue !== val) { obj.attrs[key] = val; } } } obj.className = this.getClassName(); return obj; }, /** * convert Node into a JSON string. Returns a JSON string. * @method * @memberof Kinetic.Node.prototype * @returns {String}} */ toJSON: function() { return JSON.stringify(this.toObject()); }, /** * get parent container * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Node} */ getParent: function() { return this.parent; }, /** * get layer ancestor * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Layer} */ getLayer: function() { var parent = this.getParent(); return parent ? parent.getLayer() : null; }, /** * get stage ancestor * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Stage} */ getStage: function() { return this._getCache(STAGE, this._getStage); }, _getStage: function() { var parent = this.getParent(); if(parent) { return parent.getStage(); } else { return undefined; } }, /** * fire event * @method * @memberof Kinetic.Node.prototype * @param {String} eventType event type. can be a regular event, like click, mouseover, or mouseout, or it can be a custom event, like myCustomEvent * @param {EventObject} [evt] event object * @param {Boolean} [bubble] setting the value to false, or leaving it undefined, will result in the event * not bubbling. Setting the value to true will result in the event bubbling. * @returns {Kinetic.Node} * @example * // manually fire click event<br> * node.fire('click');<br><br> * * // fire custom event<br> * node.fire('foo');<br><br> * * // fire custom event with custom event object<br> * node.fire('foo', {<br> * bar: 10<br> * });<br><br> * * // fire click event that bubbles<br> * node.fire('click', null, true); */ fire: function(eventType, evt, bubble) { // bubble if (bubble) { this._fireAndBubble(eventType, evt || {}); } // no bubble else { this._fire(eventType, evt || {}); } return this; }, /** * get absolute transform of the node which takes into * account its ancestor transforms * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Transform} */ getAbsoluteTransform: function(top) { // if using an argument, we can't cache the result. if (top) { return this._getAbsoluteTransform(top); } // if no argument, we can cache the result else { return this._getCache(ABSOLUTE_TRANSFORM, this._getAbsoluteTransform); } }, _getAbsoluteTransform: function(top) { var at = new Kinetic.Transform(), transformsEnabled, trans; // start with stage and traverse downwards to self this._eachAncestorReverse(function(node) { transformsEnabled = node.transformsEnabled(); trans = node.getTransform(); if (transformsEnabled === 'all') { at.multiply(trans); } else if (transformsEnabled === 'position') { at.translate(node.x(), node.y()); } }, top); return at; }, /** * get transform of the node * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Transform} */ getTransform: function() { return this._getCache(TRANSFORM, this._getTransform); }, _getTransform: function() { var m = new Kinetic.Transform(), x = this.getX(), y = this.getY(), rotation = Kinetic.getAngle(this.getRotation()), scaleX = this.getScaleX(), scaleY = this.getScaleY(), skewX = this.getSkewX(), skewY = this.getSkewY(), offsetX = this.getOffsetX(), offsetY = this.getOffsetY(); if(x !== 0 || y !== 0) { m.translate(x, y); } if(rotation !== 0) { m.rotate(rotation); } if(skewX !== 0 || skewY !== 0) { m.skew(skewX, skewY); } if(scaleX !== 1 || scaleY !== 1) { m.scale(scaleX, scaleY); } if(offsetX !== 0 || offsetY !== 0) { m.translate(-1 * offsetX, -1 * offsetY); } return m; }, /** * clone node. Returns a new Node instance with identical attributes. You can also override * the node properties with an object literal, enabling you to use an existing node as a template * for another node * @method * @memberof Kinetic.Node.prototype * @param {Object} attrs override attrs * @returns {Kinetic.Node} * @example * // simple clone<br> * var clone = node.clone();<br><br> * * // clone a node and override the x position<br> * var clone = rect.clone({<br> * x: 5<br> * }); */ clone: function(obj) { // instantiate new node var className = this.getClassName(), attrs = Kinetic.Util.cloneObject(this.attrs), key, allListeners, len, n, listener; // filter black attrs for (var i in CLONE_BLACK_LIST) { var blockAttr = CLONE_BLACK_LIST[i]; delete attrs[blockAttr]; } // apply attr overrides for (key in obj) { attrs[key] = obj[key]; } var node = new Kinetic[className](attrs); // copy over listeners for(key in this.eventListeners) { allListeners = this.eventListeners[key]; len = allListeners.length; for(n = 0; n < len; n++) { listener = allListeners[n]; /* * don't include kinetic namespaced listeners because * these are generated by the constructors */ if(listener.name.indexOf(KINETIC) < 0) { // if listeners array doesn't exist, then create it if(!node.eventListeners[key]) { node.eventListeners[key] = []; } node.eventListeners[key].push(listener); } } } return node; }, /** * Creates a composite data URL. If MIME type is not * specified, then "image/png" will result. For "image/jpeg", specify a quality * level as quality (range 0.0 - 1.0) * @method * @memberof Kinetic.Node.prototype * @param {Object} config * @param {String} [config.mimeType] can be "image/png" or "image/jpeg". * "image/png" is the default * @param {Number} [config.x] x position of canvas section * @param {Number} [config.y] y position of canvas section * @param {Number} [config.width] width of canvas section * @param {Number} [config.height] height of canvas section * @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType, * you can specify the quality from 0 to 1, where 0 is very poor quality and 1 * is very high quality * @returns {String} */ toDataURL: function(config) { config = config || {}; var mimeType = config.mimeType || null, quality = config.quality || null, stage = this.getStage(), x = config.x || 0, y = config.y || 0, canvas = new Kinetic.SceneCanvas({ width: config.width || this.getWidth() || (stage ? stage.getWidth() : 0), height: config.height || this.getHeight() || (stage ? stage.getHeight() : 0), pixelRatio: 1 }), context = canvas.getContext(); context.save(); if(x || y) { context.translate(-1 * x, -1 * y); } this.drawScene(canvas); context.restore(); return canvas.toDataURL(mimeType, quality); }, /** * converts node into an image. Since the toImage * method is asynchronous, a callback is required. toImage is most commonly used * to cache complex drawings as an image so that they don't have to constantly be redrawn * @method * @memberof Kinetic.Node.prototype * @param {Object} config * @param {Function} config.callback function executed when the composite has completed * @param {String} [config.mimeType] can be "image/png" or "image/jpeg". * "image/png" is the default * @param {Number} [config.x] x position of canvas section * @param {Number} [config.y] y position of canvas section * @param {Number} [config.width] width of canvas section * @param {Number} [config.height] height of canvas section * @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType, * you can specify the quality from 0 to 1, where 0 is very poor quality and 1 * is very high quality * @example * var image = node.toImage({<br> * callback: function(img) {<br> * // do stuff with img<br> * }<br> * }); */ toImage: function(config) { Kinetic.Util._getImage(this.toDataURL(config), function(img) { config.callback(img); }); }, setSize: function(size) { this.setWidth(size.width); this.setHeight(size.height); return this; }, getSize: function() { return { width: this.getWidth(), height: this.getHeight() }; }, /** * get width * @method * @memberof Kinetic.Node.prototype * @returns {Integer} */ getWidth: function() { return this.attrs.width || 0; }, /** * get height * @method * @memberof Kinetic.Node.prototype * @returns {Integer} */ getHeight: function() { return this.attrs.height || 0; }, /** * get class name, which may return Stage, Layer, Group, or shape class names like Rect, Circle, Text, etc. * @method * @memberof Kinetic.Node.prototype * @returns {String} */ getClassName: function() { return this.className || this.nodeType; }, /** * get the node type, which may return Stage, Layer, Group, or Node * @method * @memberof Kinetic.Node.prototype * @returns {String} */ getType: function() { return this.nodeType; }, getDragDistance: function() { // compare with undefined because we need to track 0 value if (this.attrs.dragDistance !== undefined) { return this.attrs.dragDistance; } else if (this.parent) { return this.parent.getDragDistance(); } else { return Kinetic.dragDistance; } }, _get: function(selector) { return this.nodeType === selector ? [this] : []; }, _off: function(type, name) { var evtListeners = this.eventListeners[type], i, evtName; for(i = 0; i < evtListeners.length; i++) { evtName = evtListeners[i].name; // the following two conditions must be true in order to remove a handler: // 1) the current event name cannot be kinetic unless the event name is kinetic // this enables developers to force remove a kinetic specific listener for whatever reason // 2) an event name is not specified, or if one is specified, it matches the current event name if((evtName !== 'kinetic' || name === 'kinetic') && (!name || evtName === name)) { evtListeners.splice(i, 1); if(evtListeners.length === 0) { delete this.eventListeners[type]; break; } i--; } } }, _fireChangeEvent: function(attr, oldVal, newVal) { this._fire(attr + CHANGE, { oldVal: oldVal, newVal: newVal }); }, /** * set id * @method * @memberof Kinetic.Node.prototype * @param {String} id * @returns {Kinetic.Node} */ setId: function(id) { var oldId = this.getId(); Kinetic._removeId(oldId); Kinetic._addId(this, id); this._setAttr(ID, id); return this; }, setName: function(name) { var oldName = this.getName(); Kinetic._removeName(oldName, this._id); Kinetic._addName(this, name); this._setAttr(NAME, name); return this; }, /** * set attr * @method * @memberof Kinetic.Node.prototype * @param {String} attr * @param {*} val * @returns {Kinetic.Node} * @example * node.setAttr('x', 5); */ setAttr: function() { var args = Array.prototype.slice.call(arguments), attr = args[0], val = args[1], method = SET + Kinetic.Util._capitalize(attr), func = this[method]; if(Kinetic.Util._isFunction(func)) { func.call(this, val); } // otherwise set directly else { this._setAttr(attr, val); } return this; }, _setAttr: function(key, val) { var oldVal; if(val !== undefined) { oldVal = this.attrs[key]; this.attrs[key] = val; this._fireChangeEvent(key, oldVal, val); } }, _setComponentAttr: function(key, component, val) { var oldVal; if(val !== undefined) { oldVal = this.attrs[key]; if (!oldVal) { // set value to default value using getAttr this.attrs[key] = this.getAttr(key); } this.attrs[key][component] = val; this._fireChangeEvent(key, oldVal, val); } }, _fireAndBubble: function(eventType, evt, compareShape) { var okayToRun = true; if(evt && this.nodeType === SHAPE) { evt.target = this; } if(eventType === MOUSEENTER && compareShape && this._id === compareShape._id) { okayToRun = false; } else if(eventType === MOUSELEAVE && compareShape && this._id === compareShape._id) { okayToRun = false; } if(okayToRun) { this._fire(eventType, evt); // simulate event bubbling if(evt && !evt.cancelBubble && this.parent) { if(compareShape && compareShape.parent) { this._fireAndBubble.call(this.parent, eventType, evt, compareShape.parent); } else { this._fireAndBubble.call(this.parent, eventType, evt); } } } }, _fire: function(eventType, evt) { var events = this.eventListeners[eventType], i; evt.type = eventType; if (events) { for(i = 0; i < events.length; i++) { events[i].handler.call(this, evt); } } }, /** * draw both scene and hit graphs. If the node being drawn is the stage, all of the layers will be cleared and redrawn * @method * @memberof Kinetic.Node.prototype * @returns {Kinetic.Node} */ draw: function() { this.drawScene(); this.drawHit(); return this; } }); /** * create node with JSON string. De-serializtion does not generate custom * shape drawing functions, images, or event handlers (this would make the * serialized object huge). If your app uses custom shapes, images, and * event handlers (it probably does), then you need to select the appropriate * shapes after loading the stage and set these properties via on(), setDrawFunc(), * and setImage() methods * @method * @memberof Kinetic.Node * @param {String} JSON string * @param {DomElement} [container] optional container dom element used only if you're * creating a stage node */ Kinetic.Node.create = function(json, container) { return this._createNode(JSON.parse(json), container); }; Kinetic.Node._createNode = function(obj, container) { var className = Kinetic.Node.prototype.getClassName.call(obj), children = obj.children, no, len, n; // if container was passed in, add it to attrs if(container) { obj.attrs.container = container; } no = new Kinetic[className](obj.attrs); if(children) { len = children.length; for(n = 0; n < len; n++) { no.add(this._createNode(children[n])); } } return no; }; // =========================== add getters setters =========================== Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'position'); /** * get/set node position relative to parent * @name position * @method * @memberof Kinetic.Node.prototype * @param {Object} pos * @param {Number} pos.x * @param {Nubmer} pos.y * @returns {Object} * @example * // get position<br> * var position = node.position();<br><br> * * // set position<br> * node.position({<br> * x: 5<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'x', 0); /** * get/set x position * @name x * @method * @memberof Kinetic.Node.prototype * @param {Number} x * @returns {Object} * @example * // get x<br> * var x = node.x();<br><br> * * // set x<br> * node.x(5); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'y', 0); /** * get/set y position * @name y * @method * @memberof Kinetic.Node.prototype * @param {Number} y * @returns {Integer} * @example * // get y<br> * var y = node.y();<br><br> * * // set y<br> * node.y(5); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'opacity', 1); /** * get/set opacity. Opacity values range from 0 to 1. * A node with an opacity of 0 is fully transparent, and a node * with an opacity of 1 is fully opaque * @name opacity * @method * @memberof Kinetic.Node.prototype * @param {Object} opacity * @returns {Number} * @example * // get opacity<br> * var opacity = node.opacity();<br><br> * * // set opacity<br> * node.opacity(0.5); */ Kinetic.Factory.addGetter(Kinetic.Node, 'name'); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'name'); /** * get/set name * @name name * @method * @memberof Kinetic.Node.prototype * @param {String} name * @returns {String} * @example * // get name<br> * var name = node.name();<br><br> * * // set name<br> * node.name('foo'); */ Kinetic.Factory.addGetter(Kinetic.Node, 'id'); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'id'); /** * get/set id * @name id * @method * @memberof Kinetic.Node.prototype * @param {String} id * @returns {String} * @example * // get id<br> * var name = node.id();<br><br> * * // set id<br> * node.id('foo'); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'rotation', 0); /** * get/set rotation in degrees * @name rotation * @method * @memberof Kinetic.Node.prototype * @param {Number} rotation * @returns {Number} * @example * // get rotation in degrees<br> * var rotation = node.rotation();<br><br> * * // set rotation in degrees<br> * node.rotation(45); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'scale', ['x', 'y']); /** * get/set scale * @name scale * @param {Object} scale * @param {Number} scale.x * @param {Number} scale.y * @method * @memberof Kinetic.Node.prototype * @returns {Object} * @example * // get scale<br> * var scale = node.scale();<br><br> * * // set scale <br> * shape.scale({<br> * x: 2<br> * y: 3<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'scaleX', 1); /** * get/set scale x * @name scaleX * @param {Number} x * @method * @memberof Kinetic.Node.prototype * @returns {Number} * @example * // get scale x<br> * var scaleX = node.scaleX();<br><br> * * // set scale x<br> * node.scaleX(2); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'scaleY', 1); /** * get/set scale y * @name scaleY * @param {Number} y * @method * @memberof Kinetic.Node.prototype * @returns {Number} * @example * // get scale y<br> * var scaleY = node.scaleY();<br><br> * * // set scale y<br> * node.scaleY(2); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'skew', ['x', 'y']); /** * get/set skew * @name skew * @param {Object} skew * @param {Number} skew.x * @param {Number} skew.y * @method * @memberof Kinetic.Node.prototype * @returns {Object} * @example * // get skew<br> * var skew = node.skew();<br><br> * * // set skew <br> * node.skew({<br> * x: 20<br> * y: 10 * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'skewX', 0); /** * get/set skew x * @name skewX * @param {Number} x * @method * @memberof Kinetic.Node.prototype * @returns {Number} * @example * // get skew x<br> * var skewX = node.skewX();<br><br> * * // set skew x<br> * node.skewX(3); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'skewY', 0); /** * get/set skew y * @name skewY * @param {Number} y * @method * @memberof Kinetic.Node.prototype * @returns {Number} * @example * // get skew y<br> * var skewY = node.skewY();<br><br> * * // set skew y<br> * node.skewY(3); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Node, 'offset', ['x', 'y']); /** * get/set offset. Offsets the default position and rotation point * @method * @memberof Kinetic.Node.prototype * @param {Object} offset * @param {Number} offset.x * @param {Number} offset.y * @returns {Object} * @example * // get offset<br> * var offset = node.offset();<br><br> * * // set offset<br> * node.offset({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'offsetX', 0); /** * get/set offset x * @name offsetX * @memberof Kinetic.Node.prototype * @param {Number} x * @returns {Number} * @example * // get offset x<br> * var offsetX = node.offsetX();<br><br> * * // set offset x<br> * node.offsetX(3); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'offsetY', 0); /** * get/set drag distance * @name dragDistance * @memberof Kinetic.Node.prototype * @param {Number} distance * @returns {Number} * @example * // get drag distance<br> * var dragDistance = node.dragDistance();<br><br> * * // set distance<br> * // node starts dragging only if pointer moved more then 3 pixels<br> * node.dragDistance(3);<br> * // or set globally<br> * Kinetic.dragDistance = 3; */ Kinetic.Factory.addSetter(Kinetic.Node, 'dragDistance'); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'dragDistance'); /** * get/set offset y * @name offsetY * @method * @memberof Kinetic.Node.prototype * @param {Number} y * @returns {Number} * @example * // get offset y<br> * var offsetY = node.offsetY();<br><br> * * // set offset y<br> * node.offsetY(3); */ Kinetic.Factory.addSetter(Kinetic.Node, 'width', 0); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'width'); /** * get/set width * @name width * @method * @memberof Kinetic.Node.prototype * @param {Number} width * @returns {Number} * @example * // get width<br> * var width = node.width();<br><br> * * // set width<br> * node.width(100); */ Kinetic.Factory.addSetter(Kinetic.Node, 'height', 0); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'height'); /** * get/set height * @name height * @method * @memberof Kinetic.Node.prototype * @param {Number} height * @returns {Number} * @example * // get height<br> * var height = node.height();<br><br> * * // set height<br> * node.height(100); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'listening', 'inherit'); /** * get/set listenig attr. If you need to determine if a node is listening or not * by taking into account its parents, use the isListening() method * @name listening * @method * @memberof Kinetic.Node.prototype * @param {Boolean|String} listening Can be "inherit", true, or false. The default is "inherit". * @returns {Boolean|String} * @example * // get listening attr<br> * var listening = node.listening();<br><br> * * // stop listening for events<br> * node.listening(false);<br><br> * * // listen for events<br> * node.listening(true);<br><br> * * // listen to events according to the parent<br> * node.listening('inherit'); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'filters', undefined, function(val) {this._filterUpToDate = false;return val;}); /** * get/set filters. Filters are applied to cached canvases * @name filters * @method * @memberof Kinetic.Node.prototype * @param {Array} filters array of filters * @returns {Array} * @example * // get filters<br> * var filters = node.filters();<br><br> * * // set a single filter<br> * node.cache();<br> * node.filters([Kinetic.Filters.Blur]);<br><br> * * // set multiple filters<br> * node.cache();<br> * node.filters([<br> * Kinetic.Filters.Blur,<br> * Kinetic.Filters.Sepia,<br> * Kinetic.Filters.Invert<br> * ]); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'visible', 'inherit'); /** * get/set visible attr. Can be "inherit", true, or false. The default is "inherit". * If you need to determine if a node is visible or not * by taking into account its parents, use the isVisible() method * @name visible * @method * @memberof Kinetic.Node.prototype * @param {Boolean|String} visible * @returns {Boolean|String} * @example * // get visible attr<br> * var visible = node.visible();<br><br> * * // make invisible<br> * node.visible(false);<br><br> * * // make visible<br> * node.visible(true);<br><br> * * // make visible according to the parent<br> * node.visible('inherit'); */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'transformsEnabled', 'all'); /** * get/set transforms that are enabled. Can be "all", "none", or "position". The default * is "all" * @name transformsEnabled * @method * @memberof Kinetic.Node.prototype * @param {String} enabled * @returns {String} * @example * // enable position transform only to improve draw performance<br> * node.transformsEnabled('position');<br><br> * * // enable all transforms<br> * node.transformsEnabled('all'); */ /** * get/set node size * @name size * @method * @memberof Kinetic.Node.prototype * @param {Object} size * @param {Number} size.width * @param {Number} size.height * @returns {Object} * @example * // get node size<br> * var size = node.size();<br> * var x = size.x;<br> * var y = size.y;<br><br> * * // set size<br> * node.size({<br> * width: 100,<br> * height: 200<br> * }); */ Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'size'); Kinetic.Factory.backCompat(Kinetic.Node, { rotateDeg: 'rotate', setRotationDeg: 'setRotation', getRotationDeg: 'getRotation' }); Kinetic.Collection.mapMethods(Kinetic.Node); })(); ;(function() { /** * Grayscale Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData */ Kinetic.Filters.Grayscale = function(imageData) { var data = imageData.data, len = data.length, i, brightness; for(i = 0; i < len; i += 4) { brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; // red data[i] = brightness; // green data[i + 1] = brightness; // blue data[i + 2] = brightness; } }; })(); ;(function() { /** * Brighten Filter. * @function * @memberof Kinetic.Filters * @param {Object} imageData */ Kinetic.Filters.Brighten = function(imageData) { var brightness = this.brightness() * 255, data = imageData.data, len = data.length, i; for(i = 0; i < len; i += 4) { // red data[i] += brightness; // green data[i + 1] += brightness; // blue data[i + 2] += brightness; } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'brightness', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set filter brightness. The brightness is a number between -1 and 1.&nbsp; Positive values * brighten the pixels and negative values darken them. * @name brightness * @method * @memberof Kinetic.Image.prototype * @param {Number} brightness value between -1 and 1 * @returns {Number} */ })(); ;(function() { /** * Invert Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData */ Kinetic.Filters.Invert = function(imageData) { var data = imageData.data, len = data.length, i; for(i = 0; i < len; i += 4) { // red data[i] = 255 - data[i]; // green data[i + 1] = 255 - data[i + 1]; // blue data[i + 2] = 255 - data[i + 2]; } }; })();;/* the Gauss filter master repo: https://github.com/pavelpower/kineticjsGaussFilter/ */ (function() { /* StackBlur - a fast almost Gaussian Blur For Canvas Version: 0.5 Author: Mario Klingemann Contact: [email protected] Website: http://www.quasimondo.com/StackBlurForCanvas Twitter: @quasimondo In case you find this class useful - especially in commercial projects - I am not totally unhappy for a small donation to my PayPal account [email protected] Or support me on flattr: https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript Copyright (c) 2010 Mario Klingemann 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. */ function BlurStack() { this.r = 0; this.g = 0; this.b = 0; this.a = 0; this.next = null; } var mul_table = [ 512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512, 454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512, 482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456, 437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512, 497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328, 320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456, 446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335, 329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512, 505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405, 399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328, 324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271, 268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456, 451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388, 385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335, 332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292, 289,287,285,282,280,278,275,273,271,269,267,265,263,261,259 ]; var shg_table = [ 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 ]; function filterGaussBlurRGBA( imageData, radius) { var pixels = imageData.data, width = imageData.width, height = imageData.height; var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum, a_sum, r_out_sum, g_out_sum, b_out_sum, a_out_sum, r_in_sum, g_in_sum, b_in_sum, a_in_sum, pr, pg, pb, pa, rbs; var div = radius + radius + 1, widthMinus1 = width - 1, heightMinus1 = height - 1, radiusPlus1 = radius + 1, sumFactor = radiusPlus1 * ( radiusPlus1 + 1 ) / 2, stackStart = new BlurStack(), stackEnd = null, stack = stackStart, stackIn = null, stackOut = null, mul_sum = mul_table[radius], shg_sum = shg_table[radius]; for ( i = 1; i < div; i++ ) { stack = stack.next = new BlurStack(); if ( i == radiusPlus1 ){ stackEnd = stack; } } stack.next = stackStart; yw = yi = 0; for ( y = 0; y < height; y++ ) { r_in_sum = g_in_sum = b_in_sum = a_in_sum = r_sum = g_sum = b_sum = a_sum = 0; r_out_sum = radiusPlus1 * ( pr = pixels[yi] ); g_out_sum = radiusPlus1 * ( pg = pixels[yi+1] ); b_out_sum = radiusPlus1 * ( pb = pixels[yi+2] ); a_out_sum = radiusPlus1 * ( pa = pixels[yi+3] ); r_sum += sumFactor * pr; g_sum += sumFactor * pg; b_sum += sumFactor * pb; a_sum += sumFactor * pa; stack = stackStart; for( i = 0; i < radiusPlus1; i++ ) { stack.r = pr; stack.g = pg; stack.b = pb; stack.a = pa; stack = stack.next; } for( i = 1; i < radiusPlus1; i++ ) { p = yi + (( widthMinus1 < i ? widthMinus1 : i ) << 2 ); r_sum += ( stack.r = ( pr = pixels[p])) * ( rbs = radiusPlus1 - i ); g_sum += ( stack.g = ( pg = pixels[p+1])) * rbs; b_sum += ( stack.b = ( pb = pixels[p+2])) * rbs; a_sum += ( stack.a = ( pa = pixels[p+3])) * rbs; r_in_sum += pr; g_in_sum += pg; b_in_sum += pb; a_in_sum += pa; stack = stack.next; } stackIn = stackStart; stackOut = stackEnd; for ( x = 0; x < width; x++ ) { pixels[yi+3] = pa = (a_sum * mul_sum) >> shg_sum; if ( pa !== 0 ) { pa = 255 / pa; pixels[yi] = ((r_sum * mul_sum) >> shg_sum) * pa; pixels[yi+1] = ((g_sum * mul_sum) >> shg_sum) * pa; pixels[yi+2] = ((b_sum * mul_sum) >> shg_sum) * pa; } else { pixels[yi] = pixels[yi+1] = pixels[yi+2] = 0; } r_sum -= r_out_sum; g_sum -= g_out_sum; b_sum -= b_out_sum; a_sum -= a_out_sum; r_out_sum -= stackIn.r; g_out_sum -= stackIn.g; b_out_sum -= stackIn.b; a_out_sum -= stackIn.a; p = ( yw + ( ( p = x + radius + 1 ) < widthMinus1 ? p : widthMinus1 ) ) << 2; r_in_sum += ( stackIn.r = pixels[p]); g_in_sum += ( stackIn.g = pixels[p+1]); b_in_sum += ( stackIn.b = pixels[p+2]); a_in_sum += ( stackIn.a = pixels[p+3]); r_sum += r_in_sum; g_sum += g_in_sum; b_sum += b_in_sum; a_sum += a_in_sum; stackIn = stackIn.next; r_out_sum += ( pr = stackOut.r ); g_out_sum += ( pg = stackOut.g ); b_out_sum += ( pb = stackOut.b ); a_out_sum += ( pa = stackOut.a ); r_in_sum -= pr; g_in_sum -= pg; b_in_sum -= pb; a_in_sum -= pa; stackOut = stackOut.next; yi += 4; } yw += width; } for ( x = 0; x < width; x++ ) { g_in_sum = b_in_sum = a_in_sum = r_in_sum = g_sum = b_sum = a_sum = r_sum = 0; yi = x << 2; r_out_sum = radiusPlus1 * ( pr = pixels[yi]); g_out_sum = radiusPlus1 * ( pg = pixels[yi+1]); b_out_sum = radiusPlus1 * ( pb = pixels[yi+2]); a_out_sum = radiusPlus1 * ( pa = pixels[yi+3]); r_sum += sumFactor * pr; g_sum += sumFactor * pg; b_sum += sumFactor * pb; a_sum += sumFactor * pa; stack = stackStart; for( i = 0; i < radiusPlus1; i++ ) { stack.r = pr; stack.g = pg; stack.b = pb; stack.a = pa; stack = stack.next; } yp = width; for( i = 1; i <= radius; i++ ) { yi = ( yp + x ) << 2; r_sum += ( stack.r = ( pr = pixels[yi])) * ( rbs = radiusPlus1 - i ); g_sum += ( stack.g = ( pg = pixels[yi+1])) * rbs; b_sum += ( stack.b = ( pb = pixels[yi+2])) * rbs; a_sum += ( stack.a = ( pa = pixels[yi+3])) * rbs; r_in_sum += pr; g_in_sum += pg; b_in_sum += pb; a_in_sum += pa; stack = stack.next; if( i < heightMinus1 ) { yp += width; } } yi = x; stackIn = stackStart; stackOut = stackEnd; for ( y = 0; y < height; y++ ) { p = yi << 2; pixels[p+3] = pa = (a_sum * mul_sum) >> shg_sum; if ( pa > 0 ) { pa = 255 / pa; pixels[p] = ((r_sum * mul_sum) >> shg_sum ) * pa; pixels[p+1] = ((g_sum * mul_sum) >> shg_sum ) * pa; pixels[p+2] = ((b_sum * mul_sum) >> shg_sum ) * pa; } else { pixels[p] = pixels[p+1] = pixels[p+2] = 0; } r_sum -= r_out_sum; g_sum -= g_out_sum; b_sum -= b_out_sum; a_sum -= a_out_sum; r_out_sum -= stackIn.r; g_out_sum -= stackIn.g; b_out_sum -= stackIn.b; a_out_sum -= stackIn.a; p = ( x + (( ( p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1 ) * width )) << 2; r_sum += ( r_in_sum += ( stackIn.r = pixels[p])); g_sum += ( g_in_sum += ( stackIn.g = pixels[p+1])); b_sum += ( b_in_sum += ( stackIn.b = pixels[p+2])); a_sum += ( a_in_sum += ( stackIn.a = pixels[p+3])); stackIn = stackIn.next; r_out_sum += ( pr = stackOut.r ); g_out_sum += ( pg = stackOut.g ); b_out_sum += ( pb = stackOut.b ); a_out_sum += ( pa = stackOut.a ); r_in_sum -= pr; g_in_sum -= pg; b_in_sum -= pb; a_in_sum -= pa; stackOut = stackOut.next; yi += width; } } } /** * Blur Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData */ Kinetic.Filters.Blur = function(imageData) { var radius = Math.round(this.blurRadius()); if (radius > 0) { filterGaussBlurRGBA(imageData, radius); } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'blurRadius', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set blur radius * @name blurRadius * @method * @memberof Kinetic.Node.prototype * @param {Integer} radius * @returns {Integer} */ })();;(function() { function pixelAt(idata, x, y) { var idx = (y * idata.width + x) * 4; var d = []; d.push(idata.data[idx++], idata.data[idx++], idata.data[idx++], idata.data[idx++]); return d; } function rgbDistance(p1, p2) { return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2) + Math.pow(p1[2] - p2[2], 2)); } function rgbMean(pTab) { var m = [0, 0, 0]; for (var i = 0; i < pTab.length; i++) { m[0] += pTab[i][0]; m[1] += pTab[i][1]; m[2] += pTab[i][2]; } m[0] /= pTab.length; m[1] /= pTab.length; m[2] /= pTab.length; return m; } function backgroundMask(idata, threshold) { var rgbv_no = pixelAt(idata, 0, 0); var rgbv_ne = pixelAt(idata, idata.width - 1, 0); var rgbv_so = pixelAt(idata, 0, idata.height - 1); var rgbv_se = pixelAt(idata, idata.width - 1, idata.height - 1); var thres = threshold || 10; if (rgbDistance(rgbv_no, rgbv_ne) < thres && rgbDistance(rgbv_ne, rgbv_se) < thres && rgbDistance(rgbv_se, rgbv_so) < thres && rgbDistance(rgbv_so, rgbv_no) < thres) { // Mean color var mean = rgbMean([rgbv_ne, rgbv_no, rgbv_se, rgbv_so]); // Mask based on color distance var mask = []; for (var i = 0; i < idata.width * idata.height; i++) { var d = rgbDistance(mean, [idata.data[i * 4], idata.data[i * 4 + 1], idata.data[i * 4 + 2]]); mask[i] = (d < thres) ? 0 : 255; } return mask; } } function applyMask(idata, mask) { for (var i = 0; i < idata.width * idata.height; i++) { idata.data[4 * i + 3] = mask[i]; } } function erodeMask(mask, sw, sh) { var weights = [1, 1, 1, 1, 0, 1, 1, 1, 1]; var side = Math.round(Math.sqrt(weights.length)); var halfSide = Math.floor(side / 2); var maskResult = []; for (var y = 0; y < sh; y++) { for (var x = 0; x < sw; x++) { var so = y * sw + x; var a = 0; for (var cy = 0; cy < side; cy++) { for (var cx = 0; cx < side; cx++) { var scy = y + cy - halfSide; var scx = x + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { var srcOff = scy * sw + scx; var wt = weights[cy * side + cx]; a += mask[srcOff] * wt; } } } maskResult[so] = (a === 255 * 8) ? 255 : 0; } } return maskResult; } function dilateMask(mask, sw, sh) { var weights = [1, 1, 1, 1, 1, 1, 1, 1, 1]; var side = Math.round(Math.sqrt(weights.length)); var halfSide = Math.floor(side / 2); var maskResult = []; for (var y = 0; y < sh; y++) { for (var x = 0; x < sw; x++) { var so = y * sw + x; var a = 0; for (var cy = 0; cy < side; cy++) { for (var cx = 0; cx < side; cx++) { var scy = y + cy - halfSide; var scx = x + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { var srcOff = scy * sw + scx; var wt = weights[cy * side + cx]; a += mask[srcOff] * wt; } } } maskResult[so] = (a >= 255 * 4) ? 255 : 0; } } return maskResult; } function smoothEdgeMask(mask, sw, sh) { var weights = [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]; var side = Math.round(Math.sqrt(weights.length)); var halfSide = Math.floor(side / 2); var maskResult = []; for (var y = 0; y < sh; y++) { for (var x = 0; x < sw; x++) { var so = y * sw + x; var a = 0; for (var cy = 0; cy < side; cy++) { for (var cx = 0; cx < side; cx++) { var scy = y + cy - halfSide; var scx = x + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { var srcOff = scy * sw + scx; var wt = weights[cy * side + cx]; a += mask[srcOff] * wt; } } } maskResult[so] = a; } } return maskResult; } /** * Mask Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData */ Kinetic.Filters.Mask = function(imageData) { // Detect pixels close to the background color var threshold = this.threshold(), mask = backgroundMask(imageData, threshold); if (mask) { // Erode mask = erodeMask(mask, imageData.width, imageData.height); // Dilate mask = dilateMask(mask, imageData.width, imageData.height); // Gradient mask = smoothEdgeMask(mask, imageData.width, imageData.height); // Apply mask applyMask(imageData, mask); // todo : Update hit region function according to mask } return imageData; }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0, null, Kinetic.Factory.afterSetFilter); })(); ;(function () { /** * RGB Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author ippo615 */ Kinetic.Filters.RGB = function (imageData) { var data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), blue = this.blue(), i, brightness; for (i = 0; i < nPixels; i += 4) { brightness = (0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2])/255; data[i ] = brightness*red; // r data[i + 1] = brightness*green; // g data[i + 2] = brightness*blue; // b data[i + 3] = data[i + 3]; // alpha } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'red', 0, function(val) { this._filterUpToDate = false; if (val > 255) { return 255; } else if (val < 0) { return 0; } else { return Math.round(val); } }); /** * get/set filter red value * @name red * @method * @memberof Kinetic.Node.prototype * @param {Integer} red value between 0 and 255 * @returns {Integer} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'green', 0, function(val) { this._filterUpToDate = false; if (val > 255) { return 255; } else if (val < 0) { return 0; } else { return Math.round(val); } }); /** * get/set filter green value * @name green * @method * @memberof Kinetic.Node.prototype * @param {Integer} green value between 0 and 255 * @returns {Integer} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'blue', 0, Kinetic.Validators.RGBComponent, Kinetic.Factory.afterSetFilter); /** * get/set filter blue value * @name blue * @method * @memberof Kinetic.Node.prototype * @param {Integer} blue value between 0 and 255 * @returns {Integer} */ })(); ;(function () { /** * HSV Filter. Adjusts the hue, saturation and value * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author ippo615 */ Kinetic.Filters.HSV = function (imageData) { var data = imageData.data, nPixels = data.length, v = Math.pow(2,this.value()), s = Math.pow(2,this.saturation()), h = Math.abs((this.hue()) + 360) % 360, i; // Basis for the technique used: // http://beesbuzz.biz/code/hsv_color_transforms.php // V is the value multiplier (1 for none, 2 for double, 0.5 for half) // S is the saturation multiplier (1 for none, 2 for double, 0.5 for half) // H is the hue shift in degrees (0 to 360) // vsu = V*S*cos(H*PI/180); // vsw = V*S*sin(H*PI/180); //[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R] //[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G] //[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B] // Precompute the values in the matrix: var vsu = v*s*Math.cos(h*Math.PI/180), vsw = v*s*Math.sin(h*Math.PI/180); // (result spot)(source spot) var rr = 0.299*v+0.701*vsu+0.167*vsw, rg = 0.587*v-0.587*vsu+0.330*vsw, rb = 0.114*v-0.114*vsu-0.497*vsw; var gr = 0.299*v-0.299*vsu-0.328*vsw, gg = 0.587*v+0.413*vsu+0.035*vsw, gb = 0.114*v-0.114*vsu+0.293*vsw; var br = 0.299*v-0.300*vsu+1.250*vsw, bg = 0.587*v-0.586*vsu-1.050*vsw, bb = 0.114*v+0.886*vsu-0.200*vsw; var r,g,b,a; for (i = 0; i < nPixels; i += 4) { r = data[i+0]; g = data[i+1]; b = data[i+2]; a = data[i+3]; data[i+0] = rr*r + rg*g + rb*b; data[i+1] = gr*r + gg*g + gb*b; data[i+2] = br*r + bg*g + bb*b; data[i+3] = a; // alpha } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'hue', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set hsv hue in degrees * @name hue * @method * @memberof Kinetic.Node.prototype * @param {Number} hue value between 0 and 359 * @returns {Number} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'saturation', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set hsv saturation * @name saturation * @method * @memberof Kinetic.Node.prototype * @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc.. * @returns {Number} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'value', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set hsv value * @name value * @method * @memberof Kinetic.Node.prototype * @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc.. * @returns {Number} */ })(); ;(function () { Kinetic.Factory.addGetterSetter(Kinetic.Node, 'hue', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set hsv hue in degrees * @name hue * @method * @memberof Kinetic.Node.prototype * @param {Number} hue value between 0 and 359 * @returns {Number} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'saturation', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set hsv saturation * @name saturation * @method * @memberof Kinetic.Node.prototype * @param {Number} saturation 0 is no change, -1.0 halves the saturation, 1.0 doubles, etc.. * @returns {Number} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'luminance', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set hsl luminance * @name value * @method * @memberof Kinetic.Node.prototype * @param {Number} value 0 is no change, -1.0 halves the value, 1.0 doubles, etc.. * @returns {Number} */ /** * HSL Filter. Adjusts the hue, saturation and luminance (or lightness) * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author ippo615 */ Kinetic.Filters.HSL = function (imageData) { var data = imageData.data, nPixels = data.length, v = 1, s = Math.pow(2,this.saturation()), h = Math.abs((this.hue()) + 360) % 360, l = this.luminance()*127, i; // Basis for the technique used: // http://beesbuzz.biz/code/hsv_color_transforms.php // V is the value multiplier (1 for none, 2 for double, 0.5 for half) // S is the saturation multiplier (1 for none, 2 for double, 0.5 for half) // H is the hue shift in degrees (0 to 360) // vsu = V*S*cos(H*PI/180); // vsw = V*S*sin(H*PI/180); //[ .299V+.701vsu+.168vsw .587V-.587vsu+.330vsw .114V-.114vsu-.497vsw ] [R] //[ .299V-.299vsu-.328vsw .587V+.413vsu+.035vsw .114V-.114vsu+.292vsw ]*[G] //[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B] // Precompute the values in the matrix: var vsu = v*s*Math.cos(h*Math.PI/180), vsw = v*s*Math.sin(h*Math.PI/180); // (result spot)(source spot) var rr = 0.299*v+0.701*vsu+0.167*vsw, rg = 0.587*v-0.587*vsu+0.330*vsw, rb = 0.114*v-0.114*vsu-0.497*vsw; var gr = 0.299*v-0.299*vsu-0.328*vsw, gg = 0.587*v+0.413*vsu+0.035*vsw, gb = 0.114*v-0.114*vsu+0.293*vsw; var br = 0.299*v-0.300*vsu+1.250*vsw, bg = 0.587*v-0.586*vsu-1.050*vsw, bb = 0.114*v+0.886*vsu-0.200*vsw; var r,g,b,a; for (i = 0; i < nPixels; i += 4) { r = data[i+0]; g = data[i+1]; b = data[i+2]; a = data[i+3]; data[i+0] = rr*r + rg*g + rb*b + l; data[i+1] = gr*r + gg*g + gb*b + l; data[i+2] = br*r + bg*g + bb*b + l; data[i+3] = a; // alpha } }; })(); ;(function () { /** * Emboss Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData * Pixastic Lib - Emboss filter - v0.1.0 * Copyright (c) 2008 Jacob Seidelin, [email protected], http://blog.nihilogic.dk/ * License: [http://www.pixastic.com/lib/license.txt] */ Kinetic.Filters.Emboss = function (imageData) { // pixastic strength is between 0 and 10. I want it between 0 and 1 // pixastic greyLevel is between 0 and 255. I want it between 0 and 1. Also, // a max value of greyLevel yields a white emboss, and the min value yields a black // emboss. Therefore, I changed greyLevel to whiteLevel var strength = this.embossStrength() * 10, greyLevel = this.embossWhiteLevel() * 255, direction = this.embossDirection(), blend = this.embossBlend(), dirY = 0, dirX = 0, data = imageData.data, w = imageData.width, h = imageData.height, w4 = w*4, y = h; switch (direction) { case 'top-left': dirY = -1; dirX = -1; break; case 'top': dirY = -1; dirX = 0; break; case 'top-right': dirY = -1; dirX = 1; break; case 'right': dirY = 0; dirX = 1; break; case 'bottom-right': dirY = 1; dirX = 1; break; case 'bottom': dirY = 1; dirX = 0; break; case 'bottom-left': dirY = 1; dirX = -1; break; case 'left': dirY = 0; dirX = -1; break; } do { var offsetY = (y-1)*w4; var otherY = dirY; if (y + otherY < 1){ otherY = 0; } if (y + otherY > h) { otherY = 0; } var offsetYOther = (y-1+otherY)*w*4; var x = w; do { var offset = offsetY + (x-1)*4; var otherX = dirX; if (x + otherX < 1){ otherX = 0; } if (x + otherX > w) { otherX = 0; } var offsetOther = offsetYOther + (x-1+otherX)*4; var dR = data[offset] - data[offsetOther]; var dG = data[offset+1] - data[offsetOther+1]; var dB = data[offset+2] - data[offsetOther+2]; var dif = dR; var absDif = dif > 0 ? dif : -dif; var absG = dG > 0 ? dG : -dG; var absB = dB > 0 ? dB : -dB; if (absG > absDif) { dif = dG; } if (absB > absDif) { dif = dB; } dif *= strength; if (blend) { var r = data[offset] + dif; var g = data[offset+1] + dif; var b = data[offset+2] + dif; data[offset] = (r > 255) ? 255 : (r < 0 ? 0 : r); data[offset+1] = (g > 255) ? 255 : (g < 0 ? 0 : g); data[offset+2] = (b > 255) ? 255 : (b < 0 ? 0 : b); } else { var grey = greyLevel - dif; if (grey < 0) { grey = 0; } else if (grey > 255) { grey = 255; } data[offset] = data[offset+1] = data[offset+2] = grey; } } while (--x); } while (--y); }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossStrength', 0.5, null, Kinetic.Factory.afterSetFilter); /** * get/set emboss strength * @name embossStrength * @method * @memberof Kinetic.Node.prototype * @param {Number} level between 0 and 1. Default is 0.5 * @returns {Number} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossWhiteLevel', 0.5, null, Kinetic.Factory.afterSetFilter); /** * get/set emboss white level * @name embossWhiteLevel * @method * @memberof Kinetic.Node.prototype * @param {Number} embossWhiteLevel between 0 and 1. Default is 0.5 * @returns {Number} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossDirection', 'top-left', null, Kinetic.Factory.afterSetFilter); /** * get/set emboss direction * @name embossDirection * @method * @memberof Kinetic.Node.prototype * @param {String} embossDirection can be top-left, top, top-right, right, bottom-right, bottom, bottom-left or left * The default is top-left * @returns {String} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'embossBlend', false, null, Kinetic.Factory.afterSetFilter); /** * get/set emboss blend * @name embossBlend * @method * @memberof Kinetic.Node.prototype * @param {Boolean} embossBlend * @returns {Boolean} */ })(); ;(function () { function remap(fromValue, fromMin, fromMax, toMin, toMax) { // Compute the range of the data var fromRange = fromMax - fromMin, toRange = toMax - toMin, toValue; // If either range is 0, then the value can only be mapped to 1 value if (fromRange === 0) { return toMin + toRange / 2; } if (toRange === 0) { return toMin; } // (1) untranslate, (2) unscale, (3) rescale, (4) retranslate toValue = (fromValue - fromMin) / fromRange; toValue = (toRange * toValue) + toMin; return toValue; } /** * Enhance Filter. Adjusts the colors so that they span the widest * possible range (ie 0-255). Performs w*h pixel reads and w*h pixel * writes. * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author ippo615 */ Kinetic.Filters.Enhance = function (imageData) { var data = imageData.data, nSubPixels = data.length, rMin = data[0], rMax = rMin, r, gMin = data[1], gMax = gMin, g, bMin = data[2], bMax = bMin, b, aMin = data[3], aMax = aMin, i; // If we are not enhancing anything - don't do any computation var enhanceAmount = this.enhance(); if( enhanceAmount === 0 ){ return; } // 1st Pass - find the min and max for each channel: for (i = 0; i < nSubPixels; i += 4) { r = data[i + 0]; if (r < rMin) { rMin = r; } else if (r > rMax) { rMax = r; } g = data[i + 1]; if (g < gMin) { gMin = g; } else if (g > gMax) { gMax = g; } b = data[i + 2]; if (b < bMin) { bMin = b; } else if (b > bMax) { bMax = b; } //a = data[i + 3]; //if (a < aMin) { aMin = a; } else //if (a > aMax) { aMax = a; } } // If there is only 1 level - don't remap if( rMax === rMin ){ rMax = 255; rMin = 0; } if( gMax === gMin ){ gMax = 255; gMin = 0; } if( bMax === bMin ){ bMax = 255; bMin = 0; } if( aMax === aMin ){ aMax = 255; aMin = 0; } var rMid, rGoalMax,rGoalMin, gMid, gGoalMax,gGoalMin, bMid, bGoalMax,aGoalMin, aMid, aGoalMax,bGoalMin; // If the enhancement is positive - stretch the histogram if ( enhanceAmount > 0 ){ rGoalMax = rMax + enhanceAmount*(255-rMax); rGoalMin = rMin - enhanceAmount*(rMin-0); gGoalMax = gMax + enhanceAmount*(255-gMax); gGoalMin = gMin - enhanceAmount*(gMin-0); bGoalMax = bMax + enhanceAmount*(255-bMax); bGoalMin = bMin - enhanceAmount*(bMin-0); aGoalMax = aMax + enhanceAmount*(255-aMax); aGoalMin = aMin - enhanceAmount*(aMin-0); // If the enhancement is negative - compress the histogram } else { rMid = (rMax + rMin)*0.5; rGoalMax = rMax + enhanceAmount*(rMax-rMid); rGoalMin = rMin + enhanceAmount*(rMin-rMid); gMid = (gMax + gMin)*0.5; gGoalMax = gMax + enhanceAmount*(gMax-gMid); gGoalMin = gMin + enhanceAmount*(gMin-gMid); bMid = (bMax + bMin)*0.5; bGoalMax = bMax + enhanceAmount*(bMax-bMid); bGoalMin = bMin + enhanceAmount*(bMin-bMid); aMid = (aMax + aMin)*0.5; aGoalMax = aMax + enhanceAmount*(aMax-aMid); aGoalMin = aMin + enhanceAmount*(aMin-aMid); } // Pass 2 - remap everything, except the alpha for (i = 0; i < nSubPixels; i += 4) { data[i + 0] = remap(data[i + 0], rMin, rMax, rGoalMin, rGoalMax); data[i + 1] = remap(data[i + 1], gMin, gMax, gGoalMin, gGoalMax); data[i + 2] = remap(data[i + 2], bMin, bMax, bGoalMin, bGoalMax); //data[i + 3] = remap(data[i + 3], aMin, aMax, aGoalMin, aGoalMax); } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'enhance', 0, null, Kinetic.Factory.afterSetFilter); /** * get/set enhance * @name enhance * @method * @memberof Kinetic.Node.prototype * @param {Float} amount * @returns {Float} */ })(); ;(function () { /** * Posterize Filter. Adjusts the channels so that there are no more * than n different values for that channel. This is also applied * to the alpha channel. * @function * @author ippo615 * @memberof Kinetic.Filters * @param {Object} imageData */ Kinetic.Filters.Posterize = function (imageData) { // level must be between 1 and 255 var levels = Math.round(this.levels() * 254) + 1, data = imageData.data, len = data.length, scale = (255 / levels), i; for (i = 0; i < len; i += 1) { data[i] = Math.floor(data[i] / scale) * scale; } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'levels', 0.5, null, Kinetic.Factory.afterSetFilter); /** * get/set levels. Must be a number between 0 and 1 * @name levels * @method * @memberof Kinetic.Node.prototype * @param {Number} level between 0 and 1 * @returns {Number} */ })();;(function () { /** * Noise Filter. Randomly adds or substracts to the color channels * @function * @memberof Kinetic.Filters * @param {Object} imagedata * @author ippo615 */ Kinetic.Filters.Noise = function (imageData) { var amount = this.noise() * 255, data = imageData.data, nPixels = data.length, half = amount / 2, i; for (i = 0; i < nPixels; i += 4) { data[i + 0] += half - 2 * half * Math.random(); data[i + 1] += half - 2 * half * Math.random(); data[i + 2] += half - 2 * half * Math.random(); } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'noise', 0.2, null, Kinetic.Factory.afterSetFilter); /** * get/set noise amount. Must be a value between 0 and 1 * @name noise * @method * @memberof Kinetic.Node.prototype * @param {Number} noise * @returns {Number} */ })(); ;(function () { /** * Pixelate Filter. Averages groups of pixels and redraws * them as larger pixels * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author ippo615 */ Kinetic.Filters.Pixelate = function (imageData) { var pixelSize = Math.ceil(this.pixelSize()), width = imageData.width, height = imageData.height, x, y, i, //pixelsPerBin = pixelSize * pixelSize, red, green, blue, alpha, nBinsX = Math.ceil(width / pixelSize), nBinsY = Math.ceil(height / pixelSize), xBinStart, xBinEnd, yBinStart, yBinEnd, xBin, yBin, pixelsInBin; imageData = imageData.data; for (xBin = 0; xBin < nBinsX; xBin += 1) { for (yBin = 0; yBin < nBinsY; yBin += 1) { // Initialize the color accumlators to 0 red = 0; green = 0; blue = 0; alpha = 0; // Determine which pixels are included in this bin xBinStart = xBin * pixelSize; xBinEnd = xBinStart + pixelSize; yBinStart = yBin * pixelSize; yBinEnd = yBinStart + pixelSize; // Add all of the pixels to this bin! pixelsInBin = 0; for (x = xBinStart; x < xBinEnd; x += 1) { if( x >= width ){ continue; } for (y = yBinStart; y < yBinEnd; y += 1) { if( y >= height ){ continue; } i = (width * y + x) * 4; red += imageData[i + 0]; green += imageData[i + 1]; blue += imageData[i + 2]; alpha += imageData[i + 3]; pixelsInBin += 1; } } // Make sure the channels are between 0-255 red = red / pixelsInBin; green = green / pixelsInBin; blue = blue / pixelsInBin; // Draw this bin for (x = xBinStart; x < xBinEnd; x += 1) { if( x >= width ){ continue; } for (y = yBinStart; y < yBinEnd; y += 1) { if( y >= height ){ continue; } i = (width * y + x) * 4; imageData[i + 0] = red; imageData[i + 1] = green; imageData[i + 2] = blue; imageData[i + 3] = alpha; } } } } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'pixelSize', 8, null, Kinetic.Factory.afterSetFilter); /** * get/set pixel size * @name pixelSize * @method * @memberof Kinetic.Node.prototype * @param {Integer} pixelSize * @returns {Integer} */ })();;(function () { /** * Threshold Filter. Pushes any value above the mid point to * the max and any value below the mid point to the min. * This affects the alpha channel. * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author ippo615 */ Kinetic.Filters.Threshold = function (imageData) { var level = this.threshold() * 255, data = imageData.data, len = data.length, i; for (i = 0; i < len; i += 1) { data[i] = data[i] < level ? 0 : 255; } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'threshold', 0.5, null, Kinetic.Factory.afterSetFilter); /** * get/set threshold. Must be a value between 0 and 1 * @name threshold * @method * @memberof Kinetic.Node.prototype * @param {Number} threshold * @returns {Number} */ })();;(function() { /** * Sepia Filter * Based on: Pixastic Lib - Sepia filter - v0.1.0 * Copyright (c) 2008 Jacob Seidelin, [email protected], http://blog.nihilogic.dk/ * @function * @memberof Kinetic.Filters * @param {Object} imageData * @author Jacob Seidelin <[email protected]> * @license MPL v1.1 [http://www.pixastic.com/lib/license.txt] */ Kinetic.Filters.Sepia = function (imageData) { var data = imageData.data, w = imageData.width, y = imageData.height, w4 = w*4, offsetY, x, offset, or, og, ob, r, g, b; do { offsetY = (y-1)*w4; x = w; do { offset = offsetY + (x-1)*4; or = data[offset]; og = data[offset+1]; ob = data[offset+2]; r = or * 0.393 + og * 0.769 + ob * 0.189; g = or * 0.349 + og * 0.686 + ob * 0.168; b = or * 0.272 + og * 0.534 + ob * 0.131; data[offset] = r > 255 ? 255 : r; data[offset+1] = g > 255 ? 255 : g; data[offset+2] = b > 255 ? 255 : b; data[offset+3] = data[offset+3]; } while (--x); } while (--y); }; })(); ;(function () { /** * Solarize Filter * @function * @memberof Kinetic.Filters * @param {Object} imageData * Pixastic Lib - Solarize filter - v0.1.0 * Copyright (c) 2008 Jacob Seidelin, [email protected], http://blog.nihilogic.dk/ * License: [http://www.pixastic.com/lib/license.txt] */ Kinetic.Filters.Solarize = function (imageData) { var data = imageData.data, w = imageData.width, h = imageData.height, w4 = w*4, y = h; do { var offsetY = (y-1)*w4; var x = w; do { var offset = offsetY + (x-1)*4; var r = data[offset]; var g = data[offset+1]; var b = data[offset+2]; if (r > 127) { r = 255 - r; } if (g > 127) { g = 255 - g; } if (b > 127) { b = 255 - b; } data[offset] = r; data[offset+1] = g; data[offset+2] = b; } while (--x); } while (--y); }; })(); ;/*jshint newcap:false */ (function () { /* * ToPolar Filter. Converts image data to polar coordinates. Performs * w*h*4 pixel reads and w*h pixel writes. The r axis is placed along * what would be the y axis and the theta axis along the x axis. * @function * @author ippo615 * @memberof Kinetic.Filters * @param {ImageData} src, the source image data (what will be transformed) * @param {ImageData} dst, the destination image data (where it will be saved) * @param {Object} opt * @param {Number} [opt.polarCenterX] horizontal location for the center of the circle, * default is in the middle * @param {Number} [opt.polarCenterY] vertical location for the center of the circle, * default is in the middle */ var ToPolar = function(src,dst,opt){ var srcPixels = src.data, dstPixels = dst.data, xSize = src.width, ySize = src.height, xMid = opt.polarCenterX || xSize/2, yMid = opt.polarCenterY || ySize/2, i, x, y, r=0,g=0,b=0,a=0; // Find the largest radius var rad, rMax = Math.sqrt( xMid*xMid + yMid*yMid ); x = xSize - xMid; y = ySize - yMid; rad = Math.sqrt( x*x + y*y ); rMax = (rad > rMax)?rad:rMax; // We'll be uisng y as the radius, and x as the angle (theta=t) var rSize = ySize, tSize = xSize, radius, theta; // We want to cover all angles (0-360) and we need to convert to // radians (*PI/180) var conversion = 360/tSize*Math.PI/180, sin, cos; // var x1, x2, x1i, x2i, y1, y2, y1i, y2i, scale; for( theta=0; theta<tSize; theta+=1 ){ sin = Math.sin(theta*conversion); cos = Math.cos(theta*conversion); for( radius=0; radius<rSize; radius+=1 ){ x = Math.floor(xMid+rMax*radius/rSize*cos); y = Math.floor(yMid+rMax*radius/rSize*sin); i = (y*xSize + x)*4; r = srcPixels[i+0]; g = srcPixels[i+1]; b = srcPixels[i+2]; a = srcPixels[i+3]; // Store it //i = (theta * xSize + radius) * 4; i = (theta + radius*xSize) * 4; dstPixels[i+0] = r; dstPixels[i+1] = g; dstPixels[i+2] = b; dstPixels[i+3] = a; } } }; /* * FromPolar Filter. Converts image data from polar coordinates back to rectangular. * Performs w*h*4 pixel reads and w*h pixel writes. * @function * @author ippo615 * @memberof Kinetic.Filters * @param {ImageData} src, the source image data (what will be transformed) * @param {ImageData} dst, the destination image data (where it will be saved) * @param {Object} opt * @param {Number} [opt.polarCenterX] horizontal location for the center of the circle, * default is in the middle * @param {Number} [opt.polarCenterY] vertical location for the center of the circle, * default is in the middle * @param {Number} [opt.polarRotation] amount to rotate the image counterclockwis, * 0 is no rotation, 360 degrees is a full rotation */ var FromPolar = function(src,dst,opt){ var srcPixels = src.data, dstPixels = dst.data, xSize = src.width, ySize = src.height, xMid = opt.polarCenterX || xSize/2, yMid = opt.polarCenterY || ySize/2, i, x, y, dx, dy, r=0,g=0,b=0,a=0; // Find the largest radius var rad, rMax = Math.sqrt( xMid*xMid + yMid*yMid ); x = xSize - xMid; y = ySize - yMid; rad = Math.sqrt( x*x + y*y ); rMax = (rad > rMax)?rad:rMax; // We'll be uisng x as the radius, and y as the angle (theta=t) var rSize = ySize, tSize = xSize, radius, theta, phaseShift = opt.polarRotation || 0; // We need to convert to degrees and we need to make sure // it's between (0-360) // var conversion = tSize/360*180/Math.PI; //var conversion = tSize/360*180/Math.PI; var x1, y1; for( x=0; x<xSize; x+=1 ){ for( y=0; y<ySize; y+=1 ){ dx = x - xMid; dy = y - yMid; radius = Math.sqrt(dx*dx + dy*dy)*rSize/rMax; theta = (Math.atan2(dy,dx)*180/Math.PI + 360 + phaseShift)%360; theta = theta*tSize/360; x1 = Math.floor(theta); y1 = Math.floor(radius); i = (y1*xSize + x1)*4; r = srcPixels[i+0]; g = srcPixels[i+1]; b = srcPixels[i+2]; a = srcPixels[i+3]; // Store it i = (y*xSize + x)*4; dstPixels[i+0] = r; dstPixels[i+1] = g; dstPixels[i+2] = b; dstPixels[i+3] = a; } } }; //Kinetic.Filters.ToPolar = Kinetic.Util._FilterWrapDoubleBuffer(ToPolar); //Kinetic.Filters.FromPolar = Kinetic.Util._FilterWrapDoubleBuffer(FromPolar); // create a temporary canvas for working - shared between multiple calls var tempCanvas = Kinetic.Util.createCanvasElement(); /* * Kaleidoscope Filter. * @function * @author ippo615 * @memberof Kinetic.Filters */ Kinetic.Filters.Kaleidoscope = function(imageData){ var xSize = imageData.width, ySize = imageData.height; var x,y,xoff,i, r,g,b,a, srcPos, dstPos; var power = Math.round( this.kaleidoscopePower() ); var angle = Math.round( this.kaleidoscopeAngle() ); var offset = Math.floor(xSize*(angle%360)/360); if( power < 1 ){return;} // Work with our shared buffer canvas tempCanvas.width = xSize; tempCanvas.height = ySize; var scratchData = tempCanvas.getContext('2d').getImageData(0,0,xSize,ySize); // Convert thhe original to polar coordinates ToPolar( imageData, scratchData, { polarCenterX:xSize/2, polarCenterY:ySize/2 }); // Determine how big each section will be, if it's too small // make it bigger var minSectionSize = xSize / Math.pow(2,power); while( minSectionSize <= 8){ minSectionSize = minSectionSize*2; power -= 1; } minSectionSize = Math.ceil(minSectionSize); var sectionSize = minSectionSize; // Copy the offset region to 0 // Depending on the size of filter and location of the offset we may need // to copy the section backwards to prevent it from rewriting itself var xStart = 0, xEnd = sectionSize, xDelta = 1; if( offset+minSectionSize > xSize ){ xStart = sectionSize; xEnd = 0; xDelta = -1; } for( y=0; y<ySize; y+=1 ){ for( x=xStart; x !== xEnd; x+=xDelta ){ xoff = Math.round(x+offset)%xSize; srcPos = (xSize*y+xoff)*4; r = scratchData.data[srcPos+0]; g = scratchData.data[srcPos+1]; b = scratchData.data[srcPos+2]; a = scratchData.data[srcPos+3]; dstPos = (xSize*y+x)*4; scratchData.data[dstPos+0] = r; scratchData.data[dstPos+1] = g; scratchData.data[dstPos+2] = b; scratchData.data[dstPos+3] = a; } } // Perform the actual effect for( y=0; y<ySize; y+=1 ){ sectionSize = Math.floor( minSectionSize ); for( i=0; i<power; i+=1 ){ for( x=0; x<sectionSize+1; x+=1 ){ srcPos = (xSize*y+x)*4; r = scratchData.data[srcPos+0]; g = scratchData.data[srcPos+1]; b = scratchData.data[srcPos+2]; a = scratchData.data[srcPos+3]; dstPos = (xSize*y+sectionSize*2-x-1)*4; scratchData.data[dstPos+0] = r; scratchData.data[dstPos+1] = g; scratchData.data[dstPos+2] = b; scratchData.data[dstPos+3] = a; } sectionSize *= 2; } } // Convert back from polar coordinates FromPolar(scratchData,imageData,{polarRotation:0}); }; /** * get/set kaleidoscope power * @name kaleidoscopePower * @method * @memberof Kinetic.Node.prototype * @param {Integer} power of kaleidoscope * @returns {Integer} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'kaleidoscopePower', 2, null, Kinetic.Factory.afterSetFilter); /** * get/set kaleidoscope angle * @name kaleidoscopeAngle * @method * @memberof Kinetic.Node.prototype * @param {Integer} degrees * @returns {Integer} */ Kinetic.Factory.addGetterSetter(Kinetic.Node, 'kaleidoscopeAngle', 0, null, Kinetic.Factory.afterSetFilter); })(); ;(function() { var BATCH_DRAW_STOP_TIME_DIFF = 500; var now =(function() { if (Kinetic.root.performance && Kinetic.root.performance.now) { return function() { return Kinetic.root.performance.now(); }; } else { return function() { return new Date().getTime(); }; } })(); var RAF = (function() { return Kinetic.root.requestAnimationFrame || Kinetic.root.webkitRequestAnimationFrame || Kinetic.root.mozRequestAnimationFrame || Kinetic.root.oRequestAnimationFrame || Kinetic.root.msRequestAnimationFrame || FRAF; })(); function FRAF(callback) { Kinetic.root.setTimeout(callback, 1000 / 60); } function requestAnimFrame() { return RAF.apply(Kinetic.root, arguments); } /** * Animation constructor. A stage is used to contain multiple layers and handle * @constructor * @memberof Kinetic * @param {Function} func function executed on each animation frame. The function is passed a frame object, which contains * timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed * since the last animation frame. The lastTime property is time in milliseconds that elapsed from the moment the animation started * to the last animation frame. The time property is the time in milliseconds that ellapsed from the moment the animation started * to the current animation frame. The frameRate property is the current frame rate in frames / second * @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null. * Not specifying a node will result in no redraw. * @example * // move a node to the right at 50 pixels / second<br> * var velocity = 50;<br><br> * * var anim = new Kinetic.Animation(function(frame) {<br> * var dist = velocity * (frame.timeDiff / 1000);<br> * node.move(dist, 0);<br> * }, layer);<br><br> * * anim.start(); */ Kinetic.Animation = function(func, layers) { var Anim = Kinetic.Animation; this.func = func; this.setLayers(layers); this.id = Anim.animIdCounter++; this.frame = { time: 0, timeDiff: 0, lastTime: now() }; }; /* * Animation methods */ Kinetic.Animation.prototype = { /** * set layers to be redrawn on each animation frame * @method * @memberof Kinetic.Animation.prototype * @param {Kinetic.Layer|Array} [layers] layer(s) to be redrawn.&nbsp; Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw. */ setLayers: function(layers) { var lays = []; // if passing in no layers if (!layers) { lays = []; } // if passing in an array of Layers // NOTE: layers could be an array or Kinetic.Collection. for simplicity, I'm just inspecting // the length property to check for both cases else if (layers.length > 0) { lays = layers; } // if passing in a Layer else { lays = [layers]; } this.layers = lays; }, /** * get layers * @method * @memberof Kinetic.Animation.prototype */ getLayers: function() { return this.layers; }, /** * add layer. Returns true if the layer was added, and false if it was not * @method * @memberof Kinetic.Animation.prototype * @param {Kinetic.Layer} layer */ addLayer: function(layer) { var layers = this.layers, len, n; if (layers) { len = layers.length; // don't add the layer if it already exists for (n = 0; n < len; n++) { if (layers[n]._id === layer._id) { return false; } } } else { this.layers = []; } this.layers.push(layer); return true; }, /** * determine if animation is running or not. returns true or false * @method * @memberof Kinetic.Animation.prototype */ isRunning: function() { var a = Kinetic.Animation, animations = a.animations, len = animations.length, n; for(n = 0; n < len; n++) { if(animations[n].id === this.id) { return true; } } return false; }, /** * start animation * @method * @memberof Kinetic.Animation.prototype */ start: function() { var Anim = Kinetic.Animation; this.stop(); this.frame.timeDiff = 0; this.frame.lastTime = now(); Anim._addAnimation(this); }, /** * stop animation * @method * @memberof Kinetic.Animation.prototype */ stop: function() { Kinetic.Animation._removeAnimation(this); }, _updateFrameObject: function(time) { this.frame.timeDiff = time - this.frame.lastTime; this.frame.lastTime = time; this.frame.time += this.frame.timeDiff; this.frame.frameRate = 1000 / this.frame.timeDiff; } }; Kinetic.Animation.animations = []; Kinetic.Animation.animIdCounter = 0; Kinetic.Animation.animRunning = false; Kinetic.Animation._addAnimation = function(anim) { this.animations.push(anim); this._handleAnimation(); }; Kinetic.Animation._removeAnimation = function(anim) { var id = anim.id, animations = this.animations, len = animations.length, n; for(n = 0; n < len; n++) { if(animations[n].id === id) { this.animations.splice(n, 1); break; } } }; Kinetic.Animation._runFrames = function() { var layerHash = {}, animations = this.animations, anim, layers, func, n, i, layersLen, layer, key; /* * loop through all animations and execute animation * function. if the animation object has specified node, * we can add the node to the nodes hash to eliminate * drawing the same node multiple times. The node property * can be the stage itself or a layer */ /* * WARNING: don't cache animations.length because it could change while * the for loop is running, causing a JS error */ for(n = 0; n < animations.length; n++) { anim = animations[n]; layers = anim.layers; func = anim.func; anim._updateFrameObject(now()); layersLen = layers.length; for (i=0; i<layersLen; i++) { layer = layers[i]; if(layer._id !== undefined) { layerHash[layer._id] = layer; } } // if animation object has a function, execute it if(func) { func.call(anim, anim.frame); } } for(key in layerHash) { layerHash[key].draw(); } }; Kinetic.Animation._animationLoop = function() { var Anim = Kinetic.Animation; if(Anim.animations.length) { requestAnimFrame(Anim._animationLoop); Anim._runFrames(); } else { Anim.animRunning = false; } }; Kinetic.Animation._handleAnimation = function() { var that = this; if(!this.animRunning) { this.animRunning = true; that._animationLoop(); } }; var moveTo = Kinetic.Node.prototype.moveTo; Kinetic.Node.prototype.moveTo = function(container) { moveTo.call(this, container); }; /** * batch draw * @method * @memberof Kinetic.Layer.prototype */ Kinetic.Layer.prototype.batchDraw = function() { var that = this, Anim = Kinetic.Animation; if (!this.batchAnim) { this.batchAnim = new Anim(function() { if (that.lastBatchDrawTime && now() - that.lastBatchDrawTime > BATCH_DRAW_STOP_TIME_DIFF) { that.batchAnim.stop(); } }, this); } this.lastBatchDrawTime = now(); if (!this.batchAnim.isRunning()) { this.draw(); this.batchAnim.start(); } }; /** * batch draw * @method * @memberof Kinetic.Stage.prototype */ Kinetic.Stage.prototype.batchDraw = function() { this.getChildren().each(function(layer) { layer.batchDraw(); }); }; })((1,eval)('this'));;(function() { var blacklist = { node: 1, duration: 1, easing: 1, onFinish: 1, yoyo: 1 }, PAUSED = 1, PLAYING = 2, REVERSING = 3, idCounter = 0; /** * Tween constructor. Tweens enable you to animate a node between the current state and a new state. * You can play, pause, reverse, seek, reset, and finish tweens. By default, tweens are animated using * a linear easing. For more tweening options, check out {@link Kinetic.Easings} * @constructor * @memberof Kinetic * @example * // instantiate new tween which fully rotates a node in 1 second * var tween = new Kinetic.Tween({<br> * node: node,<br> * rotationDeg: 360,<br> * duration: 1,<br> * easing: Kinetic.Easings.EaseInOut<br> * });<br><br> * * // play tween<br> * tween.play();<br><br> * * // pause tween<br> * tween.pause(); */ Kinetic.Tween = function(config) { var that = this, node = config.node, nodeId = node._id, duration = config.duration || 1, easing = config.easing || Kinetic.Easings.Linear, yoyo = !!config.yoyo, key; this.node = node; this._id = idCounter++; this.anim = new Kinetic.Animation(function() { that.tween.onEnterFrame(); }, node.getLayer()); this.tween = new Tween(key, function(i) { that._tweenFunc(i); }, easing, 0, 1, duration * 1000, yoyo); this._addListeners(); // init attrs map if (!Kinetic.Tween.attrs[nodeId]) { Kinetic.Tween.attrs[nodeId] = {}; } if (!Kinetic.Tween.attrs[nodeId][this._id]) { Kinetic.Tween.attrs[nodeId][this._id] = {}; } // init tweens map if (!Kinetic.Tween.tweens[nodeId]) { Kinetic.Tween.tweens[nodeId] = {}; } for (key in config) { if (blacklist[key] === undefined) { this._addAttr(key, config[key]); } } this.reset(); // callbacks this.onFinish = config.onFinish; this.onReset = config.onReset; }; // start/diff object = attrs.nodeId.tweenId.attr Kinetic.Tween.attrs = {}; // tweenId = tweens.nodeId.attr Kinetic.Tween.tweens = {}; Kinetic.Tween.prototype = { _addAttr: function(key, end) { var node = this.node, nodeId = node._id, start, diff, tweenId, n, len; // remove conflict from tween map if it exists tweenId = Kinetic.Tween.tweens[nodeId][key]; if (tweenId) { delete Kinetic.Tween.attrs[nodeId][tweenId][key]; } // add to tween map start = node.getAttr(key); if (Kinetic.Util._isArray(end)) { diff = []; len = end.length; for (n=0; n<len; n++) { diff.push(end[n] - start[n]); } } else { diff = end - start; } Kinetic.Tween.attrs[nodeId][this._id][key] = { start: start, diff: diff }; Kinetic.Tween.tweens[nodeId][key] = this._id; }, _tweenFunc: function(i) { var node = this.node, attrs = Kinetic.Tween.attrs[node._id][this._id], key, attr, start, diff, newVal, n, len; for (key in attrs) { attr = attrs[key]; start = attr.start; diff = attr.diff; if (Kinetic.Util._isArray(start)) { newVal = []; len = start.length; for (n=0; n<len; n++) { newVal.push(start[n] + (diff[n] * i)); } } else { newVal = start + (diff * i); } node.setAttr(key, newVal); } }, _addListeners: function() { var that = this; // start listeners this.tween.onPlay = function() { that.anim.start(); }; this.tween.onReverse = function() { that.anim.start(); }; // stop listeners this.tween.onPause = function() { that.anim.stop(); }; this.tween.onFinish = function() { if (that.onFinish) { that.onFinish(); } }; this.tween.onReset = function() { if (that.onReset) { that.onReset(); } }; }, /** * play * @method * @memberof Kinetic.Tween.prototype * @returns {Tween} */ play: function() { this.tween.play(); return this; }, /** * reverse * @method * @memberof Kinetic.Tween.prototype * @returns {Tween} */ reverse: function() { this.tween.reverse(); return this; }, /** * reset * @method * @memberof Kinetic.Tween.prototype * @returns {Tween} */ reset: function() { var node = this.node; this.tween.reset(); return this; }, /** * seek * @method * @memberof Kinetic.Tween.prototype * @param {Integer} t time in seconds between 0 and the duration * @returns {Tween} */ seek: function(t) { var node = this.node; this.tween.seek(t * 1000); return this; }, /** * pause * @method * @memberof Kinetic.Tween.prototype * @returns {Tween} */ pause: function() { this.tween.pause(); return this; }, /** * finish * @method * @memberof Kinetic.Tween.prototype * @returns {Tween} */ finish: function() { var node = this.node; this.tween.finish(); return this; }, /** * destroy * @method * @memberof Kinetic.Tween.prototype */ destroy: function() { var nodeId = this.node._id, thisId = this._id, attrs = Kinetic.Tween.tweens[nodeId], key; this.pause(); for (key in attrs) { delete Kinetic.Tween.tweens[nodeId][key]; } delete Kinetic.Tween.attrs[nodeId][thisId]; } }; var Tween = function(prop, propFunc, func, begin, finish, duration, yoyo) { this.prop = prop; this.propFunc = propFunc; this.begin = begin; this._pos = begin; this.duration = duration; this._change = 0; this.prevPos = 0; this.yoyo = yoyo; this._time = 0; this._position = 0; this._startTime = 0; this._finish = 0; this.func = func; this._change = finish - this.begin; this.pause(); }; /* * Tween methods */ Tween.prototype = { fire: function(str) { var handler = this[str]; if (handler) { handler(); } }, setTime: function(t) { if(t > this.duration) { if(this.yoyo) { this._time = this.duration; this.reverse(); } else { this.finish(); } } else if(t < 0) { if(this.yoyo) { this._time = 0; this.play(); } else { this.reset(); } } else { this._time = t; this.update(); } }, getTime: function() { return this._time; }, setPosition: function(p) { this.prevPos = this._pos; this.propFunc(p); this._pos = p; }, getPosition: function(t) { if(t === undefined) { t = this._time; } return this.func(t, this.begin, this._change, this.duration); }, play: function() { this.state = PLAYING; this._startTime = this.getTimer() - this._time; this.onEnterFrame(); this.fire('onPlay'); }, reverse: function() { this.state = REVERSING; this._time = this.duration - this._time; this._startTime = this.getTimer() - this._time; this.onEnterFrame(); this.fire('onReverse'); }, seek: function(t) { this.pause(); this._time = t; this.update(); this.fire('onSeek'); }, reset: function() { this.pause(); this._time = 0; this.update(); this.fire('onReset'); }, finish: function() { this.pause(); this._time = this.duration; this.update(); this.fire('onFinish'); }, update: function() { this.setPosition(this.getPosition(this._time)); }, onEnterFrame: function() { var t = this.getTimer() - this._startTime; if(this.state === PLAYING) { this.setTime(t); } else if (this.state === REVERSING) { this.setTime(this.duration - t); } }, pause: function() { this.state = PAUSED; this.fire('onPause'); }, getTimer: function() { return new Date().getTime(); } }; /* * These eases were ported from an Adobe Flash tweening library to JavaScript * by Xaric */ /** * @namespace Easings * @memberof Kinetic */ Kinetic.Easings = { /** * back ease in * @function * @memberof Kinetic.Easings */ 'BackEaseIn': function(t, b, c, d) { var s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, /** * back ease out * @function * @memberof Kinetic.Easings */ 'BackEaseOut': function(t, b, c, d) { var s = 1.70158; return c * (( t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, /** * back ease in out * @function * @memberof Kinetic.Easings */ 'BackEaseInOut': function(t, b, c, d) { var s = 1.70158; if((t /= d / 2) < 1) { return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; } return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, /** * elastic ease in * @function * @memberof Kinetic.Easings */ 'ElasticEaseIn': function(t, b, c, d, a, p) {<|fim▁hole|> var s = 0; if(t === 0) { return b; } if((t /= d) == 1) { return b + c; } if(!p) { p = d * 0.3; } if(!a || a < Math.abs(c)) { a = c; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(c / a); } return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; }, /** * elastic ease out * @function * @memberof Kinetic.Easings */ 'ElasticEaseOut': function(t, b, c, d, a, p) { // added s = 0 var s = 0; if(t === 0) { return b; } if((t /= d) == 1) { return b + c; } if(!p) { p = d * 0.3; } if(!a || a < Math.abs(c)) { a = c; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(c / a); } return (a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b); }, /** * elastic ease in out * @function * @memberof Kinetic.Easings */ 'ElasticEaseInOut': function(t, b, c, d, a, p) { // added s = 0 var s = 0; if(t === 0) { return b; } if((t /= d / 2) == 2) { return b + c; } if(!p) { p = d * (0.3 * 1.5); } if(!a || a < Math.abs(c)) { a = c; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(c / a); } if(t < 1) { return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; } return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * 0.5 + c + b; }, /** * bounce ease out * @function * @memberof Kinetic.Easings */ 'BounceEaseOut': function(t, b, c, d) { if((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if(t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b; } else if(t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b; } }, /** * bounce ease in * @function * @memberof Kinetic.Easings */ 'BounceEaseIn': function(t, b, c, d) { return c - Kinetic.Easings.BounceEaseOut(d - t, 0, c, d) + b; }, /** * bounce ease in out * @function * @memberof Kinetic.Easings */ 'BounceEaseInOut': function(t, b, c, d) { if(t < d / 2) { return Kinetic.Easings.BounceEaseIn(t * 2, 0, c, d) * 0.5 + b; } else { return Kinetic.Easings.BounceEaseOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b; } }, /** * ease in * @function * @memberof Kinetic.Easings */ 'EaseIn': function(t, b, c, d) { return c * (t /= d) * t + b; }, /** * ease out * @function * @memberof Kinetic.Easings */ 'EaseOut': function(t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, /** * ease in out * @function * @memberof Kinetic.Easings */ 'EaseInOut': function(t, b, c, d) { if((t /= d / 2) < 1) { return c / 2 * t * t + b; } return -c / 2 * ((--t) * (t - 2) - 1) + b; }, /** * strong ease in * @function * @memberof Kinetic.Easings */ 'StrongEaseIn': function(t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, /** * strong ease out * @function * @memberof Kinetic.Easings */ 'StrongEaseOut': function(t, b, c, d) { return c * (( t = t / d - 1) * t * t * t * t + 1) + b; }, /** * strong ease in out * @function * @memberof Kinetic.Easings */ 'StrongEaseInOut': function(t, b, c, d) { if((t /= d / 2) < 1) { return c / 2 * t * t * t * t * t + b; } return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }, /** * linear * @function * @memberof Kinetic.Easings */ 'Linear': function(t, b, c, d) { return c * t / d + b; } }; })(); ;(function() { Kinetic.DD = { // properties anim: new Kinetic.Animation(), isDragging: false, offset: { x: 0, y: 0 }, node: null, // methods _drag: function(evt) { var dd = Kinetic.DD, node = dd.node; if(node) { if(!dd.isDragging) { var pos = node.getStage().getPointerPosition(); var dragDistance = node.dragDistance(); var distance = Math.max( Math.abs(pos.x - dd.startPointerPos.x), Math.abs(pos.y - dd.startPointerPos.y) ); if (distance < dragDistance) { return; } } node._setDragPosition(evt); if(!dd.isDragging) { dd.isDragging = true; node.fire('dragstart', { type : 'dragstart', target : node, evt : evt }, true); } // execute ondragmove if defined node.fire('dragmove', { type : 'dragmove', target : node, evt : evt }, true); } }, _endDragBefore: function(evt) { var dd = Kinetic.DD, node = dd.node, nodeType, layer; if(node) { nodeType = node.nodeType; layer = node.getLayer(); dd.anim.stop(); // only fire dragend event if the drag and drop // operation actually started. if(dd.isDragging) { dd.isDragging = false; Kinetic.listenClickTap = false; if (evt) { evt.dragEndNode = node; } } delete dd.node; (layer || node).draw(); } }, _endDragAfter: function(evt) { evt = evt || {}; var dragEndNode = evt.dragEndNode; if (evt && dragEndNode) { dragEndNode.fire('dragend', { type : 'dragend', target : dragEndNode, evt : evt }, true); } } }; // Node extenders /** * initiate drag and drop * @method * @memberof Kinetic.Node.prototype */ Kinetic.Node.prototype.startDrag = function() { var dd = Kinetic.DD, stage = this.getStage(), layer = this.getLayer(), pos = stage.getPointerPosition(), ap = this.getAbsolutePosition(); if(pos) { if (dd.node) { dd.node.stopDrag(); } dd.node = this; dd.startPointerPos = pos; dd.offset.x = pos.x - ap.x; dd.offset.y = pos.y - ap.y; dd.anim.setLayers(layer || this.getLayers()); dd.anim.start(); this._setDragPosition(); } }; Kinetic.Node.prototype._setDragPosition = function(evt) { var dd = Kinetic.DD, pos = this.getStage().getPointerPosition(), dbf = this.getDragBoundFunc(); if (!pos) { return; } var newNodePos = { x: pos.x - dd.offset.x, y: pos.y - dd.offset.y }; if(dbf !== undefined) { newNodePos = dbf.call(this, newNodePos, evt); } this.setAbsolutePosition(newNodePos); }; /** * stop drag and drop * @method * @memberof Kinetic.Node.prototype */ Kinetic.Node.prototype.stopDrag = function() { var dd = Kinetic.DD, evt = {}; dd._endDragBefore(evt); dd._endDragAfter(evt); }; Kinetic.Node.prototype.setDraggable = function(draggable) { this._setAttr('draggable', draggable); this._dragChange(); }; var origDestroy = Kinetic.Node.prototype.destroy; Kinetic.Node.prototype.destroy = function() { var dd = Kinetic.DD; // stop DD if(dd.node && dd.node._id === this._id) { this.stopDrag(); } origDestroy.call(this); }; /** * determine if node is currently in drag and drop mode * @method * @memberof Kinetic.Node.prototype */ Kinetic.Node.prototype.isDragging = function() { var dd = Kinetic.DD; return dd.node && dd.node._id === this._id && dd.isDragging; }; Kinetic.Node.prototype._listenDrag = function() { var that = this; this._dragCleanup(); if (this.getClassName() === 'Stage') { this.on('contentMousedown.kinetic contentTouchstart.kinetic', function(evt) { if(!Kinetic.DD.node) { that.startDrag(evt); } }); } else { this.on('mousedown.kinetic touchstart.kinetic', function(evt) { if(!Kinetic.DD.node) { that.startDrag(evt); } }); } // listening is required for drag and drop /* this._listeningEnabled = true; this._clearSelfAndAncestorCache('listeningEnabled'); */ }; Kinetic.Node.prototype._dragChange = function() { if(this.attrs.draggable) { this._listenDrag(); } else { // remove event listeners this._dragCleanup(); /* * force drag and drop to end * if this node is currently in * drag and drop mode */ var stage = this.getStage(); var dd = Kinetic.DD; if(stage && dd.node && dd.node._id === this._id) { dd.node.stopDrag(); } } }; Kinetic.Node.prototype._dragCleanup = function() { if (this.getClassName() === 'Stage') { this.off('contentMousedown.kinetic'); this.off('contentTouchstart.kinetic'); } else { this.off('mousedown.kinetic'); this.off('touchstart.kinetic'); } }; Kinetic.Factory.addGetterSetter(Kinetic.Node, 'dragBoundFunc'); /** * get/set drag bound function. This is used to override the default * drag and drop position * @name dragBoundFunc * @method * @memberof Kinetic.Node.prototype * @param {Function} dragBoundFunc * @returns {Function} * @example * // get drag bound function<br> * var dragBoundFunc = node.dragBoundFunc();<br><br> * * // create vertical drag and drop<br> * node.dragBoundFunc(function(){<br> * return {<br> * x: this.getAbsolutePosition().x,<br> * y: pos.y<br> * };<br> * }); */ Kinetic.Factory.addGetter(Kinetic.Node, 'draggable', false); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Node, 'draggable'); /** * get/set draggable flag * @name draggable * @method * @memberof Kinetic.Node.prototype * @param {Boolean} draggable * @returns {Boolean} * @example * // get draggable flag<br> * var draggable = node.draggable();<br><br> * * // enable drag and drop<br> * node.draggable(true);<br><br> * * // disable drag and drop<br> * node.draggable(false); */ var html = Kinetic.document.documentElement; html.addEventListener('mouseup', Kinetic.DD._endDragBefore, true); html.addEventListener('touchend', Kinetic.DD._endDragBefore, true); html.addEventListener('mouseup', Kinetic.DD._endDragAfter, false); html.addEventListener('touchend', Kinetic.DD._endDragAfter, false); })(); ;(function() { Kinetic.Util.addMethods(Kinetic.Container, { __init: function(config) { this.children = new Kinetic.Collection(); Kinetic.Node.call(this, config); }, /** * returns a {@link Kinetic.Collection} of direct descendant nodes * @method * @memberof Kinetic.Container.prototype * @param {Function} [filterFunc] filter function * @returns {Kinetic.Collection} * @example * // get all children<br> * var children = layer.getChildren();<br><br> * * // get only circles<br> * var circles = layer.getChildren(function(node){<br> * return node.getClassName() === 'Circle';<br> * }); */ getChildren: function(predicate) { if (!predicate) { return this.children; } else { var results = new Kinetic.Collection(); this.children.each(function(child){ if (predicate(child)) { results.push(child); } }); return results; } }, /** * determine if node has children * @method * @memberof Kinetic.Container.prototype * @returns {Boolean} */ hasChildren: function() { return this.getChildren().length > 0; }, /** * remove all children * @method * @memberof Kinetic.Container.prototype */ removeChildren: function() { var children = Kinetic.Collection.toCollection(this.children); var child; for (var i = 0; i < children.length; i++) { child = children[i]; // reset parent to prevent many _setChildrenIndices calls delete child.parent; child.index = 0; if (child.hasChildren()) { child.removeChildren(); } child.remove(); } children = null; this.children = new Kinetic.Collection(); return this; }, /** * destroy all children * @method * @memberof Kinetic.Container.prototype */ destroyChildren: function() { var children = Kinetic.Collection.toCollection(this.children); var child; for (var i = 0; i < children.length; i++) { child = children[i]; // reset parent to prevent many _setChildrenIndices calls delete child.parent; child.index = 0; child.destroy(); } children = null; this.children = new Kinetic.Collection(); return this; }, /** * Add node or nodes to container. * @method * @memberof Kinetic.Container.prototype * @param {...Kinetic.Node} child * @returns {Container} * @example * layer.add(shape1, shape2, shape3); */ add: function(child) { if (arguments.length > 1) { for (var i = 0; i < arguments.length; i++) { this.add(arguments[i]); } return; } if (child.getParent()) { child.moveTo(this); return; } var children = this.children; this._validateAdd(child); child.index = children.length; child.parent = this; children.push(child); this._fire('add', { child: child }); // chainable return this; }, destroy: function() { // destroy children if (this.hasChildren()) { this.destroyChildren(); } // then destroy self Kinetic.Node.prototype.destroy.call(this); }, /** * return a {@link Kinetic.Collection} of nodes that match the selector. Use '#' for id selections * and '.' for name selections. You can also select by type or class name. Pass multiple selectors * separated by a space. * @method * @memberof Kinetic.Container.prototype * @param {String} selector * @returns {Collection} * @example * // select node with id foo<br> * var node = stage.find('#foo');<br><br> * * // select nodes with name bar inside layer<br> * var nodes = layer.find('.bar');<br><br> * * // select all groups inside layer<br> * var nodes = layer.find('Group');<br><br> * * // select all rectangles inside layer<br> * var nodes = layer.find('Rect');<br><br> * * // select node with an id of foo or a name of bar inside layer<br> * var nodes = layer.find('#foo, .bar'); */ find: function(selector) { var retArr = [], selectorArr = selector.replace(/ /g, '').split(','), len = selectorArr.length, n, i, sel, arr, node, children, clen; for (n = 0; n < len; n++) { sel = selectorArr[n]; // id selector if(sel.charAt(0) === '#') { node = this._getNodeById(sel.slice(1)); if(node) { retArr.push(node); } } // name selector else if(sel.charAt(0) === '.') { arr = this._getNodesByName(sel.slice(1)); retArr = retArr.concat(arr); } // unrecognized selector, pass to children else { children = this.getChildren(); clen = children.length; for(i = 0; i < clen; i++) { retArr = retArr.concat(children[i]._get(sel)); } } } return Kinetic.Collection.toCollection(retArr); }, _getNodeById: function(key) { var node = Kinetic.ids[key]; if(node !== undefined && this.isAncestorOf(node)) { return node; } return null; }, _getNodesByName: function(key) { var arr = Kinetic.names[key] || []; return this._getDescendants(arr); }, _get: function(selector) { var retArr = Kinetic.Node.prototype._get.call(this, selector); var children = this.getChildren(); var len = children.length; for(var n = 0; n < len; n++) { retArr = retArr.concat(children[n]._get(selector)); } return retArr; }, // extenders toObject: function() { var obj = Kinetic.Node.prototype.toObject.call(this); obj.children = []; var children = this.getChildren(); var len = children.length; for(var n = 0; n < len; n++) { var child = children[n]; obj.children.push(child.toObject()); } return obj; }, _getDescendants: function(arr) { var retArr = []; var len = arr.length; for(var n = 0; n < len; n++) { var node = arr[n]; if(this.isAncestorOf(node)) { retArr.push(node); } } return retArr; }, /** * determine if node is an ancestor * of descendant * @method * @memberof Kinetic.Container.prototype * @param {Kinetic.Node} node */ isAncestorOf: function(node) { var parent = node.getParent(); while(parent) { if(parent._id === this._id) { return true; } parent = parent.getParent(); } return false; }, clone: function(obj) { // call super method var node = Kinetic.Node.prototype.clone.call(this, obj); this.getChildren().each(function(no) { node.add(no.clone()); }); return node; }, /** * get all shapes that intersect a point. Note: because this method must clear a temporary * canvas and redraw every shape inside the container, it should only be used for special sitations * because it performs very poorly. Please use the {@link Kinetic.Stage#getIntersection} method if at all possible * because it performs much better * @method * @memberof Kinetic.Container.prototype * @param {Object} pos * @param {Number} pos.x * @param {Number} pos.y * @returns {Array} array of shapes */ getAllIntersections: function(pos) { var arr = []; this.find('Shape').each(function(shape) { if(shape.isVisible() && shape.intersects(pos)) { arr.push(shape); } }); return arr; }, _setChildrenIndices: function() { this.children.each(function(child, n) { child.index = n; }); }, drawScene: function(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()), context = canvas && canvas.getContext(), cachedCanvas = this._cache.canvas, cachedSceneCanvas = cachedCanvas && cachedCanvas.scene; if (this.isVisible()) { if (cachedSceneCanvas) { this._drawCachedSceneCanvas(context); } else { this._drawChildren(canvas, 'drawScene', top); } } return this; }, drawHit: function(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas), context = canvas && canvas.getContext(), cachedCanvas = this._cache.canvas, cachedHitCanvas = cachedCanvas && cachedCanvas.hit; if (this.shouldDrawHit()) { if (cachedHitCanvas) { this._drawCachedHitCanvas(context); } else { this._drawChildren(canvas, 'drawHit', top); } } return this; }, _drawChildren: function(canvas, drawMethod, top) { var layer = this.getLayer(), context = canvas && canvas.getContext(), clipWidth = this.getClipWidth(), clipHeight = this.getClipHeight(), hasClip = clipWidth && clipHeight, clipX, clipY; if (hasClip && layer) { clipX = this.getClipX(); clipY = this.getClipY(); context.save(); layer._applyTransform(this, context); context.beginPath(); context.rect(clipX, clipY, clipWidth, clipHeight); context.clip(); context.reset(); } this.children.each(function(child) { child[drawMethod](canvas, top); }); if (hasClip) { context.restore(); } } }); Kinetic.Util.extend(Kinetic.Container, Kinetic.Node); // deprecated methods Kinetic.Container.prototype.get = Kinetic.Container.prototype.find; // add getters setters Kinetic.Factory.addComponentsGetterSetter(Kinetic.Container, 'clip', ['x', 'y', 'width', 'height']); /** * get/set clip * @method * @name clip * @memberof Kinetic.Container.prototype * @param {Object} clip * @param {Number} clip.x * @param {Number} clip.y * @param {Number} clip.width * @param {Number} clip.height * @returns {Object} * @example * // get clip<br> * var clip = container.clip();<br><br> * * // set clip<br> * container.setClip({<br> * x: 20,<br> * y: 20,<br> * width: 20,<br> * height: 20<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipX'); /** * get/set clip x * @name clipX * @method * @memberof Kinetic.Container.prototype * @param {Number} x * @returns {Number} * @example * // get clip x<br> * var clipX = container.clipX();<br><br> * * // set clip x<br> * container.clipX(10); */ Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipY'); /** * get/set clip y * @name clipY * @method * @memberof Kinetic.Container.prototype * @param {Number} y * @returns {Number} * @example * // get clip y<br> * var clipY = container.clipY();<br><br> * * // set clip y<br> * container.clipY(10); */ Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipWidth'); /** * get/set clip width * @name clipWidth * @method * @memberof Kinetic.Container.prototype * @param {Number} width * @returns {Number} * @example * // get clip width<br> * var clipWidth = container.clipWidth();<br><br> * * // set clip width<br> * container.clipWidth(100); */ Kinetic.Factory.addGetterSetter(Kinetic.Container, 'clipHeight'); /** * get/set clip height * @name clipHeight * @method * @memberof Kinetic.Container.prototype * @param {Number} height * @returns {Number} * @example * // get clip height<br> * var clipHeight = container.clipHeight();<br><br> * * // set clip height<br> * container.clipHeight(100); */ Kinetic.Collection.mapMethods(Kinetic.Container); })(); ;(function() { var HAS_SHADOW = 'hasShadow'; function _fillFunc(context) { context.fill(); } function _strokeFunc(context) { context.stroke(); } function _fillFuncHit(context) { context.fill(); } function _strokeFuncHit(context) { context.stroke(); } function _clearHasShadowCache() { this._clearCache(HAS_SHADOW); } Kinetic.Util.addMethods(Kinetic.Shape, { __init: function(config) { this.nodeType = 'Shape'; this._fillFunc = _fillFunc; this._strokeFunc = _strokeFunc; this._fillFuncHit = _fillFuncHit; this._strokeFuncHit = _strokeFuncHit; // set colorKey var shapes = Kinetic.shapes; var key; while(true) { key = Kinetic.Util.getRandomColor(); if(key && !( key in shapes)) { break; } } this.colorKey = key; shapes[key] = this; // call super constructor Kinetic.Node.call(this, config); this.on('shadowColorChange.kinetic shadowBlurChange.kinetic shadowOffsetChange.kinetic shadowOpacityChange.kinetic shadowEnabledChange.kinetic', _clearHasShadowCache); }, hasChildren: function() { return false; }, getChildren: function() { return []; }, /** * get canvas context tied to the layer * @method * @memberof Kinetic.Shape.prototype * @returns {Kinetic.Context} */ getContext: function() { return this.getLayer().getContext(); }, /** * get canvas renderer tied to the layer. Note that this returns a canvas renderer, not a canvas element * @method * @memberof Kinetic.Shape.prototype * @returns {Kinetic.Canvas} */ getCanvas: function() { return this.getLayer().getCanvas(); }, /** * returns whether or not a shadow will be rendered * @method * @memberof Kinetic.Shape.prototype * @returns {Boolean} */ hasShadow: function() { return this._getCache(HAS_SHADOW, this._hasShadow); }, _hasShadow: function() { return this.getShadowEnabled() && (this.getShadowOpacity() !== 0 && !!(this.getShadowColor() || this.getShadowBlur() || this.getShadowOffsetX() || this.getShadowOffsetY())); }, /** * returns whether or not the shape will be filled * @method * @memberof Kinetic.Shape.prototype * @returns {Boolean} */ hasFill: function() { return !!(this.getFill() || this.getFillPatternImage() || this.getFillLinearGradientColorStops() || this.getFillRadialGradientColorStops()); }, /** * returns whether or not the shape will be stroked * @method * @memberof Kinetic.Shape.prototype * @returns {Boolean} */ hasStroke: function() { return !!(this.stroke() || this.strokeRed() || this.strokeGreen() || this.strokeBlue()); }, _get: function(selector) { return this.className === selector || this.nodeType === selector ? [this] : []; }, /** * determines if point is in the shape, regardless if other shapes are on top of it. Note: because * this method clears a temporary canvas and then redraws the shape, it performs very poorly if executed many times * consecutively. Please use the {@link Kinetic.Stage#getIntersection} method if at all possible * because it performs much better * @method * @memberof Kinetic.Shape.prototype * @param {Object} point * @param {Number} point.x * @param {Number} point.y * @returns {Boolean} */ intersects: function(pos) { var stage = this.getStage(), bufferHitCanvas = stage.bufferHitCanvas, p; bufferHitCanvas.getContext().clear(); this.drawScene(bufferHitCanvas); p = bufferHitCanvas.context.getImageData(Math.round(pos.x), Math.round(pos.y), 1, 1).data; return p[3] > 0; }, // extends Node.prototype.destroy destroy: function() { Kinetic.Node.prototype.destroy.call(this); delete Kinetic.shapes[this.colorKey]; }, _useBufferCanvas: function() { return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasFill() && this.hasStroke() && this.getStage(); }, drawScene: function(can, top) { var layer = this.getLayer(), canvas = can || layer.getCanvas(), context = canvas.getContext(), cachedCanvas = this._cache.canvas, drawFunc = this.sceneFunc(), hasShadow = this.hasShadow(), stage, bufferCanvas, bufferContext; if(this.isVisible()) { if (cachedCanvas) { this._drawCachedSceneCanvas(context); } else if (drawFunc) { context.save(); // if buffer canvas is needed if (this._useBufferCanvas()) { stage = this.getStage(); bufferCanvas = stage.bufferCanvas; bufferContext = bufferCanvas.getContext(); bufferContext.clear(); bufferContext.save(); bufferContext._applyLineJoin(this); layer._applyTransform(this, bufferContext, top); drawFunc.call(this, bufferContext); bufferContext.restore(); if (hasShadow) { context.save(); context._applyShadow(this); context.drawImage(bufferCanvas._canvas, 0, 0); context.restore(); } context._applyOpacity(this); context.drawImage(bufferCanvas._canvas, 0, 0); } // if buffer canvas is not needed else { context._applyLineJoin(this); layer._applyTransform(this, context, top); if (hasShadow) { context.save(); context._applyShadow(this); drawFunc.call(this, context); context.restore(); } context._applyOpacity(this); drawFunc.call(this, context); } context.restore(); } } return this; }, drawHit: function(can, top) { var layer = this.getLayer(), canvas = can || layer.hitCanvas, context = canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), cachedCanvas = this._cache.canvas, cachedHitCanvas = cachedCanvas && cachedCanvas.hit; if(this.shouldDrawHit()) { if (cachedHitCanvas) { this._drawCachedHitCanvas(context); } else if (drawFunc) { context.save(); context._applyLineJoin(this); layer._applyTransform(this, context, top); drawFunc.call(this, context); context.restore(); } } return this; }, /** * draw hit graph using the cached scene canvas * @method * @memberof Kinetic.Shape.prototype * @param {Integer} alphaThreshold alpha channel threshold that determines whether or not * a pixel should be drawn onto the hit graph. Must be a value between 0 and 255. * The default is 0 * @returns {Kinetic.Shape} * @example * shape.cache(); * shape.drawHitFromCache(); */ drawHitFromCache: function(alphaThreshold) { var threshold = alphaThreshold || 0, cachedCanvas = this._cache.canvas, sceneCanvas = this._getCachedSceneCanvas(), sceneContext = sceneCanvas.getContext(), hitCanvas = cachedCanvas.hit, hitContext = hitCanvas.getContext(), width = sceneCanvas.getWidth(), height = sceneCanvas.getHeight(), sceneImageData, sceneData, hitImageData, hitData, len, rgbColorKey, i, alpha; hitContext.clear(); try { sceneImageData = sceneContext.getImageData(0, 0, width, height); sceneData = sceneImageData.data; hitImageData = hitContext.getImageData(0, 0, width, height); hitData = hitImageData.data; len = sceneData.length; rgbColorKey = Kinetic.Util._hexToRgb(this.colorKey); // replace non transparent pixels with color key for(i = 0; i < len; i += 4) { alpha = sceneData[i + 3]; if (alpha > threshold) { hitData[i] = rgbColorKey.r; hitData[i + 1] = rgbColorKey.g; hitData[i + 2] = rgbColorKey.b; hitData[i + 3] = 255; } } hitContext.putImageData(hitImageData, 0, 0); } catch(e) { Kinetic.Util.warn('Unable to draw hit graph from cached scene canvas. ' + e.message); } return this; }, }); Kinetic.Util.extend(Kinetic.Shape, Kinetic.Node); // add getters and setters Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'stroke'); /** * get/set stroke color * @name stroke * @method * @memberof Kinetic.Shape.prototype * @param {String} color * @returns {String} * @example * // get stroke color<br> * var stroke = shape.stroke();<br><br> * * // set stroke color with color string<br> * shape.stroke('green');<br><br> * * // set stroke color with hex<br> * shape.stroke('#00ff00');<br><br> * * // set stroke color with rgb<br> * shape.stroke('rgb(0,255,0)');<br><br> * * // set stroke color with rgba and make it 50% opaque<br> * shape.stroke('rgba(0,255,0,0.5'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeRed', 0, Kinetic.Validators.RGBComponent); /** * get/set stroke red component * @name strokeRed * @method * @memberof Kinetic.Shape.prototype * @param {Integer} red * @returns {Integer} * @example * // get stroke red component<br> * var strokeRed = shape.strokeRed();<br><br> * * // set stroke red component<br> * shape.strokeRed(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeGreen', 0, Kinetic.Validators.RGBComponent); /** * get/set stroke green component * @name strokeGreen * @method * @memberof Kinetic.Shape.prototype * @param {Integer} green * @returns {Integer} * @example * // get stroke green component<br> * var strokeGreen = shape.strokeGreen();<br><br> * * // set stroke green component<br> * shape.strokeGreen(255); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeBlue', 0, Kinetic.Validators.RGBComponent); /** * get/set stroke blue component * @name strokeBlue * @method * @memberof Kinetic.Shape.prototype * @param {Integer} blue * @returns {Integer} * @example * // get stroke blue component<br> * var strokeBlue = shape.strokeBlue();<br><br> * * // set stroke blue component<br> * shape.strokeBlue(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeAlpha', 1, Kinetic.Validators.alphaComponent); /** * get/set stroke alpha component. Alpha is a real number between 0 and 1. The default * is 1. * @name strokeAlpha * @method * @memberof Kinetic.Shape.prototype * @param {Number} alpha * @returns {Number} * @example * // get stroke alpha component<br> * var strokeAlpha = shape.strokeAlpha();<br><br> * * // set stroke alpha component<br> * shape.strokeAlpha(0.5); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeWidth', 2); /** * get/set stroke width * @name strokeWidth * @method * @memberof Kinetic.Shape.prototype * @param {Number} strokeWidth * @returns {Number} * @example * // get stroke width<br> * var strokeWidth = shape.strokeWidth();<br><br> * * // set stroke width<br> * shape.strokeWidth(); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'lineJoin'); /** * get/set line join. Can be miter, round, or bevel. The * default is miter * @name lineJoin * @method * @memberof Kinetic.Shape.prototype * @param {String} lineJoin * @returns {String} * @example * // get line join<br> * var lineJoin = shape.lineJoin();<br><br> * * // set line join<br> * shape.lineJoin('round'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'lineCap'); /** * get/set line cap. Can be butt, round, or square * @name lineCap * @method * @memberof Kinetic.Shape.prototype * @param {String} lineCap * @returns {String} * @example * // get line cap<br> * var lineCap = shape.lineCap();<br><br> * * // set line cap<br> * shape.lineCap('round'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'sceneFunc'); /** * get/set scene draw function * @name sceneFunc * @method * @memberof Kinetic.Shape.prototype * @param {Function} drawFunc drawing function * @returns {Function} * @example * // get scene draw function<br> * var sceneFunc = shape.sceneFunc();<br><br> * * // set scene draw function<br> * shape.sceneFunc(function(context) {<br> * context.beginPath();<br> * context.rect(0, 0, this.width(), this.height());<br> * context.closePath();<br> * context.fillStrokeShape(this);<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'hitFunc'); /** * get/set hit draw function * @name hitFunc * @method * @memberof Kinetic.Shape.prototype * @param {Function} drawFunc drawing function * @returns {Function} * @example * // get hit draw function<br> * var hitFunc = shape.hitFunc();<br><br> * * // set hit draw function<br> * shape.hitFunc(function(context) {<br> * context.beginPath();<br> * context.rect(0, 0, this.width(), this.height());<br> * context.closePath();<br> * context.fillStrokeShape(this);<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'dash'); /** * get/set dash array for stroke. * @name dash * @method * @memberof Kinetic.Shape.prototype * @param {Array} dash * @returns {Array} * @example * // apply dashed stroke that is 10px long and 5 pixels apart<br> * line.dash([10, 5]);<br><br> * * // apply dashed stroke that is made up of alternating dashed<br> * // lines that are 10px long and 20px apart, and dots that have<br> * // a radius of 5px and are 20px apart<br> * line.dash([10, 20, 0.001, 20]); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowColor'); /** * get/set shadow color * @name shadowColor * @method * @memberof Kinetic.Shape.prototype * @param {String} color * @returns {String} * @example * // get shadow color<br> * var shadow = shape.shadowColor();<br><br> * * // set shadow color with color string<br> * shape.shadowColor('green');<br><br> * * // set shadow color with hex<br> * shape.shadowColor('#00ff00');<br><br> * * // set shadow color with rgb<br> * shape.shadowColor('rgb(0,255,0)');<br><br> * * // set shadow color with rgba and make it 50% opaque<br> * shape.shadowColor('rgba(0,255,0,0.5'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowRed', 0, Kinetic.Validators.RGBComponent); /** * get/set shadow red component * @name shadowRed * @method * @memberof Kinetic.Shape.prototype * @param {Integer} red * @returns {Integer} * @example * // get shadow red component<br> * var shadowRed = shape.shadowRed();<br><br> * * // set shadow red component<br> * shape.shadowRed(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowGreen', 0, Kinetic.Validators.RGBComponent); /** * get/set shadow green component * @name shadowGreen * @method * @memberof Kinetic.Shape.prototype * @param {Integer} green * @returns {Integer} * @example * // get shadow green component<br> * var shadowGreen = shape.shadowGreen();<br><br> * * // set shadow green component<br> * shape.shadowGreen(255); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowBlue', 0, Kinetic.Validators.RGBComponent); /** * get/set shadow blue component * @name shadowBlue * @method * @memberof Kinetic.Shape.prototype * @param {Integer} blue * @returns {Integer} * @example * // get shadow blue component<br> * var shadowBlue = shape.shadowBlue();<br><br> * * // set shadow blue component<br> * shape.shadowBlue(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowAlpha', 1, Kinetic.Validators.alphaComponent); /** * get/set shadow alpha component. Alpha is a real number between 0 and 1. The default * is 1. * @name shadowAlpha * @method * @memberof Kinetic.Shape.prototype * @param {Number} alpha * @returns {Number} * @example * // get shadow alpha component<br> * var shadowAlpha = shape.shadowAlpha();<br><br> * * // set shadow alpha component<br> * shape.shadowAlpha(0.5); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowBlur'); /** * get/set shadow blur * @name shadowBlur * @method * @memberof Kinetic.Shape.prototype * @param {Number} blur * @returns {Number} * @example * // get shadow blur<br> * var shadowBlur = shape.shadowBlur();<br><br> * * // set shadow blur<br> * shape.shadowBlur(10); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOpacity'); /** * get/set shadow opacity. must be a value between 0 and 1 * @name shadowOpacity * @method * @memberof Kinetic.Shape.prototype * @param {Number} opacity * @returns {Number} * @example * // get shadow opacity<br> * var shadowOpacity = shape.shadowOpacity();<br><br> * * // set shadow opacity<br> * shape.shadowOpacity(0.5); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'shadowOffset', ['x', 'y']); /** * get/set shadow offset * @name shadowOffset * @method * @memberof Kinetic.Shape.prototype * @param {Object} offset * @param {Number} offset.x * @param {Number} offset.y * @returns {Object} * @example * // get shadow offset<br> * var shadowOffset = shape.shadowOffset();<br><br> * * // set shadow offset<br> * shape.shadowOffset({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOffsetX', 0); /** * get/set shadow offset x * @name shadowOffsetX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get shadow offset x<br> * var shadowOffsetX = shape.shadowOffsetX();<br><br> * * // set shadow offset x<br> * shape.shadowOffsetX(5); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowOffsetY', 0); /** * get/set shadow offset y * @name shadowOffsetY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get shadow offset y<br> * var shadowOffsetY = shape.shadowOffsetY();<br><br> * * // set shadow offset y<br> * shape.shadowOffsetY(5); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternImage'); /** * get/set fill pattern image * @name fillPatternImage * @method * @memberof Kinetic.Shape.prototype * @param {Image} image object * @returns {Image} * @example * // get fill pattern image<br> * var fillPatternImage = shape.fillPatternImage();<br><br> * * // set fill pattern image<br> * var imageObj = new Image();<br> * imageObj.onload = function() {<br> * shape.fillPatternImage(imageObj);<br> * };<br> * imageObj.src = 'path/to/image/jpg'; */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fill'); /** * get/set fill color * @name fill * @method * @memberof Kinetic.Shape.prototype * @param {String} color * @returns {String} * @example * // get fill color<br> * var fill = shape.fill();<br><br> * * // set fill color with color string<br> * shape.fill('green');<br><br> * * // set fill color with hex<br> * shape.fill('#00ff00');<br><br> * * // set fill color with rgb<br> * shape.fill('rgb(0,255,0)');<br><br> * * // set fill color with rgba and make it 50% opaque<br> * shape.fill('rgba(0,255,0,0.5'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRed', 0, Kinetic.Validators.RGBComponent); /** * get/set fill red component * @name fillRed * @method * @memberof Kinetic.Shape.prototype * @param {Integer} red * @returns {Integer} * @example * // get fill red component<br> * var fillRed = shape.fillRed();<br><br> * * // set fill red component<br> * shape.fillRed(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillGreen', 0, Kinetic.Validators.RGBComponent); /** * get/set fill green component * @name fillGreen * @method * @memberof Kinetic.Shape.prototype * @param {Integer} green * @returns {Integer} * @example * // get fill green component<br> * var fillGreen = shape.fillGreen();<br><br> * * // set fill green component<br> * shape.fillGreen(255); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillBlue', 0, Kinetic.Validators.RGBComponent); /** * get/set fill blue component * @name fillBlue * @method * @memberof Kinetic.Shape.prototype * @param {Integer} blue * @returns {Integer} * @example * // get fill blue component<br> * var fillBlue = shape.fillBlue();<br><br> * * // set fill blue component<br> * shape.fillBlue(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillAlpha', 1, Kinetic.Validators.alphaComponent); /** * get/set fill alpha component. Alpha is a real number between 0 and 1. The default * is 1. * @name fillAlpha * @method * @memberof Kinetic.Shape.prototype * @param {Number} alpha * @returns {Number} * @example * // get fill alpha component<br> * var fillAlpha = shape.fillAlpha();<br><br> * * // set fill alpha component<br> * shape.fillAlpha(0.5); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternX', 0); /** * get/set fill pattern x * @name fillPatternX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill pattern x<br> * var fillPatternX = shape.fillPatternX();<br><br> * * // set fill pattern x<br> * shape.fillPatternX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternY', 0); /** * get/set fill pattern y * @name fillPatternY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill pattern y<br> * var fillPatternY = shape.fillPatternY();<br><br> * * // set fill pattern y<br> * shape.fillPatternY(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientColorStops'); /** * get/set fill linear gradient color stops * @name fillLinearGradientColorStops * @method * @memberof Kinetic.Shape.prototype * @param {Array} colorStops * @returns {Array} colorStops * @example * // get fill linear gradient color stops<br> * var colorStops = shape.fillLinearGradientColorStops();<br><br> * * // create a linear gradient that starts with red, changes to blue <br> * // halfway through, and then changes to green<br> * shape.fillLinearGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartRadius', 0); /** * get/set fill radial gradient start radius * @name fillRadialGradientStartRadius * @method * @memberof Kinetic.Shape.prototype * @param {Number} radius * @returns {Number} * @example * // get radial gradient start radius<br> * var startRadius = shape.fillRadialGradientStartRadius();<br><br> * * // set radial gradient start radius<br> * shape.fillRadialGradientStartRadius(0); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndRadius', 0); /** * get/set fill radial gradient end radius * @name fillRadialGradientEndRadius * @method * @memberof Kinetic.Shape.prototype * @param {Number} radius * @returns {Number} * @example * // get radial gradient end radius<br> * var endRadius = shape.fillRadialGradientEndRadius();<br><br> * * // set radial gradient end radius<br> * shape.fillRadialGradientEndRadius(100); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientColorStops'); /** * get/set fill radial gradient color stops * @name fillRadialGradientColorStops * @method * @memberof Kinetic.Shape.prototype * @param {Number} colorStops * @returns {Array} * @example * // get fill radial gradient color stops<br> * var colorStops = shape.fillRadialGradientColorStops();<br><br> * * // create a radial gradient that starts with red, changes to blue <br> * // halfway through, and then changes to green<br> * shape.fillRadialGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternRepeat', 'repeat'); /** * get/set fill pattern repeat. Can be 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'. The default is 'repeat' * @name fillPatternRepeat * @method * @memberof Kinetic.Shape.prototype * @param {String} repeat * @returns {String} * @example * // get fill pattern repeat<br> * var repeat = shape.fillPatternRepeat();<br><br> * * // repeat pattern in x direction only<br> * shape.fillPatternRepeat('repeat-x');<br><br> * * // do not repeat the pattern<br> * shape.fillPatternRepeat('no repeat'); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillEnabled', true); /** * get/set fill enabled flag * @name fillEnabled * @method * @memberof Kinetic.Shape.prototype * @param {Boolean} enabled * @returns {Boolean} * @example * // get fill enabled flag<br> * var fillEnabled = shape.fillEnabled();<br><br> * * // disable fill<br> * shape.fillEnabled(false);<br><br> * * // enable fill<br> * shape.fillEnabled(true); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeEnabled', true); /** * get/set stroke enabled flag * @name strokeEnabled * @method * @memberof Kinetic.Shape.prototype * @param {Boolean} enabled * @returns {Boolean} * @example * // get stroke enabled flag<br> * var strokeEnabled = shape.strokeEnabled();<br><br> * * // disable stroke<br> * shape.strokeEnabled(false);<br><br> * * // enable stroke<br> * shape.strokeEnabled(true); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'shadowEnabled', true); /** * get/set shadow enabled flag * @name shadowEnabled * @method * @memberof Kinetic.Shape.prototype * @param {Boolean} enabled * @returns {Boolean} * @example * // get shadow enabled flag<br> * var shadowEnabled = shape.shadowEnabled();<br><br> * * // disable shadow<br> * shape.shadowEnabled(false);<br><br> * * // enable shadow<br> * shape.shadowEnabled(true); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'dashEnabled', true); /** * get/set dash enabled flag * @name dashEnabled * @method * @memberof Kinetic.Shape.prototype * @param {Boolean} enabled * @returns {Boolean} * @example * // get dash enabled flag<br> * var dashEnabled = shape.dashEnabled();<br><br> * * // disable dash<br> * shape.dashEnabled(false);<br><br> * * // enable dash<br> * shape.dashEnabled(true); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'strokeScaleEnabled', true); /** * get/set strokeScale enabled flag * @name strokeScaleEnabled * @method * @memberof Kinetic.Shape.prototype * @param {Boolean} enabled * @returns {Boolean} * @example * // get stroke scale enabled flag<br> * var strokeScaleEnabled = shape.strokeScaleEnabled();<br><br> * * // disable stroke scale<br> * shape.strokeScaleEnabled(false);<br><br> * * // enable stroke scale<br> * shape.strokeScaleEnabled(true); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPriority', 'color'); /** * get/set fill priority. can be color, pattern, linear-gradient, or radial-gradient. The default is color. * This is handy if you want to toggle between different fill types. * @name fillPriority * @method * @memberof Kinetic.Shape.prototype * @param {String} priority * @returns {String} * @example * // get fill priority<br> * var fillPriority = shape.fillPriority();<br><br> * * // set fill priority<br> * shape.fillPriority('linear-gradient'); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillPatternOffset', ['x', 'y']); /** * get/set fill pattern offset * @name fillPatternOffset * @method * @memberof Kinetic.Shape.prototype * @param {Object} offset * @param {Number} offset.x * @param {Number} offset.y * @returns {Object} * @example * // get fill pattern offset<br> * var patternOffset = shape.fillPatternOffset();<br><br> * * // set fill pattern offset<br> * shape.fillPatternOffset({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternOffsetX', 0); /** * get/set fill pattern offset x * @name fillPatternOffsetX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill pattern offset x<br> * var patternOffsetX = shape.fillPatternOffsetX();<br><br> * * // set fill pattern offset x<br> * shape.fillPatternOffsetX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternOffsetY', 0); /** * get/set fill pattern offset y * @name fillPatternOffsetY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill pattern offset y<br> * var patternOffsetY = shape.fillPatternOffsetY();<br><br> * * // set fill pattern offset y<br> * shape.fillPatternOffsetY(10); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillPatternScale', ['x', 'y']); /** * get/set fill pattern scale * @name fillPatternScale * @method * @memberof Kinetic.Shape.prototype * @param {Object} scale * @param {Number} scale.x * @param {Number} scale.y * @returns {Object} * @example * // get fill pattern scale<br> * var patternScale = shape.fillPatternScale();<br><br> * * // set fill pattern scale<br> * shape.fillPatternScale({<br> * x: 2<br> * y: 2<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternScaleX', 1); /** * get/set fill pattern scale x * @name fillPatternScaleX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill pattern scale x<br> * var patternScaleX = shape.fillPatternScaleX();<br><br> * * // set fill pattern scale x<br> * shape.fillPatternScaleX(2); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternScaleY', 1); /** * get/set fill pattern scale y * @name fillPatternScaleY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill pattern scale y<br> * var patternScaleY = shape.fillPatternScaleY();<br><br> * * // set fill pattern scale y<br> * shape.fillPatternScaleY(2); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPoint', ['x', 'y']); /** * get/set fill linear gradient start point * @name fillLinearGradientStartPoint * @method * @memberof Kinetic.Shape.prototype * @param {Object} startPoint * @param {Number} startPoint.x * @param {Number} startPoint.y * @returns {Object} * @example * // get fill linear gradient start point<br> * var startPoint = shape.fillLinearGradientStartPoint();<br><br> * * // set fill linear gradient start point<br> * shape.fillLinearGradientStartPoint({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPointX', 0); /** * get/set fill linear gradient start point x * @name fillLinearGradientStartPointX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill linear gradient start point x<br> * var startPointX = shape.fillLinearGradientStartPointX();<br><br> * * // set fill linear gradient start point x<br> * shape.fillLinearGradientStartPointX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientStartPointY', 0); /** * get/set fill linear gradient start point y * @name fillLinearGradientStartPointY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill linear gradient start point y<br> * var startPointY = shape.fillLinearGradientStartPointY();<br><br> * * // set fill linear gradient start point y<br> * shape.fillLinearGradientStartPointY(20); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPoint', ['x', 'y']); /** * get/set fill linear gradient end point * @name fillLinearGradientEndPoint * @method * @memberof Kinetic.Shape.prototype * @param {Object} endPoint * @param {Number} endPoint.x * @param {Number} endPoint.y * @returns {Object} * @example * // get fill linear gradient end point<br> * var endPoint = shape.fillLinearGradientEndPoint();<br><br> * * // set fill linear gradient end point<br> * shape.fillLinearGradientEndPoint({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPointX', 0); /** * get/set fill linear gradient end point x * @name fillLinearGradientEndPointX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill linear gradient end point x<br> * var endPointX = shape.fillLinearGradientEndPointX();<br><br> * * // set fill linear gradient end point x<br> * shape.fillLinearGradientEndPointX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillLinearGradientEndPointY', 0); /** * get/set fill linear gradient end point y * @name fillLinearGradientEndPointY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill linear gradient end point y<br> * var endPointY = shape.fillLinearGradientEndPointY();<br><br> * * // set fill linear gradient end point y<br> * shape.fillLinearGradientEndPointY(20); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPoint', ['x', 'y']); /** * get/set fill radial gradient start point * @name fillRadialGradientStartPoint * @method * @memberof Kinetic.Shape.prototype * @param {Object} startPoint * @param {Number} startPoint.x * @param {Number} startPoint.y * @returns {Object} * @example * // get fill radial gradient start point<br> * var startPoint = shape.fillRadialGradientStartPoint();<br><br> * * // set fill radial gradient start point<br> * shape.fillRadialGradientStartPoint({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPointX', 0); /** * get/set fill radial gradient start point x * @name fillRadialGradientStartPointX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill radial gradient start point x<br> * var startPointX = shape.fillRadialGradientStartPointX();<br><br> * * // set fill radial gradient start point x<br> * shape.fillRadialGradientStartPointX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientStartPointY', 0); /** * get/set fill radial gradient start point y * @name fillRadialGradientStartPointY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill radial gradient start point y<br> * var startPointY = shape.fillRadialGradientStartPointY();<br><br> * * // set fill radial gradient start point y<br> * shape.fillRadialGradientStartPointY(20); */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPoint', ['x', 'y']); /** * get/set fill radial gradient end point * @name fillRadialGradientEndPoint * @method * @memberof Kinetic.Shape.prototype * @param {Object} endPoint * @param {Number} endPoint.x * @param {Number} endPoint.y * @returns {Object} * @example * // get fill radial gradient end point<br> * var endPoint = shape.fillRadialGradientEndPoint();<br><br> * * // set fill radial gradient end point<br> * shape.fillRadialGradientEndPoint({<br> * x: 20<br> * y: 10<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPointX', 0); /** * get/set fill radial gradient end point x * @name fillRadialGradientEndPointX * @method * @memberof Kinetic.Shape.prototype * @param {Number} x * @returns {Number} * @example * // get fill radial gradient end point x<br> * var endPointX = shape.fillRadialGradientEndPointX();<br><br> * * // set fill radial gradient end point x<br> * shape.fillRadialGradientEndPointX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillRadialGradientEndPointY', 0); /** * get/set fill radial gradient end point y * @name fillRadialGradientEndPointY * @method * @memberof Kinetic.Shape.prototype * @param {Number} y * @returns {Number} * @example * // get fill radial gradient end point y<br> * var endPointY = shape.fillRadialGradientEndPointY();<br><br> * * // set fill radial gradient end point y<br> * shape.fillRadialGradientEndPointY(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Shape, 'fillPatternRotation', 0); /** * get/set fill pattern rotation in degrees * @name fillPatternRotation * @method * @memberof Kinetic.Shape.prototype * @param {Number} rotation * @returns {Kinetic.Shape} * @example * // get fill pattern rotation<br> * var patternRotation = shape.fillPatternRotation();<br><br> * * // set fill pattern rotation<br> * shape.fillPatternRotation(20); */ Kinetic.Factory.backCompat(Kinetic.Shape, { dashArray: 'dash', getDashArray: 'getDash', setDashArray: 'getDash', drawFunc: 'sceneFunc', getDrawFunc: 'getSceneFunc', setDrawFunc: 'setSceneFunc', drawHitFunc: 'hitFunc', getDrawHitFunc: 'getHitFunc', setDrawHitFunc: 'setHitFunc' }); Kinetic.Collection.mapMethods(Kinetic.Shape); })(); ;/*jshint unused:false */ (function() { // CONSTANTS var STAGE = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', MOUSELEAVE = 'mouseleave', MOUSEOVER = 'mouseover', MOUSEENTER = 'mouseenter', MOUSEMOVE = 'mousemove', MOUSEDOWN = 'mousedown', MOUSEUP = 'mouseup', CLICK = 'click', DBL_CLICK = 'dblclick', TOUCHSTART = 'touchstart', TOUCHEND = 'touchend', TAP = 'tap', DBL_TAP = 'dbltap', TOUCHMOVE = 'touchmove', CONTENT_MOUSEOUT = 'contentMouseout', CONTENT_MOUSELEAVE = 'contentMouseleave', CONTENT_MOUSEOVER = 'contentMouseover', CONTENT_MOUSEENTER = 'contentMouseenter', CONTENT_MOUSEMOVE = 'contentMousemove', CONTENT_MOUSEDOWN = 'contentMousedown', CONTENT_MOUSEUP = 'contentMouseup', CONTENT_CLICK = 'contentClick', CONTENT_DBL_CLICK = 'contentDblclick', CONTENT_TOUCHSTART = 'contentTouchstart', CONTENT_TOUCHEND = 'contentTouchend', CONTENT_TAP = 'contentTap', CONTENT_DBL_TAP = 'contentDbltap', CONTENT_TOUCHMOVE = 'contentTouchmove', DIV = 'div', RELATIVE = 'relative', INLINE_BLOCK = 'inline-block', KINETICJS_CONTENT = 'kineticjs-content', SPACE = ' ', UNDERSCORE = '_', CONTAINER = 'container', EMPTY_STRING = '', EVENTS = [MOUSEDOWN, MOUSEMOVE, MOUSEUP, MOUSEOUT, TOUCHSTART, TOUCHMOVE, TOUCHEND, MOUSEOVER], // cached variables eventsLength = EVENTS.length; function addEvent(ctx, eventName) { ctx.content.addEventListener(eventName, function(evt) { ctx[UNDERSCORE + eventName](evt); }, false); } Kinetic.Util.addMethods(Kinetic.Stage, { ___init: function(config) { this.nodeType = STAGE; // call super constructor Kinetic.Container.call(this, config); this._id = Kinetic.idCounter++; this._buildDOM(); this._bindContentEvents(); this._enableNestedTransforms = false; Kinetic.stages.push(this); }, _validateAdd: function(child) { if (child.getType() !== 'Layer') { Kinetic.Util.error('You may only add layers to the stage.'); } }, /** * set container dom element which contains the stage wrapper div element * @method * @memberof Kinetic.Stage.prototype * @param {DomElement} container can pass in a dom element or id string */ setContainer: function(container) { if( typeof container === STRING) { var id = container; container = Kinetic.document.getElementById(container); if (!container) { throw 'Can not find container in document with id ' + id; } } this._setAttr(CONTAINER, container); return this; }, shouldDrawHit: function() { return true; }, draw: function() { Kinetic.Node.prototype.draw.call(this); return this; }, /** * draw layer scene graphs * @name draw * @method * @memberof Kinetic.Stage.prototype */ /** * draw layer hit graphs * @name drawHit * @method * @memberof Kinetic.Stage.prototype */ /** * set height * @method * @memberof Kinetic.Stage.prototype * @param {Number} height */ setHeight: function(height) { Kinetic.Node.prototype.setHeight.call(this, height); this._resizeDOM(); return this; }, /** * set width * @method * @memberof Kinetic.Stage.prototype * @param {Number} width */ setWidth: function(width) { Kinetic.Node.prototype.setWidth.call(this, width); this._resizeDOM(); return this; }, /** * clear all layers * @method * @memberof Kinetic.Stage.prototype */ clear: function() { var layers = this.children, len = layers.length, n; for(n = 0; n < len; n++) { layers[n].clear(); } return this; }, clone: function(obj) { if (!obj) { obj = {}; } obj.container = Kinetic.document.createElement(DIV); return Kinetic.Container.prototype.clone.call(this, obj); }, /** * destroy stage * @method * @memberof Kinetic.Stage.prototype */ destroy: function() { var content = this.content; Kinetic.Container.prototype.destroy.call(this); if(content && Kinetic.Util._isInDocument(content)) { this.getContainer().removeChild(content); } var index = Kinetic.stages.indexOf(this); if (index > -1) { Kinetic.stages.splice(index, 1); } }, /** * get pointer position which can be a touch position or mouse position * @method * @memberof Kinetic.Stage.prototype * @returns {Object} */ getPointerPosition: function() { return this.pointerPos; }, getStage: function() { return this; }, /** * get stage content div element which has the * the class name "kineticjs-content" * @method * @memberof Kinetic.Stage.prototype */ getContent: function() { return this.content; }, /** * Creates a composite data URL and requires a callback because the composite is generated asynchronously. * @method * @memberof Kinetic.Stage.prototype * @param {Object} config * @param {Function} config.callback function executed when the composite has completed * @param {String} [config.mimeType] can be "image/png" or "image/jpeg". * "image/png" is the default * @param {Number} [config.x] x position of canvas section * @param {Number} [config.y] y position of canvas section * @param {Number} [config.width] width of canvas section * @param {Number} [config.height] height of canvas section * @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType, * you can specify the quality from 0 to 1, where 0 is very poor quality and 1 * is very high quality */ toDataURL: function(config) { config = config || {}; var mimeType = config.mimeType || null, quality = config.quality || null, x = config.x || 0, y = config.y || 0, canvas = new Kinetic.SceneCanvas({ width: config.width || this.getWidth(), height: config.height || this.getHeight(), pixelRatio: 1 }), _context = canvas.getContext()._context, layers = this.children; if(x || y) { _context.translate(-1 * x, -1 * y); } function drawLayer(n) { var layer = layers[n], layerUrl = layer.toDataURL(), imageObj = new Kinetic.window.Image(); imageObj.onload = function() { _context.drawImage(imageObj, 0, 0); if(n < layers.length - 1) { drawLayer(n + 1); } else { config.callback(canvas.toDataURL(mimeType, quality)); } }; imageObj.src = layerUrl; } drawLayer(0); }, /** * converts stage into an image. * @method * @memberof Kinetic.Stage.prototype * @param {Object} config * @param {Function} config.callback function executed when the composite has completed * @param {String} [config.mimeType] can be "image/png" or "image/jpeg". * "image/png" is the default * @param {Number} [config.x] x position of canvas section * @param {Number} [config.y] y position of canvas section * @param {Number} [config.width] width of canvas section * @param {Number} [config.height] height of canvas section * @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType, * you can specify the quality from 0 to 1, where 0 is very poor quality and 1 * is very high quality */ toImage: function(config) { var cb = config.callback; config.callback = function(dataUrl) { Kinetic.Util._getImage(dataUrl, function(img) { cb(img); }); }; this.toDataURL(config); }, /** * get visible intersection shape. This is the preferred * method for determining if a point intersects a shape or not * @method * @memberof Kinetic.Stage.prototype * @param {Object} pos * @param {Number} pos.x * @param {Number} pos.y * @returns {Kinetic.Shape} */ getIntersection: function(pos) { var layers = this.getChildren(), len = layers.length, end = len - 1, n, shape; for(n = end; n >= 0; n--) { shape = layers[n].getIntersection(pos); if (shape) { return shape; } } return null; }, _resizeDOM: function() { if(this.content) { var width = this.getWidth(), height = this.getHeight(), layers = this.getChildren(), len = layers.length, n, layer; // set content dimensions this.content.style.width = width + PX; this.content.style.height = height + PX; this.bufferCanvas.setSize(width, height); this.bufferHitCanvas.setSize(width, height); // set layer dimensions for(n = 0; n < len; n++) { layer = layers[n]; layer.getCanvas().setSize(width, height); layer.hitCanvas.setSize(width, height); layer.draw(); } } }, /** * add layer or layers to stage * @method * @memberof Kinetic.Stage.prototype * @param {...Kinetic.Layer} layer * @example * stage.add(layer1, layer2, layer3); */ add: function(layer) { if (arguments.length > 1) { for (var i = 0; i < arguments.length; i++) { this.add(arguments[i]); } return; } Kinetic.Container.prototype.add.call(this, layer); layer._setCanvasSize(this.width(), this.height()); // draw layer and append canvas to container layer.draw(); this.content.appendChild(layer.canvas._canvas); // chainable return this; }, getParent: function() { return null; }, getLayer: function() { return null; }, /** * returns a {@link Kinetic.Collection} of layers * @method * @memberof Kinetic.Stage.prototype */ getLayers: function() { return this.getChildren(); }, _bindContentEvents: function() { for (var n = 0; n < eventsLength; n++) { addEvent(this, EVENTS[n]); } }, _mouseover: function(evt) { if (!Kinetic.UA.mobile) { this._setPointerPosition(evt); this._fire(CONTENT_MOUSEOVER, {evt: evt}); } }, _mouseout: function(evt) { if (!Kinetic.UA.mobile) { this._setPointerPosition(evt); var targetShape = this.targetShape; if(targetShape && !Kinetic.isDragging()) { targetShape._fireAndBubble(MOUSEOUT, {evt: evt}); targetShape._fireAndBubble(MOUSELEAVE, {evt: evt}); this.targetShape = null; } this.pointerPos = undefined; this._fire(CONTENT_MOUSEOUT, {evt: evt}); } }, _mousemove: function(evt) { if (!Kinetic.UA.mobile) { this._setPointerPosition(evt); var dd = Kinetic.DD, shape = this.getIntersection(this.getPointerPosition()); if(shape && shape.isListening()) { if(!Kinetic.isDragging() && (!this.targetShape || this.targetShape._id !== shape._id)) { if(this.targetShape) { this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt}, shape); this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt}, shape); } shape._fireAndBubble(MOUSEOVER, {evt: evt}, this.targetShape); shape._fireAndBubble(MOUSEENTER, {evt: evt}, this.targetShape); this.targetShape = shape; } else { shape._fireAndBubble(MOUSEMOVE, {evt: evt}); } } /* * if no shape was detected, clear target shape and try * to run mouseout from previous target shape */ else { if(this.targetShape && !Kinetic.isDragging()) { this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt}); this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt}); this.targetShape = null; } } // content event this._fire(CONTENT_MOUSEMOVE, {evt: evt}); if(dd) { dd._drag(evt); } } // always call preventDefault for desktop events because some browsers // try to drag and drop the canvas element if (evt.preventDefault) { evt.preventDefault(); } }, _mousedown: function(evt) { if (!Kinetic.UA.mobile) { this._setPointerPosition(evt); var shape = this.getIntersection(this.getPointerPosition()); Kinetic.listenClickTap = true; if (shape && shape.isListening()) { this.clickStartShape = shape; shape._fireAndBubble(MOUSEDOWN, {evt: evt}); } // content event this._fire(CONTENT_MOUSEDOWN, {evt: evt}); } // always call preventDefault for desktop events because some browsers // try to drag and drop the canvas element if (evt.preventDefault) { evt.preventDefault(); } }, _mouseup: function(evt) { if (!Kinetic.UA.mobile) { this._setPointerPosition(evt); var that = this, shape = this.getIntersection(this.getPointerPosition()), clickStartShape = this.clickStartShape, fireDblClick = false; if(Kinetic.inDblClickWindow) { fireDblClick = true; Kinetic.inDblClickWindow = false; } else { Kinetic.inDblClickWindow = true; } setTimeout(function() { Kinetic.inDblClickWindow = false; }, Kinetic.dblClickWindow); if (shape && shape.isListening()) { shape._fireAndBubble(MOUSEUP, {evt: evt}); // detect if click or double click occurred if(Kinetic.listenClickTap && clickStartShape && clickStartShape._id === shape._id) { shape._fireAndBubble(CLICK, {evt: evt}); if(fireDblClick) { shape._fireAndBubble(DBL_CLICK, {evt: evt}); } } } // content events this._fire(CONTENT_MOUSEUP, {evt: evt}); if (Kinetic.listenClickTap) { this._fire(CONTENT_CLICK, {evt: evt}); if(fireDblClick) { this._fire(CONTENT_DBL_CLICK, {evt: evt}); } } Kinetic.listenClickTap = false; } // always call preventDefault for desktop events because some browsers // try to drag and drop the canvas element if (evt.preventDefault) { evt.preventDefault(); } }, _touchstart: function(evt) { this._setPointerPosition(evt); var shape = this.getIntersection(this.getPointerPosition()); Kinetic.listenClickTap = true; if (shape && shape.isListening()) { this.tapStartShape = shape; shape._fireAndBubble(TOUCHSTART, {evt: evt}); // only call preventDefault if the shape is listening for events if (shape.isListening() && evt.preventDefault) { evt.preventDefault(); } } // content event this._fire(CONTENT_TOUCHSTART, {evt: evt}); }, _touchend: function(evt) { this._setPointerPosition(evt); var shape = this.getIntersection(this.getPointerPosition()), fireDblClick = false; if(Kinetic.inDblClickWindow) { fireDblClick = true; Kinetic.inDblClickWindow = false; } else { Kinetic.inDblClickWindow = true; } setTimeout(function() { Kinetic.inDblClickWindow = false; }, Kinetic.dblClickWindow); if (shape && shape.isListening()) { shape._fireAndBubble(TOUCHEND, {evt: evt}); // detect if tap or double tap occurred if(Kinetic.listenClickTap && shape._id === this.tapStartShape._id) { shape._fireAndBubble(TAP, {evt: evt}); if(fireDblClick) { shape._fireAndBubble(DBL_TAP, {evt: evt}); } } // only call preventDefault if the shape is listening for events if (shape.isListening() && evt.preventDefault) { evt.preventDefault(); } } // content events if (Kinetic.listenClickTap) { this._fire(CONTENT_TOUCHEND, {evt: evt}); if(fireDblClick) { this._fire(CONTENT_DBL_TAP, {evt: evt}); } } Kinetic.listenClickTap = false; }, _touchmove: function(evt) { this._setPointerPosition(evt); var dd = Kinetic.DD, shape = this.getIntersection(this.getPointerPosition()); if (shape && shape.isListening()) { shape._fireAndBubble(TOUCHMOVE, {evt: evt}); // only call preventDefault if the shape is listening for events if (shape.isListening() && evt.preventDefault) { evt.preventDefault(); } } this._fire(CONTENT_TOUCHMOVE, {evt: evt}); // start drag and drop if(dd) { dd._drag(evt); } }, _setPointerPosition: function(evt) { var contentPosition = this._getContentPosition(), offsetX = evt.offsetX, clientX = evt.clientX, x = null, y = null, touch; evt = evt ? evt : window.event; // touch events if(evt.touches !== undefined) { // currently, only handle one finger if (evt.touches.length > 0) { touch = evt.touches[0]; // get the information for finger #1 x = touch.clientX - contentPosition.left; y = touch.clientY - contentPosition.top; } } // mouse events else { // if offsetX is defined, assume that offsetY is defined as well if (offsetX !== undefined) { x = offsetX; y = evt.offsetY; } // we unforunately have to use UA detection here because accessing // the layerX or layerY properties in newer veresions of Chrome // throws a JS warning. layerX and layerY are required for FF // when the container is transformed via CSS. else if (Kinetic.UA.browser === 'mozilla') { x = evt.layerX; y = evt.layerY; } // if clientX is defined, assume that clientY is defined as well else if (clientX !== undefined && contentPosition) { x = clientX - contentPosition.left; y = evt.clientY - contentPosition.top; } } if (x !== null && y !== null) { this.pointerPos = { x: x, y: y }; } }, _getContentPosition: function() { var rect = this.content.getBoundingClientRect ? this.content.getBoundingClientRect() : { top: 0, left: 0 }; return { top: rect.top, left: rect.left }; }, _buildDOM: function() { var container = this.getContainer(); if (!container) { if (Kinetic.Util.isBrowser()) { throw 'Stage has not container. But container is required'; } else { // automatically create element for jsdom in nodejs env container = Kinetic.document.createElement(DIV); } } // clear content inside container container.innerHTML = EMPTY_STRING; // content this.content = Kinetic.document.createElement(DIV); this.content.style.position = RELATIVE; this.content.style.display = INLINE_BLOCK; this.content.className = KINETICJS_CONTENT; this.content.setAttribute('role', 'presentation'); container.appendChild(this.content); // the buffer canvas pixel ratio must be 1 because it is used as an // intermediate canvas before copying the result onto a scene canvas. // not setting it to 1 will result in an over compensation this.bufferCanvas = new Kinetic.SceneCanvas({ pixelRatio: 1 }); this.bufferHitCanvas = new Kinetic.HitCanvas(); this._resizeDOM(); }, _onContent: function(typesStr, handler) { var types = typesStr.split(SPACE), len = types.length, n, baseEvent; for(n = 0; n < len; n++) { baseEvent = types[n]; this.content.addEventListener(baseEvent, handler, false); } }, // currently cache function is now working for stage, because stage has no its own canvas element // TODO: may be it is better to cache all children layers? cache: function() { Kinetic.Util.warn('Cache function is not allowed for stage. You may use cache only for layers, groups and shapes.'); return; }, clearCache : function() { } }); Kinetic.Util.extend(Kinetic.Stage, Kinetic.Container); // add getters and setters Kinetic.Factory.addGetter(Kinetic.Stage, 'container'); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Stage, 'container'); /** * get container DOM element * @name container * @method * @memberof Kinetic.Stage.prototype * @returns {DomElement} container * @example * // get container<br> * var container = stage.container();<br><br> * * // set container<br> * var container = document.createElement('div');<br> * body.appendChild(container);<br> * stage.container(container); */ })(); ;(function() { Kinetic.Util.addMethods(Kinetic.BaseLayer, { ___init: function(config) { this.nodeType = 'Layer'; Kinetic.Container.call(this, config); }, createPNGStream : function() { return this.canvas._canvas.createPNGStream(); }, /** * get layer canvas * @method * @memberof Kinetic.BaseLayer.prototype */ getCanvas: function() { return this.canvas; }, /** * get layer hit canvas * @method * @memberof Kinetic.BaseLayer.prototype */ getHitCanvas: function() { return this.hitCanvas; }, /** * get layer canvas context * @method * @memberof Kinetic.BaseLayer.prototype */ getContext: function() { return this.getCanvas().getContext(); }, /** * clear scene and hit canvas contexts tied to the layer * @method * @memberof Kinetic.BaseLayer.prototype * @param {Object} [bounds] * @param {Number} [bounds.x] * @param {Number} [bounds.y] * @param {Number} [bounds.width] * @param {Number} [bounds.height] * @example * layer.clear();<br> * layer.clear(0, 0, 100, 100); */ clear: function(bounds) { this.getContext().clear(bounds); this.getHitCanvas().getContext().clear(bounds); return this; }, // extend Node.prototype.setZIndex setZIndex: function(index) { Kinetic.Node.prototype.setZIndex.call(this, index); var stage = this.getStage(); if(stage) { stage.content.removeChild(this.getCanvas()._canvas); if(index < stage.getChildren().length - 1) { stage.content.insertBefore(this.getCanvas()._canvas, stage.getChildren()[index + 1].getCanvas()._canvas); } else { stage.content.appendChild(this.getCanvas()._canvas); } } return this; }, // extend Node.prototype.moveToTop moveToTop: function() { Kinetic.Node.prototype.moveToTop.call(this); var stage = this.getStage(); if(stage) { stage.content.removeChild(this.getCanvas()._canvas); stage.content.appendChild(this.getCanvas()._canvas); } }, // extend Node.prototype.moveUp moveUp: function() { if(Kinetic.Node.prototype.moveUp.call(this)) { var stage = this.getStage(); if(stage) { stage.content.removeChild(this.getCanvas()._canvas); if(this.index < stage.getChildren().length - 1) { stage.content.insertBefore(this.getCanvas()._canvas, stage.getChildren()[this.index + 1].getCanvas()._canvas); } else { stage.content.appendChild(this.getCanvas()._canvas); } } } }, // extend Node.prototype.moveDown moveDown: function() { if(Kinetic.Node.prototype.moveDown.call(this)) { var stage = this.getStage(); if(stage) { var children = stage.getChildren(); stage.content.removeChild(this.getCanvas()._canvas); stage.content.insertBefore(this.getCanvas()._canvas, children[this.index + 1].getCanvas()._canvas); } } }, // extend Node.prototype.moveToBottom moveToBottom: function() { if(Kinetic.Node.prototype.moveToBottom.call(this)) { var stage = this.getStage(); if(stage) { var children = stage.getChildren(); stage.content.removeChild(this.getCanvas()._canvas); stage.content.insertBefore(this.getCanvas()._canvas, children[1].getCanvas()._canvas); } } }, getLayer: function() { return this; }, remove: function() { var _canvas = this.getCanvas()._canvas; Kinetic.Node.prototype.remove.call(this); if(_canvas && _canvas.parentNode && Kinetic.Util._isInDocument(_canvas)) { _canvas.parentNode.removeChild(_canvas); } return this; }, getStage: function() { return this.parent; } }); Kinetic.Util.extend(Kinetic.BaseLayer, Kinetic.Container); // add getters and setters Kinetic.Factory.addGetterSetter(Kinetic.BaseLayer, 'clearBeforeDraw', true); /** * get/set clearBeforeDraw flag which determines if the layer is cleared or not * before drawing * @name clearBeforeDraw * @method * @memberof Kinetic.BaseLayer.prototype * @param {Boolean} clearBeforeDraw * @returns {Boolean} * @example * // get clearBeforeDraw flag<br> * var clearBeforeDraw = layer.clearBeforeDraw();<br><br> * * // disable clear before draw<br> * layer.clearBeforeDraw(false);<br><br> * * // enable clear before draw<br> * layer.clearBeforeDraw(true); */ Kinetic.Collection.mapMethods(Kinetic.BaseLayer); })(); ;(function() { // constants var HASH = '#', BEFORE_DRAW ='beforeDraw', DRAW = 'draw', /* * 2 - 3 - 4 * | | * 1 - 0 5 * | * 8 - 7 - 6 */ INTERSECTION_OFFSETS = [ {x: 0, y: 0}, // 0 {x: -1, y: 0}, // 1 {x: -1, y: -1}, // 2 {x: 0, y: -1}, // 3 {x: 1, y: -1}, // 4 {x: 1, y: 0}, // 5 {x: 1, y: 1}, // 6 {x: 0, y: 1}, // 7 {x: -1, y: 1} // 8 ], INTERSECTION_OFFSETS_LEN = INTERSECTION_OFFSETS.length; Kinetic.Util.addMethods(Kinetic.Layer, { ____init: function(config) { this.nodeType = 'Layer'; this.canvas = new Kinetic.SceneCanvas(); this.hitCanvas = new Kinetic.HitCanvas(); // call super constructor Kinetic.BaseLayer.call(this, config); }, _setCanvasSize: function(width, height) { this.canvas.setSize(width, height); this.hitCanvas.setSize(width, height); }, _validateAdd: function(child) { var type = child.getType(); if (type !== 'Group' && type !== 'Shape') { Kinetic.Util.error('You may only add groups and shapes to a layer.'); } }, /** * get visible intersection shape. This is the preferred * method for determining if a point intersects a shape or not * @method * @memberof Kinetic.Layer.prototype * @param {Object} pos * @param {Number} pos.x * @param {Number} pos.y * @returns {Kinetic.Shape} */ getIntersection: function(pos) { var obj, i, intersectionOffset, shape; if(this.hitGraphEnabled() && this.isVisible()) { for (i=0; i<INTERSECTION_OFFSETS_LEN; i++) { intersectionOffset = INTERSECTION_OFFSETS[i]; obj = this._getIntersection({ x: pos.x + intersectionOffset.x, y: pos.y + intersectionOffset.y }); shape = obj.shape; if (shape) { return shape; } else if (!obj.antialiased) { return null; } } } else { return null; } }, _getIntersection: function(pos) { var p = this.hitCanvas.context._context.getImageData(pos.x, pos.y, 1, 1).data, p3 = p[3], colorKey, shape; // fully opaque pixel if(p3 === 255) { colorKey = Kinetic.Util._rgbToHex(p[0], p[1], p[2]); shape = Kinetic.shapes[HASH + colorKey]; return { shape: shape }; } // antialiased pixel else if(p3 > 0) { return { antialiased: true }; } // empty pixel else { return {}; } }, drawScene: function(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()); this._fire(BEFORE_DRAW, { node: this }); if(this.getClearBeforeDraw()) { canvas.getContext().clear(); } Kinetic.Container.prototype.drawScene.call(this, canvas, top); this._fire(DRAW, { node: this }); return this; }, // the apply transform method is handled by the Layer and FastLayer class // because it is up to the layer to decide if an absolute or relative transform // should be used _applyTransform: function(shape, context, top) { var m = shape.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); }, drawHit: function(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas); if(layer && layer.getClearBeforeDraw()) { layer.getHitCanvas().getContext().clear(); } Kinetic.Container.prototype.drawHit.call(this, canvas, top); return this; }, /** * clear scene and hit canvas contexts tied to the layer * @method * @memberof Kinetic.Layer.prototype * @param {Object} [bounds] * @param {Number} [bounds.x] * @param {Number} [bounds.y] * @param {Number} [bounds.width] * @param {Number} [bounds.height] * @example * layer.clear();<br> * layer.clear(0, 0, 100, 100); */ clear: function(bounds) { this.getContext().clear(bounds); this.getHitCanvas().getContext().clear(bounds); return this; }, // extend Node.prototype.setVisible setVisible: function(visible) { Kinetic.Node.prototype.setVisible.call(this, visible); if(visible) { this.getCanvas()._canvas.style.display = 'block'; this.hitCanvas._canvas.style.display = 'block'; } else { this.getCanvas()._canvas.style.display = 'none'; this.hitCanvas._canvas.style.display = 'none'; } return this; }, /** * enable hit graph * @name enableHitGraph * @method * @memberof Kinetic.Layer.prototype * @returns {Node} */ enableHitGraph: function() { this.setHitGraphEnabled(true); return this; }, /** * disable hit graph * @name enableHitGraph * @method * @memberof Kinetic.Layer.prototype * @returns {Node} */ disableHitGraph: function() { this.setHitGraphEnabled(false); return this; } }); Kinetic.Util.extend(Kinetic.Layer, Kinetic.BaseLayer); Kinetic.Factory.addGetterSetter(Kinetic.Layer, 'hitGraphEnabled', true); /** * get/set hitGraphEnabled flag. Disabling the hit graph will greatly increase * draw performance because the hit graph will not be redrawn each time the layer is * drawn. This, however, also disables mouse/touch event detection * @name hitGraphEnabled * @method * @memberof Kinetic.Layer.prototype * @param {Boolean} enabled * @returns {Boolean} * @example * // get hitGraphEnabled flag<br> * var hitGraphEnabled = layer.hitGraphEnabled();<br><br> * * // disable hit graph<br> * layer.hitGraphEnabled(false);<br><br> * * // enable hit graph<br> * layer.hitGraphEnabled(true); */ Kinetic.Collection.mapMethods(Kinetic.Layer); })(); ;(function() { // constants var HASH = '#', BEFORE_DRAW ='beforeDraw', DRAW = 'draw'; Kinetic.Util.addMethods(Kinetic.FastLayer, { ____init: function(config) { this.nodeType = 'Layer'; this.canvas = new Kinetic.SceneCanvas(); // call super constructor Kinetic.BaseLayer.call(this, config); }, _validateAdd: function(child) { var type = child.getType(); if (type !== 'Shape') { Kinetic.Util.error('You may only add shapes to a fast layer.'); } }, _setCanvasSize: function(width, height) { this.canvas.setSize(width, height); }, hitGraphEnabled: function() { return false; }, getIntersection: function() { return null; }, drawScene: function(can) { var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()); if(this.getClearBeforeDraw()) { canvas.getContext().clear(); } Kinetic.Container.prototype.drawScene.call(this, canvas); return this; }, // the apply transform method is handled by the Layer and FastLayer class // because it is up to the layer to decide if an absolute or relative transform // should be used _applyTransform: function(shape, context, top) { if (!top || top._id !== this._id) { var m = shape.getTransform().getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); } }, draw: function() { this.drawScene(); return this; }, /** * clear scene and hit canvas contexts tied to the layer * @method * @memberof Kinetic.FastLayer.prototype * @param {Object} [bounds] * @param {Number} [bounds.x] * @param {Number} [bounds.y] * @param {Number} [bounds.width] * @param {Number} [bounds.height] * @example * layer.clear();<br> * layer.clear(0, 0, 100, 100); */ clear: function(bounds) { this.getContext().clear(bounds); return this; }, // extend Node.prototype.setVisible setVisible: function(visible) { Kinetic.Node.prototype.setVisible.call(this, visible); if(visible) { this.getCanvas()._canvas.style.display = 'block'; } else { this.getCanvas()._canvas.style.display = 'none'; } return this; } }); Kinetic.Util.extend(Kinetic.FastLayer, Kinetic.BaseLayer); Kinetic.Collection.mapMethods(Kinetic.FastLayer); })(); ;(function() { Kinetic.Util.addMethods(Kinetic.Group, { ___init: function(config) { this.nodeType = 'Group'; // call super constructor Kinetic.Container.call(this, config); }, _validateAdd: function(child) { var type = child.getType(); if (type !== 'Group' && type !== 'Shape') { Kinetic.Util.error('You may only add groups and shapes to groups.'); } } }); Kinetic.Util.extend(Kinetic.Group, Kinetic.Container); Kinetic.Collection.mapMethods(Kinetic.Group); })(); ;(function() { /** * Rect constructor * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {Number} [config.cornerRadius] * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var rect = new Kinetic.Rect({<br> * width: 100,<br> * height: 50,<br> * fill: 'red',<br> * stroke: 'black',<br> * strokeWidth: 5<br> * }); */ Kinetic.Rect = function(config) { this.___init(config); }; Kinetic.Rect.prototype = { ___init: function(config) { Kinetic.Shape.call(this, config); this.className = 'Rect'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var cornerRadius = this.getCornerRadius(), width = this.getWidth(), height = this.getHeight(); context.beginPath(); if(!cornerRadius) { // simple rect - don't bother doing all that complicated maths stuff. context.rect(0, 0, width, height); } else { // arcTo would be nicer, but browser support is patchy (Opera) context.moveTo(cornerRadius, 0); context.lineTo(width - cornerRadius, 0); context.arc(width - cornerRadius, cornerRadius, cornerRadius, Math.PI * 3 / 2, 0, false); context.lineTo(width, height - cornerRadius); context.arc(width - cornerRadius, height - cornerRadius, cornerRadius, 0, Math.PI / 2, false); context.lineTo(cornerRadius, height); context.arc(cornerRadius, height - cornerRadius, cornerRadius, Math.PI / 2, Math.PI, false); context.lineTo(0, cornerRadius); context.arc(cornerRadius, cornerRadius, cornerRadius, Math.PI, Math.PI * 3 / 2, false); } context.closePath(); context.fillStrokeShape(this); } }; Kinetic.Util.extend(Kinetic.Rect, Kinetic.Shape); Kinetic.Factory.addGetterSetter(Kinetic.Rect, 'cornerRadius', 0); /** * get/set corner radius * @name cornerRadius * @method * @memberof Kinetic.Rect.prototype * @param {Number} cornerRadius * @returns {Number} * @example * // get corner radius<br> * var cornerRadius = rect.cornerRadius();<br><br> * * // set corner radius<br> * rect.cornerRadius(10); */ Kinetic.Collection.mapMethods(Kinetic.Rect); })(); ;(function() { // the 0.0001 offset fixes a bug in Chrome 27 var PIx2 = (Math.PI * 2) - 0.0001, CIRCLE = 'Circle'; /** * Circle constructor * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {Number} config.radius * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * // create circle * var circle = new Kinetic.Circle({<br> * radius: 40,<br> * fill: 'red',<br> * stroke: 'black'<br> * strokeWidth: 5<br> * }); */ Kinetic.Circle = function(config) { this.___init(config); }; Kinetic.Circle.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = CIRCLE; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { context.beginPath(); context.arc(0, 0, this.getRadius(), 0, PIx2, false); context.closePath(); context.fillStrokeShape(this); }, // implements Shape.prototype.getWidth() getWidth: function() { return this.getRadius() * 2; }, // implements Shape.prototype.getHeight() getHeight: function() { return this.getRadius() * 2; }, // implements Shape.prototype.setWidth() setWidth: function(width) { Kinetic.Node.prototype.setWidth.call(this, width); this.setRadius(width / 2); }, // implements Shape.prototype.setHeight() setHeight: function(height) { Kinetic.Node.prototype.setHeight.call(this, height); this.setRadius(height / 2); } }; Kinetic.Util.extend(Kinetic.Circle, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Circle, 'radius', 0); /** * get/set radius * @name radius * @method * @memberof Kinetic.Circle.prototype * @param {Number} radius * @returns {Number} * @example * // get radius<br> * var radius = circle.radius();<br><br> * * // set radius<br> * circle.radius(10);<br> */ Kinetic.Collection.mapMethods(Kinetic.Circle); })(); ;(function() { // the 0.0001 offset fixes a bug in Chrome 27 var PIx2 = (Math.PI * 2) - 0.0001, ELLIPSE = 'Ellipse'; /** * Ellipse constructor * @constructor * @augments Kinetic.Shape * @param {Object} config * @param {Object} config.radius defines x and y radius * @@ShapeParams * @@NodeParams * @example * var ellipse = new Kinetic.Ellipse({<br> * radius : {<br> * x : 50,<br> * y : 50<br> * },<br> * fill: 'red'<br> * }); */ Kinetic.Ellipse = function(config) { this.___init(config); }; Kinetic.Ellipse.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = ELLIPSE; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var r = this.getRadius(), rx = r.x, ry = r.y; context.beginPath(); context.save(); if(rx !== ry) { context.scale(1, ry / rx); } context.arc(0, 0, rx, 0, PIx2, false); context.restore(); context.closePath(); context.fillStrokeShape(this); }, // implements Shape.prototype.getWidth() getWidth: function() { return this.getRadius().x * 2; }, // implements Shape.prototype.getHeight() getHeight: function() { return this.getRadius().y * 2; }, // implements Shape.prototype.setWidth() setWidth: function(width) { Kinetic.Node.prototype.setWidth.call(this, width); this.setRadius({ x: width / 2 }); }, // implements Shape.prototype.setHeight() setHeight: function(height) { Kinetic.Node.prototype.setHeight.call(this, height); this.setRadius({ y: height / 2 }); } }; Kinetic.Util.extend(Kinetic.Ellipse, Kinetic.Shape); // add getters setters Kinetic.Factory.addComponentsGetterSetter(Kinetic.Ellipse, 'radius', ['x', 'y']); /** * get/set radius * @name radius * @method * @memberof Kinetic.Ellipse.prototype * @param {Object} radius * @param {Number} radius.x * @param {Number} radius.y * @returns {Object} * @example * // get radius<br> * var radius = ellipse.radius();<br><br> * * // set radius<br> * ellipse.radius({<br> * x: 200,<br> * y: 100<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Ellipse, 'radiusX', 0); /** * get/set radius x * @name radiusX * @method * @memberof Kinetic.Ellipse.prototype * @param {Number} x * @returns {Number} * @example * // get radius x<br> * var radiusX = ellipse.radiusX();<br><br> * * // set radius x<br> * ellipse.radiusX(200); */ Kinetic.Factory.addGetterSetter(Kinetic.Ellipse, 'radiusY', 0); /** * get/set radius y * @name radiusY * @method * @memberof Kinetic.Ellipse.prototype * @param {Number} y * @returns {Number} * @example * // get radius y<br> * var radiusY = ellipse.radiusY();<br><br> * * // set radius y<br> * ellipse.radiusY(200); */ Kinetic.Collection.mapMethods(Kinetic.Ellipse); })();;(function() { // the 0.0001 offset fixes a bug in Chrome 27 var PIx2 = (Math.PI * 2) - 0.0001; /** * Ring constructor * @constructor * @augments Kinetic.Shape * @param {Object} config * @param {Number} config.innerRadius * @param {Number} config.outerRadius * @param {Boolean} [config.clockwise] * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var ring = new Kinetic.Ring({<br> * innerRadius: 40,<br> * outerRadius: 80,<br> * fill: 'red',<br> * stroke: 'black',<br> * strokeWidth: 5<br> * }); */ Kinetic.Ring = function(config) { this.___init(config); }; Kinetic.Ring.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'Ring'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { context.beginPath(); context.arc(0, 0, this.getInnerRadius(), 0, PIx2, false); context.moveTo(this.getOuterRadius(), 0); context.arc(0, 0, this.getOuterRadius(), PIx2, 0, true); context.closePath(); context.fillStrokeShape(this); }, // implements Shape.prototype.getWidth() getWidth: function() { return this.getOuterRadius() * 2; }, // implements Shape.prototype.getHeight() getHeight: function() { return this.getOuterRadius() * 2; }, // implements Shape.prototype.setWidth() setWidth: function(width) { Kinetic.Node.prototype.setWidth.call(this, width); this.setOuterRadius(width / 2); }, // implements Shape.prototype.setHeight() setHeight: function(height) { Kinetic.Node.prototype.setHeight.call(this, height); this.setOuterRadius(height / 2); } }; Kinetic.Util.extend(Kinetic.Ring, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Ring, 'innerRadius', 0); /** * get/set innerRadius * @name innerRadius * @method * @memberof Kinetic.Ring.prototype * @param {Number} innerRadius * @returns {Number} * @example * // get inner radius<br> * var innerRadius = ring.innerRadius();<br><br> * * // set inner radius<br> * ring.innerRadius(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Ring, 'outerRadius', 0); /** * get/set outerRadius * @name outerRadius * @method * @memberof Kinetic.Ring.prototype * @param {Number} outerRadius * @returns {Number} * @example * // get outer radius<br> * var outerRadius = ring.outerRadius();<br><br> * * // set outer radius<br> * ring.outerRadius(20); */ Kinetic.Collection.mapMethods(Kinetic.Ring); })(); ;(function() { /** * Wedge constructor * @constructor * @augments Kinetic.Shape * @param {Object} config * @param {Number} config.angle in degrees * @param {Number} config.radius * @param {Boolean} [config.clockwise] * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * // draw a wedge that's pointing downwards<br> * var wedge = new Kinetic.Wedge({<br> * radius: 40,<br> * fill: 'red',<br> * stroke: 'black'<br> * strokeWidth: 5,<br> * angleDeg: 60,<br> * rotationDeg: -120<br> * }); */ Kinetic.Wedge = function(config) { this.___init(config); }; Kinetic.Wedge.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'Wedge'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { context.beginPath(); context.arc(0, 0, this.getRadius(), 0, Kinetic.getAngle(this.getAngle()), this.getClockwise()); context.lineTo(0, 0); context.closePath(); context.fillStrokeShape(this); } }; Kinetic.Util.extend(Kinetic.Wedge, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'radius', 0); /** * get/set radius * @name radius * @method * @memberof Kinetic.Wedge.prototype * @param {Number} radius * @returns {Number} * @example * // get radius<br> * var radius = wedge.radius();<br><br> * * // set radius<br> * wedge.radius(10);<br> */ Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'angle', 0); /** * get/set angle in degrees * @name angle * @method * @memberof Kinetic.Wedge.prototype * @param {Number} angle * @returns {Number} * @example * // get angle<br> * var angle = wedge.angle();<br><br> * * // set angle<br> * wedge.angle(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Wedge, 'clockwise', false); /** * get/set clockwise flag * @name clockwise * @method * @memberof Kinetic.Wedge.prototype * @param {Number} clockwise * @returns {Number} * @example * // get clockwise flag<br> * var clockwise = wedge.clockwise();<br><br> * * // draw wedge counter-clockwise<br> * wedge.clockwise(false);<br><br> * * // draw wedge clockwise<br> * wedge.clockwise(true); */ Kinetic.Factory.backCompat(Kinetic.Wedge, { angleDeg: 'angle', getAngleDeg: 'getAngle', setAngleDeg: 'setAngle' }); Kinetic.Collection.mapMethods(Kinetic.Wedge); })(); ;(function() { var PI_OVER_180 = Math.PI / 180; /** * Arc constructor * @constructor * @augments Kinetic.Shape * @param {Object} config * @param {Number} config.angle in degrees * @param {Number} config.innerRadius * @param {Number} config.outerRadius * @param {Boolean} [config.clockwise] * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * // draw a Arc that's pointing downwards<br> * var arc = new Kinetic.Arc({<br> * innerRadius: 40,<br> * outerRadius: 80,<br> * fill: 'red',<br> * stroke: 'black'<br> * strokeWidth: 5,<br> * angle: 60,<br> * rotationDeg: -120<br> * }); */ Kinetic.Arc = function(config) { this.___init(config); }; Kinetic.Arc.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'Arc'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var angle = Kinetic.getAngle(this.angle()), clockwise = this.clockwise(); context.beginPath(); context.arc(0, 0, this.getOuterRadius(), 0, angle, clockwise); context.arc(0, 0, this.getInnerRadius(), angle, 0, !clockwise); context.closePath(); context.fillStrokeShape(this); } }; Kinetic.Util.extend(Kinetic.Arc, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'innerRadius', 0); /** * get/set innerRadius * @name innerRadius * @method * @memberof Kinetic.Arc.prototype * @param {Number} innerRadius * @returns {Number} * @example * // get inner radius * var innerRadius = arc.innerRadius(); * * // set inner radius * arc.innerRadius(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'outerRadius', 0); /** * get/set outerRadius * @name outerRadius * @method * @memberof Kinetic.Arc.prototype * @param {Number} outerRadius * @returns {Number} * @example * // get outer radius<br> * var outerRadius = arc.outerRadius();<br><br> * * // set outer radius<br> * arc.outerRadius(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'angle', 0); /** * get/set angle in degrees * @name angle * @method * @memberof Kinetic.Arc.prototype * @param {Number} angle * @returns {Number} * @example * // get angle<br> * var angle = arc.angle();<br><br> * * // set angle<br> * arc.angle(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Arc, 'clockwise', false); /** * get/set clockwise flag * @name clockwise * @method * @memberof Kinetic.Arc.prototype * @param {Boolean} clockwise * @returns {Boolean} * @example * // get clockwise flag<br> * var clockwise = arc.clockwise();<br><br> * * // draw arc counter-clockwise<br> * arc.clockwise(false);<br><br> * * // draw arc clockwise<br> * arc.clockwise(true); */ Kinetic.Collection.mapMethods(Kinetic.Arc); })(); ;(function() { // CONSTANTS var IMAGE = 'Image'; /** * Image constructor * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {ImageObject} config.image * @param {Object} [config.crop] * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var imageObj = new Image();<br> * imageObj.onload = function() {<br> * var image = new Kinetic.Image({<br> * x: 200,<br> * y: 50,<br> * image: imageObj,<br> * width: 100,<br> * height: 100<br> * });<br> * };<br> * imageObj.src = '/path/to/image.jpg' */ Kinetic.Image = function(config) { this.___init(config); }; Kinetic.Image.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = IMAGE; this.sceneFunc(this._sceneFunc); this.hitFunc(this._hitFunc); }, _useBufferCanvas: function() { return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasStroke(); }, _sceneFunc: function(context) { var width = this.getWidth(), height = this.getHeight(), image = this.getImage(), crop, cropWidth, cropHeight, params; if (image) { crop = this.getCrop(); cropWidth = crop.width; cropHeight = crop.height; if (cropWidth && cropHeight) { params = [image, crop.x, crop.y, cropWidth, cropHeight, 0, 0, width, height]; } else { params = [image, 0, 0, width, height]; } } context.beginPath(); context.rect(0, 0, width, height); context.closePath(); context.fillStrokeShape(this); if (image) { context.drawImage.apply(context, params); } }, _hitFunc: function(context) { var width = this.getWidth(), height = this.getHeight(); context.beginPath(); context.rect(0, 0, width, height); context.closePath(); context.fillStrokeShape(this); }, getWidth: function() { var image = this.getImage(); return this.attrs.width || (image ? image.width : 0); }, getHeight: function() { var image = this.getImage(); return this.attrs.height || (image ? image.height : 0); } }; Kinetic.Util.extend(Kinetic.Image, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Image, 'image'); /** * set image * @name setImage * @method * @memberof Kinetic.Image.prototype * @param {ImageObject} image */ /** * get image * @name getImage * @method * @memberof Kinetic.Image.prototype * @returns {ImageObject} */ Kinetic.Factory.addComponentsGetterSetter(Kinetic.Image, 'crop', ['x', 'y', 'width', 'height']); /** * get/set crop * @method * @name crop * @memberof Kinetic.Image.prototype * @param {Object} crop * @param {Number} crop.x * @param {Number} crop.y * @param {Number} crop.width * @param {Number} crop.height * @returns {Object} * @example * // get crop<br> * var crop = image.crop();<br><br> * * // set crop<br> * image.crop({<br> * x: 20,<br> * y: 20,<br> * width: 20,<br> * height: 20<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropX', 0); /** * get/set crop x * @method * @name cropX * @memberof Kinetic.Image.prototype * @param {Number} x * @returns {Number} * @example * // get crop x<br> * var cropX = image.cropX();<br><br> * * // set crop x<br> * image.cropX(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropY', 0); /** * get/set crop y * @name cropY * @method * @memberof Kinetic.Image.prototype * @param {Number} y * @returns {Number} * @example * // get crop y<br> * var cropY = image.cropY();<br><br> * * // set crop y<br> * image.cropY(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropWidth', 0); /** * get/set crop width * @name cropWidth * @method * @memberof Kinetic.Image.prototype * @param {Number} width * @returns {Number} * @example * // get crop width<br> * var cropWidth = image.cropWidth();<br><br> * * // set crop width<br> * image.cropWidth(20); */ Kinetic.Factory.addGetterSetter(Kinetic.Image, 'cropHeight', 0); /** * get/set crop height * @name cropHeight * @method * @memberof Kinetic.Image.prototype * @param {Number} height * @returns {Number} * @example * // get crop height<br> * var cropHeight = image.cropHeight();<br><br> * * // set crop height<br> * image.cropHeight(20); */ Kinetic.Collection.mapMethods(Kinetic.Image); })(); ;(function() { // constants var AUTO = 'auto', //CANVAS = 'canvas', CENTER = 'center', CHANGE_KINETIC = 'Change.kinetic', CONTEXT_2D = '2d', DASH = '-', EMPTY_STRING = '', LEFT = 'left', TEXT = 'text', TEXT_UPPER = 'Text', MIDDLE = 'middle', NORMAL = 'normal', PX_SPACE = 'px ', SPACE = ' ', RIGHT = 'right', WORD = 'word', CHAR = 'char', NONE = 'none', ATTR_CHANGE_LIST = ['fontFamily', 'fontSize', 'fontStyle', 'fontVariant', 'padding', 'align', 'lineHeight', 'text', 'width', 'height', 'wrap'], // cached variables attrChangeListLen = ATTR_CHANGE_LIST.length, dummyContext = Kinetic.Util.createCanvasElement().getContext(CONTEXT_2D); /** * Text constructor * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {String} [config.fontFamily] default is Arial * @param {Number} [config.fontSize] in pixels. Default is 12 * @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal * @param {String} [config.fontVariant] can be normal or small-caps. Default is normal * @param {String} config.text * @param {String} [config.align] can be left, center, or right * @param {Number} [config.padding] * @param {Number} [config.width] default is auto * @param {Number} [config.height] default is auto * @param {Number} [config.lineHeight] default is 1 * @param {String} [config.wrap] can be word, char, or none. Default is word * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var text = new Kinetic.Text({<br> * x: 10,<br> * y: 15,<br> * text: 'Simple Text',<br> * fontSize: 30,<br> * fontFamily: 'Calibri',<br> * fill: 'green'<br> * }); */ Kinetic.Text = function(config) { this.___init(config); }; function _fillFunc(context) { context.fillText(this.partialText, 0, 0); } function _strokeFunc(context) { context.strokeText(this.partialText, 0, 0); } Kinetic.Text.prototype = { ___init: function(config) { var that = this; if (config.width === undefined) { config.width = AUTO; } if (config.height === undefined) { config.height = AUTO; } // call super constructor Kinetic.Shape.call(this, config); this._fillFunc = _fillFunc; this._strokeFunc = _strokeFunc; this.className = TEXT_UPPER; // update text data for certain attr changes for(var n = 0; n < attrChangeListLen; n++) { this.on(ATTR_CHANGE_LIST[n] + CHANGE_KINETIC, that._setTextData); } this._setTextData(); this.sceneFunc(this._sceneFunc); this.hitFunc(this._hitFunc); }, _sceneFunc: function(context) { var p = this.getPadding(), textHeight = this.getTextHeight(), lineHeightPx = this.getLineHeight() * textHeight, textArr = this.textArr, textArrLen = textArr.length, totalWidth = this.getWidth(), n; context.setAttr('font', this._getContextFont()); context.setAttr('textBaseline', MIDDLE); context.setAttr('textAlign', LEFT); context.save(); context.translate(p, 0); context.translate(0, p + textHeight / 2); // draw text lines for(n = 0; n < textArrLen; n++) { var obj = textArr[n], text = obj.text, width = obj.width; // horizontal alignment context.save(); if(this.getAlign() === RIGHT) { context.translate(totalWidth - width - p * 2, 0); } else if(this.getAlign() === CENTER) { context.translate((totalWidth - width - p * 2) / 2, 0); } this.partialText = text; context.fillStrokeShape(this); context.restore(); context.translate(0, lineHeightPx); } context.restore(); }, _hitFunc: function(context) { var width = this.getWidth(), height = this.getHeight(); context.beginPath(); context.rect(0, 0, width, height); context.closePath(); context.fillStrokeShape(this); }, setText: function(text) { var str = Kinetic.Util._isString(text) ? text : text.toString(); this._setAttr(TEXT, str); return this; }, /** * get width of text area, which includes padding * @method * @memberof Kinetic.Text.prototype * @returns {Number} */ getWidth: function() { return this.attrs.width === AUTO ? this.getTextWidth() + this.getPadding() * 2 : this.attrs.width; }, /** * get the height of the text area, which takes into account multi-line text, line heights, and padding * @method * @memberof Kinetic.Text.prototype * @returns {Number} */ getHeight: function() { return this.attrs.height === AUTO ? (this.getTextHeight() * this.textArr.length * this.getLineHeight()) + this.getPadding() * 2 : this.attrs.height; }, /** * get text width * @method * @memberof Kinetic.Text.prototype * @returns {Number} */ getTextWidth: function() { return this.textWidth; }, /** * get text height * @method * @memberof Kinetic.Text.prototype * @returns {Number} */ getTextHeight: function() { return this.textHeight; }, _getTextSize: function(text) { var _context = dummyContext, fontSize = this.getFontSize(), metrics; _context.save(); _context.font = this._getContextFont(); metrics = _context.measureText(text); _context.restore(); return { width: metrics.width, height: parseInt(fontSize, 10) }; }, _getContextFont: function() { return this.getFontStyle() + SPACE + this.getFontVariant() + SPACE + this.getFontSize() + PX_SPACE + this.getFontFamily(); }, _addTextLine: function (line, width) { return this.textArr.push({text: line, width: width}); }, _getTextWidth: function (text) { return dummyContext.measureText(text).width; }, _setTextData: function () { var lines = this.getText().split('\n'), fontSize = +this.getFontSize(), textWidth = 0, lineHeightPx = this.getLineHeight() * fontSize, width = this.attrs.width, height = this.attrs.height, fixedWidth = width !== AUTO, fixedHeight = height !== AUTO, padding = this.getPadding(), maxWidth = width - padding * 2, maxHeightPx = height - padding * 2, currentHeightPx = 0, wrap = this.getWrap(), shouldWrap = wrap !== NONE, wrapAtWord = wrap !== CHAR && shouldWrap; this.textArr = []; dummyContext.save(); dummyContext.font = this._getContextFont(); for (var i = 0, max = lines.length; i < max; ++i) { var line = lines[i], lineWidth = this._getTextWidth(line); if (fixedWidth && lineWidth > maxWidth) { /* * if width is fixed and line does not fit entirely * break the line into multiple fitting lines */ while (line.length > 0) { /* * use binary search to find the longest substring that * that would fit in the specified width */ var low = 0, high = line.length, match = '', matchWidth = 0; while (low < high) { var mid = (low + high) >>> 1, substr = line.slice(0, mid + 1), substrWidth = this._getTextWidth(substr); if (substrWidth <= maxWidth) { low = mid + 1; match = substr; matchWidth = substrWidth; } else { high = mid; } } /* * 'low' is now the index of the substring end * 'match' is the substring * 'matchWidth' is the substring width in px */ if (match) { // a fitting substring was found if (wrapAtWord) { // try to find a space or dash where wrapping could be done var wrapIndex = Math.max(match.lastIndexOf(SPACE), match.lastIndexOf(DASH)) + 1; if (wrapIndex > 0) { // re-cut the substring found at the space/dash position low = wrapIndex; match = match.slice(0, low); matchWidth = this._getTextWidth(match); } } this._addTextLine(match, matchWidth); textWidth = Math.max(textWidth, matchWidth); currentHeightPx += lineHeightPx; if (!shouldWrap || (fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx)) { /* * stop wrapping if wrapping is disabled or if adding * one more line would overflow the fixed height */ break; } line = line.slice(low); if (line.length > 0) { // Check if the remaining text would fit on one line lineWidth = this._getTextWidth(line); if (lineWidth <= maxWidth) { // if it does, add the line and break out of the loop this._addTextLine(line, lineWidth); currentHeightPx += lineHeightPx; textWidth = Math.max(textWidth, lineWidth); break; } } } else { // not even one character could fit in the element, abort break; } } } else { // element width is automatically adjusted to max line width this._addTextLine(line, lineWidth); currentHeightPx += lineHeightPx; textWidth = Math.max(textWidth, lineWidth); } // if element height is fixed, abort if adding one more line would overflow if (fixedHeight && currentHeightPx + lineHeightPx > maxHeightPx) { break; } } dummyContext.restore(); this.textHeight = fontSize; this.textWidth = textWidth; } }; Kinetic.Util.extend(Kinetic.Text, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontFamily', 'Arial'); /** * get/set font family * @name fontFamily * @method * @memberof Kinetic.Text.prototype * @param {String} fontFamily * @returns {String} * @example * // get font family<br> * var fontFamily = text.fontFamily();<br><br><br> * * // set font family<br> * text.fontFamily('Arial'); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontSize', 12); /** * get/set font size in pixels * @name fontSize * @method * @memberof Kinetic.Text.prototype * @param {Number} fontSize * @returns {Number} * @example * // get font size<br> * var fontSize = text.fontSize();<br><br> * * // set font size to 22px<br> * text.fontSize(22); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontStyle', NORMAL); /** * set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default. * @name fontStyle * @method * @memberof Kinetic.Text.prototype * @param {String} fontStyle * @returns {String} * @example * // get font style<br> * var fontStyle = text.fontStyle();<br><br> * * // set font style<br> * text.fontStyle('bold'); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'fontVariant', NORMAL); /** * set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default. * @name fontVariant * @method * @memberof Kinetic.Text.prototype * @param {String} fontVariant * @returns {String} * @example * // get font variant<br> * var fontVariant = text.fontVariant();<br><br> * * // set font variant<br> * text.fontVariant('small-caps'); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'padding', 0); /** * set padding * @name padding * @method * @memberof Kinetic.Text.prototype * @param {Number} padding * @returns {Number} * @example * // get padding<br> * var padding = text.padding();<br><br> * * // set padding to 10 pixels<br> * text.padding(10); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'align', LEFT); /** * get/set horizontal align of text. Can be 'left', 'center', or 'right' * @name align * @method * @memberof Kinetic.Text.prototype * @param {String} align * @returns {String} * @example * // get text align<br> * var align = text.align();<br><br> * * // center text<br> * text.align('center');<br><br> * * // align text to right<br> * text.align('right'); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'lineHeight', 1); /** * get/set line height. The default is 1. * @name lineHeight * @method * @memberof Kinetic.Text.prototype * @param {Number} lineHeight * @returns {Number} * @example * // get line height<br> * var lineHeight = text.lineHeight();<br><br><br> * * // set the line height<br> * text.lineHeight(2); */ Kinetic.Factory.addGetterSetter(Kinetic.Text, 'wrap', WORD); /** * get/set wrap. Can be word, char, or none. Default is word. * @name wrap * @method * @memberof Kinetic.Text.prototype * @param {String} wrap * @returns {String} * @example * // get wrap<br> * var wrap = text.wrap();<br><br> * * // set wrap<br> * text.wrap('word'); */ Kinetic.Factory.addGetter(Kinetic.Text, 'text', EMPTY_STRING); Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Text, 'text'); /** * get/set text * @name getText * @method * @memberof Kinetic.Text.prototype * @param {String} text * @returns {String} * @example * // get text<br> * var text = text.text();<br><br> * * // set text<br> * text.text('Hello world!'); */ Kinetic.Collection.mapMethods(Kinetic.Text); })(); ;(function() { /** * Line constructor.&nbsp; Lines are defined by an array of points and * a tension * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {Array} config.points * @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation. * The default is 0 * @param {Boolean} [config.closed] defines whether or not the line shape is closed, creating a polygon or blob * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var line = new Kinetic.Line({<br> * x: 100,<br> * y: 50,<br> * points: [73, 70, 340, 23, 450, 60, 500, 20],<br> * stroke: 'red',<br> * tension: 1<br> * }); */ Kinetic.Line = function(config) { this.___init(config); }; Kinetic.Line.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'Line'; this.on('pointsChange.kinetic tensionChange.kinetic closedChange.kinetic', function() { this._clearCache('tensionPoints'); }); this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var points = this.getPoints(), length = points.length, tension = this.getTension(), closed = this.getClosed(), tp, len, n; context.beginPath(); context.moveTo(points[0], points[1]); // tension if(tension !== 0 && length > 4) { tp = this.getTensionPoints(); len = tp.length; n = closed ? 0 : 4; if (!closed) { context.quadraticCurveTo(tp[0], tp[1], tp[2], tp[3]); } while(n < len - 2) { context.bezierCurveTo(tp[n++], tp[n++], tp[n++], tp[n++], tp[n++], tp[n++]); } if (!closed) { context.quadraticCurveTo(tp[len-2], tp[len-1], points[length-2], points[length-1]); } } // no tension else { for(n = 2; n < length; n+=2) { context.lineTo(points[n], points[n+1]); } } // closed e.g. polygons and blobs if (closed) { context.closePath(); context.fillStrokeShape(this); } // open e.g. lines and splines else { context.strokeShape(this); } }, getTensionPoints: function() { return this._getCache('tensionPoints', this._getTensionPoints); }, _getTensionPoints: function() { if (this.getClosed()) { return this._getTensionPointsClosed(); } else { return Kinetic.Util._expandPoints(this.getPoints(), this.getTension()); } }, _getTensionPointsClosed: function() { var p = this.getPoints(), len = p.length, tension = this.getTension(), util = Kinetic.Util, firstControlPoints = util._getControlPoints( p[len-2], p[len-1], p[0], p[1], p[2], p[3], tension ), lastControlPoints = util._getControlPoints( p[len-4], p[len-3], p[len-2], p[len-1], p[0], p[1], tension ), middle = Kinetic.Util._expandPoints(p, tension), tp = [ firstControlPoints[2], firstControlPoints[3] ] .concat(middle) .concat([ lastControlPoints[0], lastControlPoints[1], p[len-2], p[len-1], lastControlPoints[2], lastControlPoints[3], firstControlPoints[0], firstControlPoints[1], p[0], p[1] ]); return tp; } }; Kinetic.Util.extend(Kinetic.Line, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Line, 'closed', false); /** * get/set closed flag. The default is false * @name closed * @method * @memberof Kinetic.Line.prototype * @param {Boolean} closed * @returns {Boolean} * @example * // get closed flag<br> * var closed = line.closed();<br><br> * * // close the shape<br> * line.closed(true);<br><br> * * // open the shape<br> * line.closed(false); */ Kinetic.Factory.addGetterSetter(Kinetic.Line, 'tension', 0); /** * get/set tension * @name tension * @method * @memberof Kinetic.Line.prototype * @param {Number} Higher values will result in a more curvy line. A value of 0 will result in no interpolation. * The default is 0 * @returns {Number} * @example * // get tension<br> * var tension = line.tension();<br><br> * * // set tension<br> * line.tension(3); */ Kinetic.Factory.addGetterSetter(Kinetic.Line, 'points'); /** * get/set points array * @name points * @method * @memberof Kinetic.Line.prototype * @param {Array} points * @returns {Array} * @example * // get points<br> * var points = line.points();<br><br> * * // set points<br> * line.points([10, 20, 30, 40, 50, 60]);<br><br> * * // push a new point<br> * line.points(line.points().concat([70, 80])); */ Kinetic.Collection.mapMethods(Kinetic.Line); })();;(function() { /** * Sprite constructor * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {String} config.animation animation key * @param {Object} config.animations animation map * @param {Integer} [config.frameIndex] animation frame index * @param {Image} config.image image object * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var imageObj = new Image();<br> * imageObj.onload = function() {<br> * var sprite = new Kinetic.Sprite({<br> * x: 200,<br> * y: 100,<br> * image: imageObj,<br> * animation: 'standing',<br> * animations: {<br> * standing: [<br> * // x, y, width, height (6 frames)<br> * 0, 0, 49, 109,<br> * 52, 0, 49, 109,<br> * 105, 0, 49, 109,<br> * 158, 0, 49, 109,<br> * 210, 0, 49, 109,<br> * 262, 0, 49, 109<br> * ],<br> * kicking: [<br> * // x, y, width, height (6 frames)<br> * 0, 109, 45, 98,<br> * 45, 109, 45, 98,<br> * 95, 109, 63, 98,<br> * 156, 109, 70, 98,<br> * 229, 109, 60, 98,<br> * 287, 109, 41, 98<br> * ]<br> * },<br> * frameRate: 7,<br> * frameIndex: 0<br> * });<br> * };<br> * imageObj.src = '/path/to/image.jpg' */ Kinetic.Sprite = function(config) { this.___init(config); }; Kinetic.Sprite.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'Sprite'; this.anim = new Kinetic.Animation(); this.on('animationChange.kinetic', function() { // reset index when animation changes this.frameIndex(0); }); // smooth change for frameRate this.on('frameRateChange.kinetic', function() { if (!this.anim.isRunning()) { return; } clearInterval(this.interval); this._setInterval(); }); this.sceneFunc(this._sceneFunc); this.hitFunc(this._hitFunc); }, _sceneFunc: function(context) { var anim = this.getAnimation(), index = this.frameIndex(), ix4 = index * 4, set = this.getAnimations()[anim], x = set[ix4 + 0], y = set[ix4 + 1], width = set[ix4 + 2], height = set[ix4 + 3], image = this.getImage(); if(image) { context.drawImage(image, x, y, width, height, 0, 0, width, height); } }, _hitFunc: function(context) { var anim = this.getAnimation(), index = this.frameIndex(), ix4 = index * 4, set = this.getAnimations()[anim], width = set[ix4 + 2], height = set[ix4 + 3]; context.beginPath(); context.rect(0, 0, width, height); context.closePath(); context.fillShape(this); }, _useBufferCanvas: function() { return (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && this.hasStroke(); }, _setInterval: function() { var that = this; this.interval = setInterval(function() { that._updateIndex(); }, 1000 / this.getFrameRate()); }, /** * start sprite animation * @method * @memberof Kinetic.Sprite.prototype */ start: function() { var layer = this.getLayer(); /* * animation object has no executable function because * the updates are done with a fixed FPS with the setInterval * below. The anim object only needs the layer reference for * redraw */ this.anim.setLayers(layer); this._setInterval(); this.anim.start(); }, /** * stop sprite animation * @method * @memberof Kinetic.Sprite.prototype */ stop: function() { this.anim.stop(); clearInterval(this.interval); }, /** * determine if animation of sprite is running or not. returns true or false * @method * @memberof Kinetic.Animation.prototype * @returns {Boolean} */ isRunning: function() { return this.anim.isRunning(); }, _updateIndex: function() { var index = this.frameIndex(), animation = this.getAnimation(), animations = this.getAnimations(), anim = animations[animation], len = anim.length / 4; if(index < len - 1) { this.frameIndex(index + 1); } else { this.frameIndex(0); } } }; Kinetic.Util.extend(Kinetic.Sprite, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'animation'); /** * get/set animation key * @name animation * @method * @memberof Kinetic.Sprite.prototype * @param {String} anim animation key * @returns {String} * @example * // get animation key<br> * var animation = sprite.animation();<br><br> * * // set animation key<br> * sprite.animation('kicking'); */ Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'animations'); /** * get/set animations map * @name animations * @method * @memberof Kinetic.Sprite.prototype * @param {Object} animations * @returns {Object} * @example * // get animations map<br> * var animations = sprite.animations();<br><br> * * // set animations map<br> * sprite.animations({<br> * standing: [<br> * // x, y, width, height (6 frames)<br> * 0, 0, 49, 109,<br> * 52, 0, 49, 109,<br> * 105, 0, 49, 109,<br> * 158, 0, 49, 109,<br> * 210, 0, 49, 109,<br> * 262, 0, 49, 109<br> * ],<br> * kicking: [<br> * // x, y, width, height (6 frames)<br> * 0, 109, 45, 98,<br> * 45, 109, 45, 98,<br> * 95, 109, 63, 98,<br> * 156, 109, 70, 98,<br> * 229, 109, 60, 98,<br> * 287, 109, 41, 98<br> * ]<br> * }); */ Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'image'); /** * get/set image * @name image * @method * @memberof Kinetic.Sprite.prototype * @param {Image} image * @returns {Image} * @example * // get image * var image = sprite.image();<br><br> * * // set image<br> * sprite.image(imageObj); */ Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'frameIndex', 0); /** * set/set animation frame index * @name frameIndex * @method * @memberof Kinetic.Sprite.prototype * @param {Integer} frameIndex * @returns {Integer} * @example * // get animation frame index<br> * var frameIndex = sprite.frameIndex();<br><br> * * // set animation frame index<br> * sprite.frameIndex(3); */ Kinetic.Factory.addGetterSetter(Kinetic.Sprite, 'frameRate', 17); /** * get/set frame rate in frames per second. Increase this number to make the sprite * animation run faster, and decrease the number to make the sprite animation run slower * The default is 17 frames per second * @name frameRate * @method * @memberof Kinetic.Sprite.prototype * @param {Integer} frameRate * @returns {Integer} * @example * // get frame rate<br> * var frameRate = sprite.frameRate();<br><br> * * // set frame rate to 2 frames per second<br> * sprite.frameRate(2); */ Kinetic.Factory.backCompat(Kinetic.Sprite, { index: 'frameIndex', getIndex: 'getFrameIndex', setIndex: 'setFrameIndex' }); Kinetic.Collection.mapMethods(Kinetic.Sprite); })(); ;(function () { /** * Path constructor. * @author Jason Follas * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {String} config.data SVG data string * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var path = new Kinetic.Path({<br> * x: 240,<br> * y: 40,<br> * data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z',<br> * fill: 'green',<br> * scale: 2<br> * }); */ Kinetic.Path = function (config) { this.___init(config); }; Kinetic.Path.prototype = { ___init: function (config) { this.dataArray = []; var that = this; // call super constructor Kinetic.Shape.call(this, config); this.className = 'Path'; this.dataArray = Kinetic.Path.parsePathData(this.getData()); this.on('dataChange.kinetic', function () { that.dataArray = Kinetic.Path.parsePathData(this.getData()); }); this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var ca = this.dataArray, closedPath = false; // context position context.beginPath(); for (var n = 0; n < ca.length; n++) { var c = ca[n].command; var p = ca[n].points; switch (c) { case 'L': context.lineTo(p[0], p[1]); break; case 'M': context.moveTo(p[0], p[1]); break; case 'C': context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]); break; case 'Q': context.quadraticCurveTo(p[0], p[1], p[2], p[3]); break; case 'A': var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7]; var r = (rx > ry) ? rx : ry; var scaleX = (rx > ry) ? 1 : rx / ry; var scaleY = (rx > ry) ? ry / rx : 1; context.translate(cx, cy); context.rotate(psi); context.scale(scaleX, scaleY); context.arc(0, 0, r, theta, theta + dTheta, 1 - fs); context.scale(1 / scaleX, 1 / scaleY); context.rotate(-psi); context.translate(-cx, -cy); break; case 'z': context.closePath(); closedPath = true; break; } } if (closedPath) { context.fillStrokeShape(this); } else { context.strokeShape(this); } } }; Kinetic.Util.extend(Kinetic.Path, Kinetic.Shape); Kinetic.Path.getLineLength = function(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); }; Kinetic.Path.getPointOnLine = function(dist, P1x, P1y, P2x, P2y, fromX, fromY) { if(fromX === undefined) { fromX = P1x; } if(fromY === undefined) { fromY = P1y; } var m = (P2y - P1y) / ((P2x - P1x) + 0.00000001); var run = Math.sqrt(dist * dist / (1 + m * m)); if(P2x < P1x) { run *= -1; } var rise = m * run; var pt; if (P2x === P1x) { // vertical line pt = { x: fromX, y: fromY + rise }; } else if((fromY - P1y) / ((fromX - P1x) + 0.00000001) === m) { pt = { x: fromX + run, y: fromY + rise }; } else { var ix, iy; var len = this.getLineLength(P1x, P1y, P2x, P2y); if(len < 0.00000001) { return undefined; } var u = (((fromX - P1x) * (P2x - P1x)) + ((fromY - P1y) * (P2y - P1y))); u = u / (len * len); ix = P1x + u * (P2x - P1x); iy = P1y + u * (P2y - P1y); var pRise = this.getLineLength(fromX, fromY, ix, iy); var pRun = Math.sqrt(dist * dist - pRise * pRise); run = Math.sqrt(pRun * pRun / (1 + m * m)); if(P2x < P1x) { run *= -1; } rise = m * run; pt = { x: ix + run, y: iy + rise }; } return pt; }; Kinetic.Path.getPointOnCubicBezier = function(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) { function CB1(t) { return t * t * t; } function CB2(t) { return 3 * t * t * (1 - t); } function CB3(t) { return 3 * t * (1 - t) * (1 - t); } function CB4(t) { return (1 - t) * (1 - t) * (1 - t); } var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct); var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct); return { x: x, y: y }; }; Kinetic.Path.getPointOnQuadraticBezier = function(pct, P1x, P1y, P2x, P2y, P3x, P3y) { function QB1(t) { return t * t; } function QB2(t) { return 2 * t * (1 - t); } function QB3(t) { return (1 - t) * (1 - t); } var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct); var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct); return { x: x, y: y }; }; Kinetic.Path.getPointOnEllipticalArc = function(cx, cy, rx, ry, theta, psi) { var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi); var pt = { x: rx * Math.cos(theta), y: ry * Math.sin(theta) }; return { x: cx + (pt.x * cosPsi - pt.y * sinPsi), y: cy + (pt.x * sinPsi + pt.y * cosPsi) }; }; /* * get parsed data array from the data * string. V, v, H, h, and l data are converted to * L data for the purpose of high performance Path * rendering */ Kinetic.Path.parsePathData = function(data) { // Path Data Segment must begin with a moveTo //m (x y)+ Relative moveTo (subsequent points are treated as lineTo) //M (x y)+ Absolute moveTo (subsequent points are treated as lineTo) //l (x y)+ Relative lineTo //L (x y)+ Absolute LineTo //h (x)+ Relative horizontal lineTo //H (x)+ Absolute horizontal lineTo //v (y)+ Relative vertical lineTo //V (y)+ Absolute vertical lineTo //z (closepath) //Z (closepath) //c (x1 y1 x2 y2 x y)+ Relative Bezier curve //C (x1 y1 x2 y2 x y)+ Absolute Bezier curve //q (x1 y1 x y)+ Relative Quadratic Bezier //Q (x1 y1 x y)+ Absolute Quadratic Bezier //t (x y)+ Shorthand/Smooth Relative Quadratic Bezier //T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier //s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve //S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve //a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc //A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc // return early if data is not defined if(!data) { return []; } // command string var cs = data; // command chars var cc = ['m', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A']; // convert white spaces to commas cs = cs.replace(new RegExp(' ', 'g'), ','); // create pipes so that we can split the data for(var n = 0; n < cc.length; n++) { cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); } // create array var arr = cs.split('|'); var ca = []; // init context point var cpx = 0; var cpy = 0; for( n = 1; n < arr.length; n++) { var str = arr[n]; var c = str.charAt(0); str = str.slice(1); // remove ,- for consistency str = str.replace(new RegExp(',-', 'g'), '-'); // add commas so that it's easy to split str = str.replace(new RegExp('-', 'g'), ',-'); str = str.replace(new RegExp('e,-', 'g'), 'e-'); var p = str.split(','); if(p.length > 0 && p[0] === '') { p.shift(); } // convert strings to floats for(var i = 0; i < p.length; i++) { p[i] = parseFloat(p[i]); } while(p.length > 0) { if(isNaN(p[0])) {// case for a trailing comma before next command break; } var cmd = null; var points = []; var startX = cpx, startY = cpy; // Move var from within the switch to up here (jshint) var prevCmd, ctlPtx, ctlPty; // Ss, Tt var rx, ry, psi, fa, fs, x1, y1; // Aa // convert l, H, h, V, and v to L switch (c) { // Note: Keep the lineTo's above the moveTo's in this switch case 'l': cpx += p.shift(); cpy += p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'L': cpx = p.shift(); cpy = p.shift(); points.push(cpx, cpy); break; // Note: lineTo handlers need to be above this point case 'm': var dx = p.shift(); var dy = p.shift(); cpx += dx; cpy += dy; cmd = 'M'; // After closing the path move the current position // to the the first point of the path (if any). if(ca.length>2 && ca[ca.length-1].command==='z'){ for(var idx=ca.length-2;idx>=0;idx--){ if(ca[idx].command==='M'){ cpx=ca[idx].points[0]+dx; cpy=ca[idx].points[1]+dy; break; } } } points.push(cpx, cpy); c = 'l'; // subsequent points are treated as relative lineTo break; case 'M': cpx = p.shift(); cpy = p.shift(); cmd = 'M'; points.push(cpx, cpy); c = 'L'; // subsequent points are treated as absolute lineTo break; case 'h': cpx += p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'H': cpx = p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'v': cpy += p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'V': cpy = p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'C': points.push(p.shift(), p.shift(), p.shift(), p.shift()); cpx = p.shift(); cpy = p.shift(); points.push(cpx, cpy); break; case 'c': points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift()); cpx += p.shift(); cpy += p.shift(); cmd = 'C'; points.push(cpx, cpy); break; case 'S': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if(prevCmd.command === 'C') { ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPty = cpy + (cpy - prevCmd.points[3]); } points.push(ctlPtx, ctlPty, p.shift(), p.shift()); cpx = p.shift(); cpy = p.shift(); cmd = 'C'; points.push(cpx, cpy); break; case 's': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if(prevCmd.command === 'C') { ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPty = cpy + (cpy - prevCmd.points[3]); } points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift()); cpx += p.shift(); cpy += p.shift(); cmd = 'C'; points.push(cpx, cpy); break; case 'Q': points.push(p.shift(), p.shift()); cpx = p.shift(); cpy = p.shift(); points.push(cpx, cpy); break; case 'q': points.push(cpx + p.shift(), cpy + p.shift()); cpx += p.shift(); cpy += p.shift(); cmd = 'Q'; points.push(cpx, cpy); break; case 'T': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if(prevCmd.command === 'Q') { ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPty = cpy + (cpy - prevCmd.points[1]); } cpx = p.shift(); cpy = p.shift(); cmd = 'Q'; points.push(ctlPtx, ctlPty, cpx, cpy); break; case 't': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if(prevCmd.command === 'Q') { ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPty = cpy + (cpy - prevCmd.points[1]); } cpx += p.shift(); cpy += p.shift(); cmd = 'Q'; points.push(ctlPtx, ctlPty, cpx, cpy); break; case 'A': rx = p.shift(); ry = p.shift(); psi = p.shift(); fa = p.shift(); fs = p.shift(); x1 = cpx; y1 = cpy; cpx = p.shift(); cpy = p.shift(); cmd = 'A'; points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); break; case 'a': rx = p.shift(); ry = p.shift(); psi = p.shift(); fa = p.shift(); fs = p.shift(); x1 = cpx; y1 = cpy; cpx += p.shift(); cpy += p.shift(); cmd = 'A'; points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); break; } ca.push({ command: cmd || c, points: points, start: { x: startX, y: startY }, pathLength: this.calcLength(startX, startY, cmd || c, points) }); } if(c === 'z' || c === 'Z') { ca.push({ command: 'z', points: [], start: undefined, pathLength: 0 }); } } return ca; }; Kinetic.Path.calcLength = function(x, y, cmd, points) { var len, p1, p2, t; var path = Kinetic.Path; switch (cmd) { case 'L': return path.getLineLength(x, y, points[0], points[1]); case 'C': // Approximates by breaking curve into 100 line segments len = 0.0; p1 = path.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]); for( t = 0.01; t <= 1; t += 0.01) { p2 = path.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]); len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); p1 = p2; } return len; case 'Q': // Approximates by breaking curve into 100 line segments len = 0.0; p1 = path.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]); for( t = 0.01; t <= 1; t += 0.01) { p2 = path.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]); len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); p1 = p2; } return len; case 'A': // Approximates by breaking curve into line segments len = 0.0; var start = points[4]; // 4 = theta var dTheta = points[5]; // 5 = dTheta var end = points[4] + dTheta; var inc = Math.PI / 180.0; // 1 degree resolution if(Math.abs(start - end) < inc) { inc = Math.abs(start - end); } // Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi p1 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0); if(dTheta < 0) {// clockwise for( t = start - inc; t > end; t -= inc) { p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0); len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); p1 = p2; } } else {// counter-clockwise for( t = start + inc; t < end; t += inc) { p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0); len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); p1 = p2; } } p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0); len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); return len; } return 0; }; Kinetic.Path.convertEndpointToCenterParameterization = function(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { // Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes var psi = psiDeg * (Math.PI / 180.0); var xp = Math.cos(psi) * (x1 - x2) / 2.0 + Math.sin(psi) * (y1 - y2) / 2.0; var yp = -1 * Math.sin(psi) * (x1 - x2) / 2.0 + Math.cos(psi) * (y1 - y2) / 2.0; var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); if(lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } var f = Math.sqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp))); if(fa === fs) { f *= -1; } if(isNaN(f)) { f = 0; } var cxp = f * rx * yp / ry; var cyp = f * -ry * xp / rx; var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; var vMag = function(v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; var vRatio = function(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); }; var vAngle = function(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); }; var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); var u = [(xp - cxp) / rx, (yp - cyp) / ry]; var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; var dTheta = vAngle(u, v); if(vRatio(u, v) <= -1) { dTheta = Math.PI; } if(vRatio(u, v) >= 1) { dTheta = 0; } if(fs === 0 && dTheta > 0) { dTheta = dTheta - 2 * Math.PI; } if(fs === 1 && dTheta < 0) { dTheta = dTheta + 2 * Math.PI; } return [cx, cy, rx, ry, theta, dTheta, psi, fs]; }; // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Path, 'data'); /** * set SVG path data string. This method * also automatically parses the data string * into a data array. Currently supported SVG data: * M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z * @name setData * @method * @memberof Kinetic.Path.prototype * @param {String} SVG path command string */ /** * get SVG path data string * @name getData * @method * @memberof Kinetic.Path.prototype */ Kinetic.Collection.mapMethods(Kinetic.Path); })(); ;(function() { var EMPTY_STRING = '', //CALIBRI = 'Calibri', NORMAL = 'normal'; /** * Path constructor. * @author Jason Follas * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {String} [config.fontFamily] default is Calibri * @param {Number} [config.fontSize] default is 12 * @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal * @param {String} [config.fontVariant] can be normal or small-caps. Default is normal * @param {String} config.text * @param {String} config.data SVG data string * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var textpath = new Kinetic.TextPath({<br> * x: 100,<br> * y: 50,<br> * fill: '#333',<br> * fontSize: '24',<br> * fontFamily: 'Arial',<br> * text: 'All the world\'s a stage, and all the men and women merely players.',<br> * data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50'<br> * }); */ Kinetic.TextPath = function(config) { this.___init(config); }; function _fillFunc(context) { context.fillText(this.partialText, 0, 0); } function _strokeFunc(context) { context.strokeText(this.partialText, 0, 0); } Kinetic.TextPath.prototype = { ___init: function(config) { var that = this; this.dummyCanvas = Kinetic.Util.createCanvasElement(); this.dataArray = []; // call super constructor Kinetic.Shape.call(this, config); // overrides // TODO: shouldn't this be on the prototype? this._fillFunc = _fillFunc; this._strokeFunc = _strokeFunc; this._fillFuncHit = _fillFunc; this._strokeFuncHit = _strokeFunc; this.className = 'TextPath'; this.dataArray = Kinetic.Path.parsePathData(this.attrs.data); this.on('dataChange.kinetic', function() { that.dataArray = Kinetic.Path.parsePathData(this.attrs.data); }); // update text data for certain attr changes this.on('textChange.kinetic textStroke.kinetic textStrokeWidth.kinetic', that._setTextData); that._setTextData(); this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { context.setAttr('font', this._getContextFont()); context.setAttr('textBaseline', 'middle'); context.setAttr('textAlign', 'left'); context.save(); var glyphInfo = this.glyphInfo; for(var i = 0; i < glyphInfo.length; i++) { context.save(); var p0 = glyphInfo[i].p0; context.translate(p0.x, p0.y); context.rotate(glyphInfo[i].rotation); this.partialText = glyphInfo[i].text; context.fillStrokeShape(this); context.restore(); //// To assist with debugging visually, uncomment following // context.beginPath(); // if (i % 2) // context.strokeStyle = 'cyan'; // else // context.strokeStyle = 'green'; // var p1 = glyphInfo[i].p1; // context.moveTo(p0.x, p0.y); // context.lineTo(p1.x, p1.y); // context.stroke(); } context.restore(); }, /** * get text width in pixels * @method * @memberof Kinetic.TextPath.prototype */ getTextWidth: function() { return this.textWidth; }, /** * get text height in pixels * @method * @memberof Kinetic.TextPath.prototype */ getTextHeight: function() { return this.textHeight; }, /** * set text * @method * @memberof Kinetic.TextPath.prototype * @param {String} text */ setText: function(text) { Kinetic.Text.prototype.setText.call(this, text); }, _getTextSize: function(text) { var dummyCanvas = this.dummyCanvas; var _context = dummyCanvas.getContext('2d'); _context.save(); _context.font = this._getContextFont(); var metrics = _context.measureText(text); _context.restore(); return { width: metrics.width, height: parseInt(this.attrs.fontSize, 10) }; }, _setTextData: function() { var that = this; var size = this._getTextSize(this.attrs.text); this.textWidth = size.width; this.textHeight = size.height; this.glyphInfo = []; var charArr = this.attrs.text.split(''); var p0, p1, pathCmd; var pIndex = -1; var currentT = 0; var getNextPathSegment = function() { currentT = 0; var pathData = that.dataArray; for(var i = pIndex + 1; i < pathData.length; i++) { if(pathData[i].pathLength > 0) { pIndex = i; return pathData[i]; } else if(pathData[i].command == 'M') { p0 = { x: pathData[i].points[0], y: pathData[i].points[1] }; } } return {}; }; var findSegmentToFitCharacter = function(c) { var glyphWidth = that._getTextSize(c).width; var currLen = 0; var attempts = 0; p1 = undefined; while(Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 && attempts < 25) { attempts++; var cumulativePathLength = currLen; while(pathCmd === undefined) { pathCmd = getNextPathSegment(); if(pathCmd && cumulativePathLength + pathCmd.pathLength < glyphWidth) { cumulativePathLength += pathCmd.pathLength; pathCmd = undefined; } } if(pathCmd === {} || p0 === undefined) { return undefined; } var needNewSegment = false; switch (pathCmd.command) { case 'L': if(Kinetic.Path.getLineLength(p0.x, p0.y, pathCmd.points[0], pathCmd.points[1]) > glyphWidth) { p1 = Kinetic.Path.getPointOnLine(glyphWidth, p0.x, p0.y, pathCmd.points[0], pathCmd.points[1], p0.x, p0.y); } else { pathCmd = undefined; } break; case 'A': var start = pathCmd.points[4]; // 4 = theta var dTheta = pathCmd.points[5]; // 5 = dTheta var end = pathCmd.points[4] + dTheta; if(currentT === 0){ currentT = start + 0.00000001; } // Just in case start is 0 else if(glyphWidth > currLen) { currentT += (Math.PI / 180.0) * dTheta / Math.abs(dTheta); } else { currentT -= Math.PI / 360.0 * dTheta / Math.abs(dTheta); } // Credit for bug fix: @therth https://github.com/ericdrowell/KineticJS/issues/249 // Old code failed to render text along arc of this path: "M 50 50 a 150 50 0 0 1 250 50 l 50 0" if(dTheta < 0 && currentT < end || dTheta >= 0 && currentT > end) { currentT = end; needNewSegment = true; } p1 = Kinetic.Path.getPointOnEllipticalArc(pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], currentT, pathCmd.points[6]); break; case 'C': if(currentT === 0) { if(glyphWidth > pathCmd.pathLength) { currentT = 0.00000001; } else { currentT = glyphWidth / pathCmd.pathLength; } } else if(glyphWidth > currLen) { currentT += (glyphWidth - currLen) / pathCmd.pathLength; } else { currentT -= (currLen - glyphWidth) / pathCmd.pathLength; } if(currentT > 1.0) { currentT = 1.0; needNewSegment = true; } p1 = Kinetic.Path.getPointOnCubicBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3], pathCmd.points[4], pathCmd.points[5]); break; case 'Q': if(currentT === 0) { currentT = glyphWidth / pathCmd.pathLength; } else if(glyphWidth > currLen) { currentT += (glyphWidth - currLen) / pathCmd.pathLength; } else { currentT -= (currLen - glyphWidth) / pathCmd.pathLength; } if(currentT > 1.0) { currentT = 1.0; needNewSegment = true; } p1 = Kinetic.Path.getPointOnQuadraticBezier(currentT, pathCmd.start.x, pathCmd.start.y, pathCmd.points[0], pathCmd.points[1], pathCmd.points[2], pathCmd.points[3]); break; } if(p1 !== undefined) { currLen = Kinetic.Path.getLineLength(p0.x, p0.y, p1.x, p1.y); } if(needNewSegment) { needNewSegment = false; pathCmd = undefined; } } }; for(var i = 0; i < charArr.length; i++) { // Find p1 such that line segment between p0 and p1 is approx. width of glyph findSegmentToFitCharacter(charArr[i]); if(p0 === undefined || p1 === undefined) { break; } var width = Kinetic.Path.getLineLength(p0.x, p0.y, p1.x, p1.y); // Note: Since glyphs are rendered one at a time, any kerning pair data built into the font will not be used. // Can foresee having a rough pair table built in that the developer can override as needed. var kern = 0; // placeholder for future implementation var midpoint = Kinetic.Path.getPointOnLine(kern + width / 2.0, p0.x, p0.y, p1.x, p1.y); var rotation = Math.atan2((p1.y - p0.y), (p1.x - p0.x)); this.glyphInfo.push({ transposeX: midpoint.x, transposeY: midpoint.y, text: charArr[i], rotation: rotation, p0: p0, p1: p1 }); p0 = p1; } } }; // map TextPath methods to Text Kinetic.TextPath.prototype._getContextFont = Kinetic.Text.prototype._getContextFont; Kinetic.Util.extend(Kinetic.TextPath, Kinetic.Shape); // add setters and getters Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontFamily', 'Arial'); /** * set font family * @name setFontFamily * @method * @memberof Kinetic.TextPath.prototype * @param {String} fontFamily */ /** * get font family * @name getFontFamily * @method * @memberof Kinetic.TextPath.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontSize', 12); /** * set font size * @name setFontSize * @method * @memberof Kinetic.TextPath.prototype * @param {int} fontSize */ /** * get font size * @name getFontSize * @method * @memberof Kinetic.TextPath.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontStyle', NORMAL); /** * set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default. * @name setFontStyle * @method * @memberof Kinetic.TextPath.prototype * @param {String} fontStyle */ /** * get font style * @name getFontStyle * @method * @memberof Kinetic.TextPath.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.TextPath, 'fontVariant', NORMAL); /** * set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default. * @name setFontVariant * @method * @memberof Kinetic.TextPath.prototype * @param {String} fontVariant */ /** * @get font variant * @name getFontVariant * @method * @memberof Kinetic.TextPath.prototype */ Kinetic.Factory.addGetter(Kinetic.TextPath, 'text', EMPTY_STRING); /** * get text * @name getText * @method * @memberof Kinetic.TextPath.prototype */ Kinetic.Collection.mapMethods(Kinetic.TextPath); })(); ;(function() { /** * RegularPolygon constructor.&nbsp; Examples include triangles, squares, pentagons, hexagons, etc. * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {Number} config.sides * @param {Number} config.radius * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var hexagon = new Kinetic.RegularPolygon({<br> * x: 100,<br> * y: 200,<br> * sides: 6,<br> * radius: 70,<br> * fill: 'red',<br> * stroke: 'black',<br> * strokeWidth: 4<br> * }); */ Kinetic.RegularPolygon = function(config) { this.___init(config); }; Kinetic.RegularPolygon.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'RegularPolygon'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var sides = this.attrs.sides, radius = this.attrs.radius, n, x, y; context.beginPath(); context.moveTo(0, 0 - radius); for(n = 1; n < sides; n++) { x = radius * Math.sin(n * 2 * Math.PI / sides); y = -1 * radius * Math.cos(n * 2 * Math.PI / sides); context.lineTo(x, y); } context.closePath(); context.fillStrokeShape(this); } }; Kinetic.Util.extend(Kinetic.RegularPolygon, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon, 'radius', 0); /** * set radius * @name setRadius * @method * @memberof Kinetic.RegularPolygon.prototype * @param {Number} radius */ /** * get radius * @name getRadius * @method * @memberof Kinetic.RegularPolygon.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon, 'sides', 0); /** * set number of sides * @name setSides * @method * @memberof Kinetic.RegularPolygon.prototype * @param {int} sides */ /** * get number of sides * @name getSides * @method * @memberof Kinetic.RegularPolygon.prototype */ Kinetic.Collection.mapMethods(Kinetic.RegularPolygon); })(); ;(function() { /** * Star constructor * @constructor * @memberof Kinetic * @augments Kinetic.Shape * @param {Object} config * @param {Integer} config.numPoints * @param {Number} config.innerRadius * @param {Number} config.outerRadius * @param {String} [config.fill] fill color * @param {Integer} [config.fillRed] set fill red component * @param {Integer} [config.fillGreen] set fill green component * @param {Integer} [config.fillBlue] set fill blue component * @param {Integer} [config.fillAlpha] set fill alpha component * @param {Image} [config.fillPatternImage] fill pattern image * @param {Number} [config.fillPatternX] * @param {Number} [config.fillPatternY] * @param {Object} [config.fillPatternOffset] object with x and y component * @param {Number} [config.fillPatternOffsetX] * @param {Number} [config.fillPatternOffsetY] * @param {Object} [config.fillPatternScale] object with x and y component * @param {Number} [config.fillPatternScaleX] * @param {Number} [config.fillPatternScaleY] * @param {Number} [config.fillPatternRotation] * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component * @param {Number} [config.fillLinearGradientStartPointX] * @param {Number} [config.fillLinearGradientStartPointY] * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component * @param {Number} [config.fillLinearGradientEndPointX] * @param {Number} [config.fillLinearGradientEndPointY] * @param {Array} [config.fillLinearGradientColorStops] array of color stops * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component * @param {Number} [config.fillRadialGradientStartPointX] * @param {Number} [config.fillRadialGradientStartPointY] * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component * @param {Number} [config.fillRadialGradientEndPointX] * @param {Number} [config.fillRadialGradientEndPointY] * @param {Number} [config.fillRadialGradientStartRadius] * @param {Number} [config.fillRadialGradientEndRadius] * @param {Array} [config.fillRadialGradientColorStops] array of color stops * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration * @param {String} [config.stroke] stroke color * @param {Integer} [config.strokeRed] set stroke red component * @param {Integer} [config.strokeGreen] set stroke green component * @param {Integer} [config.strokeBlue] set stroke blue component * @param {Integer} [config.strokeAlpha] set stroke alpha component * @param {Number} [config.strokeWidth] stroke width * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true * @param {String} [config.lineJoin] can be miter, round, or bevel. The default * is miter * @param {String} [config.lineCap] can be butt, round, or sqare. The default * is butt * @param {String} [config.shadowColor] * @param {Integer} [config.shadowRed] set shadow color red component * @param {Integer} [config.shadowGreen] set shadow color green component * @param {Integer} [config.shadowBlue] set shadow color blue component * @param {Integer} [config.shadowAlpha] set shadow color alpha component * @param {Number} [config.shadowBlur] * @param {Object} [config.shadowOffset] object with x and y component * @param {Number} [config.shadowOffsetX] * @param {Number} [config.shadowOffsetY] * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number * between 0 and 1 * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true * @param {Array} [config.dash] * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * var star = new Kinetic.Star({<br> * x: 100,<br> * y: 200,<br> * numPoints: 5,<br> * innerRadius: 70,<br> * outerRadius: 70,<br> * fill: 'red',<br> * stroke: 'black',<br> * strokeWidth: 4<br> * }); */ Kinetic.Star = function(config) { this.___init(config); }; Kinetic.Star.prototype = { ___init: function(config) { // call super constructor Kinetic.Shape.call(this, config); this.className = 'Star'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var innerRadius = this.innerRadius(), outerRadius = this.outerRadius(), numPoints = this.numPoints(); context.beginPath(); context.moveTo(0, 0 - outerRadius); for(var n = 1; n < numPoints * 2; n++) { var radius = n % 2 === 0 ? outerRadius : innerRadius; var x = radius * Math.sin(n * Math.PI / numPoints); var y = -1 * radius * Math.cos(n * Math.PI / numPoints); context.lineTo(x, y); } context.closePath(); context.fillStrokeShape(this); } }; Kinetic.Util.extend(Kinetic.Star, Kinetic.Shape); // add getters setters Kinetic.Factory.addGetterSetter(Kinetic.Star, 'numPoints', 5); /** * set number of points * @name setNumPoints * @method * @memberof Kinetic.Star.prototype * @param {Integer} points */ /** * get number of points * @name getNumPoints * @method * @memberof Kinetic.Star.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.Star, 'innerRadius', 0); /** * set inner radius * @name setInnerRadius * @method * @memberof Kinetic.Star.prototype * @param {Number} radius */ /** * get inner radius * @name getInnerRadius * @method * @memberof Kinetic.Star.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.Star, 'outerRadius', 0); /** * set outer radius * @name setOuterRadius * @method * @memberof Kinetic.Star.prototype * @param {Number} radius */ /** * get outer radius * @name getOuterRadius * @method * @memberof Kinetic.Star.prototype */ Kinetic.Collection.mapMethods(Kinetic.Star); })(); ;(function() { // constants var ATTR_CHANGE_LIST = ['fontFamily', 'fontSize', 'fontStyle', 'padding', 'lineHeight', 'text'], CHANGE_KINETIC = 'Change.kinetic', NONE = 'none', UP = 'up', RIGHT = 'right', DOWN = 'down', LEFT = 'left', LABEL = 'Label', // cached variables attrChangeListLen = ATTR_CHANGE_LIST.length; /** * Label constructor.&nbsp; Labels are groups that contain a Text and Tag shape * @constructor * @memberof Kinetic * @param {Object} config * @param {Number} [config.x] * @param {Number} [config.y] * @param {Number} [config.width] * @param {Number} [config.height] * @param {Boolean} [config.visible] * @param {Boolean} [config.listening] whether or not the node is listening for events * @param {String} [config.id] unique id * @param {String} [config.name] non-unique name * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 * @param {Object} [config.scale] set scale * @param {Number} [config.scaleX] set scale x * @param {Number} [config.scaleY] set scale y * @param {Number} [config.rotation] rotation in degrees * @param {Object} [config.offset] offset from center point and rotation point * @param {Number} [config.offsetX] set offset x * @param {Number} [config.offsetY] set offset y * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop * the entire stage by dragging any portion of the stage * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] * @example * // create label * var label = new Kinetic.Label({<br> * x: 100,<br> * y: 100, <br> * draggable: true<br> * });<br><br> * * // add a tag to the label<br> * label.add(new Kinetic.Tag({<br> * fill: '#bbb',<br> * stroke: '#333',<br> * shadowColor: 'black',<br> * shadowBlur: 10,<br> * shadowOffset: [10, 10],<br> * shadowOpacity: 0.2,<br> * lineJoin: 'round',<br> * pointerDirection: 'up',<br> * pointerWidth: 20,<br> * pointerHeight: 20,<br> * cornerRadius: 5<br> * }));<br><br> * * // add text to the label<br> * label.add(new Kinetic.Text({<br> * text: 'Hello World!',<br> * fontSize: 50,<br> * lineHeight: 1.2,<br> * padding: 10,<br> * fill: 'green'<br> * })); */ Kinetic.Label = function(config) { this.____init(config); }; Kinetic.Label.prototype = { ____init: function(config) { var that = this; this.className = LABEL; Kinetic.Group.call(this, config); this.on('add.kinetic', function(evt) { that._addListeners(evt.child); that._sync(); }); }, /** * get Text shape for the label. You need to access the Text shape in order to update * the text properties * @name getText * @method * @memberof Kinetic.Label.prototype */ getText: function() { return this.find('Text')[0]; }, /** * get Tag shape for the label. You need to access the Tag shape in order to update * the pointer properties and the corner radius * @name getTag * @method * @memberof Kinetic.Label.prototype */ getTag: function() { return this.find('Tag')[0]; }, _addListeners: function(text) { var that = this, n; var func = function(){ that._sync(); }; // update text data for certain attr changes for(n = 0; n < attrChangeListLen; n++) { text.on(ATTR_CHANGE_LIST[n] + CHANGE_KINETIC, func); } }, getWidth: function() { return this.getText().getWidth(); }, getHeight: function() { return this.getText().getHeight(); }, _sync: function() { var text = this.getText(), tag = this.getTag(), width, height, pointerDirection, pointerWidth, x, y, pointerHeight; if (text && tag) { width = text.getWidth(); height = text.getHeight(); pointerDirection = tag.getPointerDirection(); pointerWidth = tag.getPointerWidth(); pointerHeight = tag.getPointerHeight(); x = 0; y = 0; switch(pointerDirection) { case UP: x = width / 2; y = -1 * pointerHeight; break; case RIGHT: x = width + pointerWidth; y = height / 2; break; case DOWN: x = width / 2; y = height + pointerHeight; break; case LEFT: x = -1 * pointerWidth; y = height / 2; break; } tag.setAttrs({ x: -1 * x, y: -1 * y, width: width, height: height }); text.setAttrs({ x: -1 * x, y: -1 * y }); } } }; Kinetic.Util.extend(Kinetic.Label, Kinetic.Group); Kinetic.Collection.mapMethods(Kinetic.Label); /** * Tag constructor.&nbsp; A Tag can be configured * to have a pointer element that points up, right, down, or left * @constructor * @memberof Kinetic * @param {Object} config * @param {String} [config.pointerDirection] can be up, right, down, left, or none; the default * is none. When a pointer is present, the positioning of the label is relative to the tip of the pointer. * @param {Number} [config.pointerWidth] * @param {Number} [config.pointerHeight] * @param {Number} [config.cornerRadius] */ Kinetic.Tag = function(config) { this.___init(config); }; Kinetic.Tag.prototype = { ___init: function(config) { Kinetic.Shape.call(this, config); this.className = 'Tag'; this.sceneFunc(this._sceneFunc); }, _sceneFunc: function(context) { var width = this.getWidth(), height = this.getHeight(), pointerDirection = this.getPointerDirection(), pointerWidth = this.getPointerWidth(), pointerHeight = this.getPointerHeight(); //cornerRadius = this.getCornerRadius(); context.beginPath(); context.moveTo(0,0); if (pointerDirection === UP) { context.lineTo((width - pointerWidth)/2, 0); context.lineTo(width/2, -1 * pointerHeight); context.lineTo((width + pointerWidth)/2, 0); } context.lineTo(width, 0); if (pointerDirection === RIGHT) { context.lineTo(width, (height - pointerHeight)/2); context.lineTo(width + pointerWidth, height/2); context.lineTo(width, (height + pointerHeight)/2); } context.lineTo(width, height); if (pointerDirection === DOWN) { context.lineTo((width + pointerWidth)/2, height); context.lineTo(width/2, height + pointerHeight); context.lineTo((width - pointerWidth)/2, height); } context.lineTo(0, height); if (pointerDirection === LEFT) { context.lineTo(0, (height + pointerHeight)/2); context.lineTo(-1 * pointerWidth, height/2); context.lineTo(0, (height - pointerHeight)/2); } context.closePath(); context.fillStrokeShape(this); } }; Kinetic.Util.extend(Kinetic.Tag, Kinetic.Shape); Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerDirection', NONE); /** * set pointer Direction * @name setPointerDirection * @method * @memberof Kinetic.Tag.prototype * @param {String} pointerDirection can be up, right, down, left, or none. The * default is none */ /** * get pointer Direction * @name getPointerDirection * @method * @memberof Kinetic.Tag.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerWidth', 0); /** * set pointer width * @name setPointerWidth * @method * @memberof Kinetic.Tag.prototype * @param {Number} pointerWidth */ /** * get pointer width * @name getPointerWidth * @method * @memberof Kinetic.Tag.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'pointerHeight', 0); /** * set pointer height * @name setPointerHeight * @method * @memberof Kinetic.Tag.prototype * @param {Number} pointerHeight */ /** * get pointer height * @name getPointerHeight * @method * @memberof Kinetic.Tag.prototype */ Kinetic.Factory.addGetterSetter(Kinetic.Tag, 'cornerRadius', 0); /** * set corner radius * @name setCornerRadius * @method * @memberof Kinetic.Tag.prototype * @param {Number} corner radius */ /** * get corner radius * @name getCornerRadius * @method * @memberof Kinetic.Tag.prototype */ Kinetic.Collection.mapMethods(Kinetic.Tag); })();<|fim▁end|>
// added s = 0
<|file_name|>vertex_outside.rs<|end_file_name|><|fim▁begin|>use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and a vertex that is guaranteed to not be in it. #[derive(Clone, Debug)] pub struct VertexOutside<G>(pub G, pub MockVertex) where G: GuidedArbGraph, G::Graph: TestGraph; impl<G> Ensure for VertexOutside<G> where G: GuidedArbGraph, G::Graph: TestGraph, { fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self { unimplemented!() } fn validate(_c: &Self::Ensured, _: &()) -> bool { unimplemented!() } } impl_ensurer! { use<G> VertexOutside<G>: Ensure as (self.0): G where G: GuidedArbGraph, G::Graph: TestGraph, } impl<Gr> GuidedArbGraph for VertexOutside<Gr> where Gr: GuidedArbGraph, Gr::Graph: TestGraph, { fn choose_size<G: Gen>( g: &mut G, v_min: usize, v_max: usize, e_min: usize, e_max: usize, ) -> (usize, usize) { Gr::choose_size(g, v_min, v_max, e_min, e_max) } fn arbitrary_fixed<G: Gen>(g: &mut G, v_count: usize, e_count: usize) -> Self { let graph = Gr::arbitrary_fixed(g, v_count, e_count); // Find a vertex that isn't in the graph let mut v = MockVertex::arbitrary(g); while graph.graph().contains_vertex(v) { v = MockVertex::arbitrary(g); } Self(graph, v) } fn shrink_guided(&self, limits: HashSet<Limit>) -> Box<dyn Iterator<Item = Self>> { let mut result = Vec::new(); // First shrink the graph, keeping only the shrunk ones where the vertex // stays invalid result.extend( self.0 .shrink_guided(limits) .filter(|g| !g.graph().contains_vertex(self.1)) .map(|g| Self(g, self.1)), ); // We then shrink the vertex, keeping only the shrunk values // that are invalid in the graph result.extend( self.1 .shrink() .filter(|&v| self.0.graph().contains_vertex(v)) .map(|v| Self(self.0.clone(), v)), ); Box::new(result.into_iter())<|fim▁hole|><|fim▁end|>
} }
<|file_name|>cm_cloud_managed_devices.py<|end_file_name|><|fim▁begin|># coding=utf-8 # # Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """iWorkflow® Device Groups (shared) module for CM Cloud Managed Devices REST URI ``http://localhost/mgmt/shared/resolver/device-groups/cm-cloud-managed-devices`` """ from f5.iworkflow.resource import Collection from f5.iworkflow.resource import OrganizingCollection from f5.iworkflow.resource import Resource class Cm_Cloud_Managed_Devices(OrganizingCollection): def __init__(self, device_groups): super(Cm_Cloud_Managed_Devices, self).__init__(device_groups) self._meta_data['required_json_kind'] = \ 'shared:resolver:device-groups:devicegroupstate' self._meta_data['attribute_registry'] = { 'cm:shared:licensing:pools:licensepoolmembercollectionstate': Devices_s } self._meta_data['allowed_lazy_attributes'] = [ Devices_s ] class Devices_s(Collection): def __init__(self, cm_cloud_managed_devices): super(Devices_s, self).__init__(cm_cloud_managed_devices) self._meta_data['allowed_lazy_attributes'] = [Device] self._meta_data['required_json_kind'] = \ 'shared:resolver:device-groups:devicegroupdevicecollectionstate' self._meta_data['attribute_registry'] = { 'shared:resolver:device-groups:restdeviceresolverdevicestate': Device # NOQA } class Device(Resource): def __init__(self, devices_s): super(Device, self).__init__(devices_s) self._meta_data['required_json_kind'] = \ 'shared:resolver:device-groups:restdeviceresolverdevicestate' self._meta_data['required_creation_parameters'] = {<|fim▁hole|> 'address', 'password', 'userName'} self._meta_data['required_load_parameters'] = {'uuid', }<|fim▁end|>
<|file_name|>items.js<|end_file_name|><|fim▁begin|>$(function() { /* We're going to use these elements a lot, so let's save references to them * here. All of these elements are already created by the HTML code produced * by the items page. */ var $orderPanel = $('#order-panel'); var $orderPanelCloseButton = $('#order-panel-close-button'); var $itemName = $('#item-name'); var $itemDescription = $('#item-description'); var $itemQuantity = $('#item-quantity-input'); var $itemId = $('#item-id-input'); /* Show or hide the side panel. We do this by animating its `left` CSS * property, causing it to slide off screen with a negative value when * we want to hide it. */ var togglePanel = function(show) { $orderPanel.animate({ right: show ? 0 : -$orderPanel.outerWidth()}); }; /* A function to show an alert box at the top of the page. */ var showAlert = function(message, type) { /* This stuctured mess of code creates a Bootstrap-style alert box. * Note the use of chainable jQuery methods. */ var $alert = ( $('<div>') // create a <div> element .text(message) // set its text .addClass('alert') // add some CSS classes and attributes .addClass('alert-' + type) .addClass('alert-dismissible') .attr('role', 'alert') .prepend( // prepend a close button to the inner HTML $('<button>') // create a <button> element .attr('type', 'button') // and so on... .addClass('close') .attr('data-dismiss', 'alert') .html('&times;') // &times; is code for the x-symbol ) .hide() // initially hide the alert so it will slide into view );<|fim▁hole|> $('#alerts').append($alert); /* Slide the alert into view with an animation. */ $alert.slideDown(); }; /* Close the panel when the close button is clicked. */ $('#order-panel-close-button').click(function() { togglePanel(false); }); /* Whenever an element with class `item-link` is clicked, copy over the item * information to the side panel, then show the side panel. */ $('.item-link').click(function(event) { // Prevent default link navigation event.preventDefault(); var $this = $(this); $itemName.text($this.find('.item-name').text()); $itemDescription.text($this.find('.item-description').text()); $itemId.val($this.attr('data-id')); togglePanel(true); }); /* A boring detail but an important one. When the size of the window changes, * update the `left` property of the side menu so that it remains fully * hidden. */ $(window).resize(function() { if($orderPanel.offset().right < 0) { $orderPanel.offset({ right: -$orderPanel.outerWidth() }); } }); /* When the form is submitted (button is pressed or enter key is pressed), * make the Ajax call to add the item to the current order. */ $('#item-add-form').submit(function(event) { // Prevent default form submission event.preventDefault(); /* No input validation... yet. */ var quantity = $itemQuantity.val(); //get orderid var orderID; $.ajax({ type: 'PUT', url: '/orders/', contentType: 'application/json', data:JSON.stringify({ userID: 1 }), async: false, dataType: 'json' }).done(function(data) { orderID = data.orderID //showAlert('Order created successfully', 'success'); }).fail(function() { showAlert('Fail to get orderID', 'danger'); }); /* Send the data to `PUT /orders/:orderid/items/:itemid`. */ $.ajax({ /* The HTTP method. */ type: 'PUT', /* The URL. Use a dummy order ID for now. */ url: '/orders/'+orderID+'/items/' + $itemId.val(), /* The `Content-Type` header. This tells the server what format the body * of our request is in. This sets the header as * `Content-Type: application/json`. */ contentType: 'application/json', /* The request body. `JSON.stringify` formats it as JSON. */ data: JSON.stringify({ quantity: quantity }), /* The `Accept` header. This tells the server that we want to receive * JSON. This sets the header as something like * `Accept: application/json`. */ dataType: 'json' }).done(function() { /* This is called if and when the server responds with a 2XX (success) * status code. */ /* Show a success message. */ showAlert('Posted the order with id ' + orderID, 'success'); /* Close the side panel while we're at it. */ togglePanel(false); }).fail(function() { showAlert('Something went wrong.', 'danger'); }); }); });<|fim▁end|>
/* Add the alert to the alert container. */
<|file_name|>bottomNavigationClasses.d.ts<|end_file_name|><|fim▁begin|>export interface BottomNavigationClasses { /** Styles applied to the root element. */ root: string; } export declare type BottomNavigationClassKey = keyof BottomNavigationClasses; <|fim▁hole|>export declare function getBottomNavigationUtilityClass(slot: string): string; declare const bottomNavigationClasses: BottomNavigationClasses; export default bottomNavigationClasses;<|fim▁end|>
<|file_name|>polish.py<|end_file_name|><|fim▁begin|>#(c) 2016 by Authors #This file is a part of ABruijn program. #Released under the BSD license (see LICENSE file) """ Runs polishing binary in parallel and concatentes output """ from __future__ import absolute_import from __future__ import division import logging import subprocess import os from collections import defaultdict from flye.polishing.alignment import (make_alignment, get_contigs_info, merge_chunks, split_into_chunks) from flye.utils.sam_parser import SynchronizedSamReader from flye.polishing.bubbles import make_bubbles import flye.utils.fasta_parser as fp from flye.utils.utils import which import flye.config.py_cfg as cfg from flye.six import iteritems from flye.six.moves import range POLISH_BIN = "flye-modules" logger = logging.getLogger() class PolishException(Exception): pass def check_binaries(): if not which(POLISH_BIN): raise PolishException("polishing binary was not found. " "Did you run 'make'?") try: devnull = open(os.devnull, "w") subprocess.check_call([POLISH_BIN, "polisher", "-h"], stderr=devnull) except subprocess.CalledProcessError as e: if e.returncode == -9: logger.error("Looks like the system ran out of memory") raise PolishException(str(e)) except OSError as e: raise PolishException(str(e)) def polish(contig_seqs, read_seqs, work_dir, num_iters, num_threads, error_mode, output_progress): """ High-level polisher interface """ logger_state = logger.disabled if not output_progress: logger.disabled = True subs_matrix = os.path.join(cfg.vals["pkg_root"],<|fim▁hole|> cfg.vals["err_modes"][error_mode]["hopo_matrix"]) stats_file = os.path.join(work_dir, "contigs_stats.txt") prev_assembly = contig_seqs contig_lengths = None coverage_stats = None for i in range(num_iters): logger.info("Polishing genome (%d/%d)", i + 1, num_iters) #split into 1Mb chunks to reduce RAM usage #slightly vary chunk size between iterations CHUNK_SIZE = 1000000 - (i % 2) * 100000 chunks_file = os.path.join(work_dir, "chunks_{0}.fasta".format(i + 1)) chunks = split_into_chunks(fp.read_sequence_dict(prev_assembly), CHUNK_SIZE) fp.write_fasta_dict(chunks, chunks_file) #### logger.info("Running minimap2") alignment_file = os.path.join(work_dir, "minimap_{0}.bam".format(i + 1)) make_alignment(chunks_file, read_seqs, num_threads, work_dir, error_mode, alignment_file, reference_mode=True, sam_output=True) ##### logger.info("Separating alignment into bubbles") contigs_info = get_contigs_info(chunks_file) bubbles_file = os.path.join(work_dir, "bubbles_{0}.fasta".format(i + 1)) coverage_stats, mean_aln_error = \ make_bubbles(alignment_file, contigs_info, chunks_file, error_mode, num_threads, bubbles_file) logger.info("Alignment error rate: %f", mean_aln_error) consensus_out = os.path.join(work_dir, "consensus_{0}.fasta".format(i + 1)) polished_file = os.path.join(work_dir, "polished_{0}.fasta".format(i + 1)) if os.path.getsize(bubbles_file) == 0: logger.info("No reads were aligned during polishing") if not output_progress: logger.disabled = logger_state open(stats_file, "w").write("#seq_name\tlength\tcoverage\n") open(polished_file, "w") return polished_file, stats_file ##### logger.info("Correcting bubbles") _run_polish_bin(bubbles_file, subs_matrix, hopo_matrix, consensus_out, num_threads, output_progress) polished_fasta, polished_lengths = _compose_sequence(consensus_out) merged_chunks = merge_chunks(polished_fasta) fp.write_fasta_dict(merged_chunks, polished_file) #Cleanup os.remove(chunks_file) os.remove(bubbles_file) os.remove(consensus_out) os.remove(alignment_file) contig_lengths = polished_lengths prev_assembly = polished_file #merge information from chunks contig_lengths = merge_chunks(contig_lengths, fold_function=sum) coverage_stats = merge_chunks(coverage_stats, fold_function=lambda l: sum(l) // len(l)) with open(stats_file, "w") as f: f.write("#seq_name\tlength\tcoverage\n") for ctg_id in contig_lengths: f.write("{0}\t{1}\t{2}\n".format(ctg_id, contig_lengths[ctg_id], coverage_stats[ctg_id])) if not output_progress: logger.disabled = logger_state return prev_assembly, stats_file def generate_polished_edges(edges_file, gfa_file, polished_contigs, work_dir, error_mode, num_threads): """ Generate polished graph edges sequences by extracting them from polished contigs """ logger.debug("Generating polished GFA") alignment_file = os.path.join(work_dir, "edges_aln.bam") polished_dict = fp.read_sequence_dict(polished_contigs) make_alignment(polished_contigs, [edges_file], num_threads, work_dir, error_mode, alignment_file, reference_mode=True, sam_output=True) aln_reader = SynchronizedSamReader(alignment_file, polished_dict, cfg.vals["max_read_coverage"]) aln_by_edge = defaultdict(list) #getting one best alignment for each contig while not aln_reader.is_eof(): _, ctg_aln = aln_reader.get_chunk() for aln in ctg_aln: aln_by_edge[aln.qry_id].append(aln) aln_reader.close() MIN_CONTAINMENT = 0.9 updated_seqs = 0 edges_dict = fp.read_sequence_dict(edges_file) for edge in edges_dict: if edge in aln_by_edge: main_aln = aln_by_edge[edge][0] map_start = main_aln.trg_start map_end = main_aln.trg_end for aln in aln_by_edge[edge]: if aln.trg_id == main_aln.trg_id and aln.trg_sign == main_aln.trg_sign: map_start = min(map_start, aln.trg_start) map_end = max(map_end, aln.trg_end) new_seq = polished_dict[main_aln.trg_id][map_start : map_end] if main_aln.qry_sign == "-": new_seq = fp.reverse_complement(new_seq) #print edge, main_aln.qry_len, len(new_seq), main_aln.qry_start, main_aln.qry_end if len(new_seq) / aln.qry_len > MIN_CONTAINMENT: edges_dict[edge] = new_seq updated_seqs += 1 #writes fasta file with polished egdes #edges_polished = os.path.join(work_dir, "polished_edges.fasta") #fp.write_fasta_dict(edges_dict, edges_polished) #writes gfa file with polished edges with open(os.path.join(work_dir, "polished_edges.gfa"), "w") as gfa_polished, \ open(gfa_file, "r") as gfa_in: for line in gfa_in: if line.startswith("S"): seq_id = line.split()[1] coverage_tag = line.split()[3] gfa_polished.write("S\t{0}\t{1}\t{2}\n" .format(seq_id, edges_dict[seq_id], coverage_tag)) else: gfa_polished.write(line) logger.debug("%d sequences remained unpolished", len(edges_dict) - updated_seqs) os.remove(alignment_file) def filter_by_coverage(args, stats_in, contigs_in, stats_out, contigs_out): """ Filters out contigs with low coverage """ SUBASM_MIN_COVERAGE = 1 HARD_MIN_COVERAGE = cfg.vals["hard_minimum_coverage"] RELATIVE_MIN_COVERAGE = cfg.vals["relative_minimum_coverage"] ctg_stats = {} sum_cov = 0 sum_length = 0 with open(stats_in, "r") as f: for line in f: if line.startswith("#"): continue tokens = line.split("\t") ctg_id, ctg_len, ctg_cov = tokens[0], int(tokens[1]), int(tokens[2]) ctg_stats[ctg_id] = (ctg_len, ctg_cov) sum_cov += ctg_cov * ctg_len sum_length += ctg_len mean_coverage = int(sum_cov / sum_length) coverage_threshold = None if args.read_type == "subasm": coverage_threshold = SUBASM_MIN_COVERAGE elif args.meta: coverage_threshold = HARD_MIN_COVERAGE else: coverage_threshold = int(round(mean_coverage / RELATIVE_MIN_COVERAGE)) coverage_threshold = max(HARD_MIN_COVERAGE, coverage_threshold) logger.debug("Mean contig coverage: %d, selected threshold: %d", mean_coverage, coverage_threshold) filtered_num = 0 filtered_seq = 0 good_fasta = {} for hdr, seq in fp.stream_sequence(contigs_in): if ctg_stats[hdr][1] >= coverage_threshold: good_fasta[hdr] = seq else: filtered_num += 1 filtered_seq += ctg_stats[hdr][0] logger.debug("Filtered %d contigs of total length %d", filtered_num, filtered_seq) fp.write_fasta_dict(good_fasta, contigs_out) with open(stats_out, "w") as f: f.write("#seq_name\tlength\tcoverage\n") for ctg_id in good_fasta: f.write("{0}\t{1}\t{2}\n".format(ctg_id, ctg_stats[ctg_id][0], ctg_stats[ctg_id][1])) def _run_polish_bin(bubbles_in, subs_matrix, hopo_matrix, consensus_out, num_threads, output_progress): """ Invokes polishing binary """ cmdline = [POLISH_BIN, "polisher", "--bubbles", bubbles_in, "--subs-mat", subs_matrix, "--hopo-mat", hopo_matrix, "--out", consensus_out, "--threads", str(num_threads)] if not output_progress: cmdline.append("--quiet") try: subprocess.check_call(cmdline) except subprocess.CalledProcessError as e: if e.returncode == -9: logger.error("Looks like the system ran out of memory") raise PolishException(str(e)) except OSError as e: raise PolishException(str(e)) def _compose_sequence(consensus_file): """ Concatenates bubbles consensuses into genome """ consensuses = defaultdict(list) coverage = defaultdict(list) with open(consensus_file, "r") as f: header = True for line in f: if header: tokens = line.strip().split(" ") ctg_id = tokens[0][1:] ctg_pos = int(tokens[1]) coverage[ctg_id].append(int(tokens[2])) else: consensuses[ctg_id].append((ctg_pos, line.strip())) header = not header polished_fasta = {} polished_stats = {} for ctg_id, seqs in iteritems(consensuses): sorted_seqs = [p[1] for p in sorted(seqs, key=lambda p: p[0])] concat_seq = "".join(sorted_seqs) #mean_coverage = sum(coverage[ctg_id]) / len(coverage[ctg_id]) polished_fasta[ctg_id] = concat_seq polished_stats[ctg_id] = len(concat_seq) return polished_fasta, polished_stats<|fim▁end|>
cfg.vals["err_modes"][error_mode]["subs_matrix"]) hopo_matrix = os.path.join(cfg.vals["pkg_root"],
<|file_name|>tabsExample.tsx<|end_file_name|><|fim▁begin|>/* * Copyright 2015 Palantir Technologies, Inc. All rights reserved. * Licensed under the BSD-3 License as modified (the “License”); you may obtain a copy * of the license at https://github.com/palantir/blueprint/blob/master/LICENSE * and https://github.com/palantir/blueprint/blob/master/PATENTS */ import * as React from "react"; import { Switch, Tab, TabList, TabPanel, Tabs } from "@blueprintjs/core"; import BaseExample, { handleBooleanChange } from "./common/baseExample"; export class TabsExample extends BaseExample<{ isVertical?: boolean }> { public state = { isVertical: false, }; private toggleIsVertical = handleBooleanChange((isVertical) => this.setState({ isVertical })); <|fim▁hole|> return ( <Tabs className={this.state.isVertical ? "pt-vertical" : null} key={this.state.isVertical ? "vertical" : "horizontal"} > <TabList> <Tab>React</Tab> <Tab>Angular</Tab> <Tab>Ember</Tab> <Tab isDisabled={true}>Backbone</Tab> </TabList> <TabPanel> <h3>Example panel: React</h3> <p className="pt-running-text"> Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project. </p> </TabPanel> <TabPanel> <h3>Example panel: Angular</h3> <p className="pt-running-text"> HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop. </p> </TabPanel> <TabPanel> <h3>Example panel: Ember</h3> <p className="pt-running-text"> Ember.js is an open-source JavaScript application framework, based on the model-view-controller (MVC) pattern. It allows developers to create scalable single-page web applications by incorporating common idioms and best practices into the framework. What is your favorite JS framework? </p> <input className="pt-input" type="text"/> </TabPanel> <TabPanel> <h3>Backbone</h3> </TabPanel> </Tabs> ); } protected renderOptions() { return [ [ <Switch checked={this.state.isVertical} label="Use vertical tabs" key="Vertical" onChange={this.toggleIsVertical} />, ], ]; } }<|fim▁end|>
protected renderExample() {
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from polymorphic import PolymorphicModel from django.db.models import F from django.core.urlresolvers import reverse from django.contrib.auth.models import User from celery.exceptions import SoftTimeLimitExceeded from .jenkins import get_job_status from .alert import (send_alert, AlertPlugin, AlertPluginUserData, update_alert_plugins) from .calendar import get_events from .graphite import parse_metric from .graphite import get_data from .tasks import update_service, update_instance from datetime import datetime, timedelta from django.utils import timezone import json import re import time import os import subprocess import requests from celery.utils.log import get_task_logger RAW_DATA_LIMIT = 5000 logger = get_task_logger(__name__) CHECK_TYPES = ( ('>', 'Greater than'), ('>=', 'Greater than or equal'), ('<', 'Less than'), ('<=', 'Less than or equal'), ('==', 'Equal to'), ) def serialize_recent_results(recent_results): if not recent_results: return '' def result_to_value(result): if result.succeeded: return '1' else: return '-1' vals = [result_to_value(r) for r in recent_results] vals.reverse() return ','.join(vals) def calculate_debounced_passing(recent_results, debounce=0): """ `debounce` is the number of previous failures we need (not including this) to mark a search as passing or failing Returns: True if passing given debounce factor False if failing """ if not recent_results: return True debounce_window = recent_results[:debounce + 1] for r in debounce_window: if r.succeeded: return True return False class CheckGroupMixin(models.Model): class Meta: abstract = True PASSING_STATUS = 'PASSING' WARNING_STATUS = 'WARNING' ERROR_STATUS = 'ERROR' CRITICAL_STATUS = 'CRITICAL' CALCULATED_PASSING_STATUS = 'passing' CALCULATED_INTERMITTENT_STATUS = 'intermittent' CALCULATED_FAILING_STATUS = 'failing' STATUSES = ( (CALCULATED_PASSING_STATUS, CALCULATED_PASSING_STATUS), (CALCULATED_INTERMITTENT_STATUS, CALCULATED_INTERMITTENT_STATUS), (CALCULATED_FAILING_STATUS, CALCULATED_FAILING_STATUS), ) IMPORTANCES = ( (WARNING_STATUS, 'Warning'), (ERROR_STATUS, 'Error'), (CRITICAL_STATUS, 'Critical'), ) name = models.TextField() users_to_notify = models.ManyToManyField( User, blank=True, help_text='Users who should receive alerts.', ) alerts_enabled = models.BooleanField( default=True, help_text='Alert when this service is not healthy.', ) status_checks = models.ManyToManyField( 'StatusCheck', blank=True, help_text='Checks used to calculate service status.', ) last_alert_sent = models.DateTimeField( null=True, blank=True, ) alerts = models.ManyToManyField( 'AlertPlugin', blank=True, help_text='Alerts channels through which you wish to be notified' ) email_alert = models.BooleanField(default=False) hipchat_alert = models.BooleanField(default=True) sms_alert = models.BooleanField(default=False) telephone_alert = models.BooleanField( default=False, help_text='Must be enabled, and check importance set to Critical, to receive telephone alerts.', ) overall_status = models.TextField(default=PASSING_STATUS) old_overall_status = models.TextField(default=PASSING_STATUS) hackpad_id = models.TextField( null=True, blank=True, verbose_name='Recovery instructions', help_text='Gist, Hackpad or Refheap js embed with recovery instructions e.g. https://you.hackpad.com/some_document.js' ) def __unicode__(self): return self.name def most_severe(self, check_list): failures = [c.importance for c in check_list] if self.CRITICAL_STATUS in failures: return self.CRITICAL_STATUS if self.ERROR_STATUS in failures: return self.ERROR_STATUS if self.WARNING_STATUS in failures: return self.WARNING_STATUS return self.PASSING_STATUS @property def is_critical(self): """ Break out separately because it's a bit of a pain to get wrong. """ if self.old_overall_status != self.CRITICAL_STATUS and self.overall_status == self.CRITICAL_STATUS: return True return False def alert(self): if not self.alerts_enabled: return if self.overall_status != self.PASSING_STATUS: # Don't alert every time if self.overall_status == self.WARNING_STATUS: if self.last_alert_sent and (timezone.now() - timedelta(minutes=settings.NOTIFICATION_INTERVAL)) < self.last_alert_sent: return elif self.overall_status in (self.CRITICAL_STATUS, self.ERROR_STATUS): if self.last_alert_sent and (timezone.now() - timedelta(minutes=settings.ALERT_INTERVAL)) < self.last_alert_sent: return self.last_alert_sent = timezone.now() else: # We don't count "back to normal" as an alert self.last_alert_sent = None self.save() self.snapshot.did_send_alert = True self.snapshot.save() send_alert(self, duty_officers=get_duty_officers()) @property def recent_snapshots(self): snapshots = self.snapshots.filter( time__gt=(timezone.now() - timedelta(minutes=60 * 24))) snapshots = list(snapshots.values()) for s in snapshots: s['time'] = time.mktime(s['time'].timetuple()) return snapshots def graphite_status_checks(self): return self.status_checks.filter(polymorphic_ctype__model='graphitestatuscheck') def http_status_checks(self): return self.status_checks.filter(polymorphic_ctype__model='httpstatuscheck') def jenkins_status_checks(self): return self.status_checks.filter(polymorphic_ctype__model='jenkinsstatuscheck') def active_graphite_status_checks(self): return self.graphite_status_checks().filter(active=True) def active_http_status_checks(self): return self.http_status_checks().filter(active=True) def active_jenkins_status_checks(self): return self.jenkins_status_checks().filter(active=True) def active_status_checks(self): return self.status_checks.filter(active=True) def inactive_status_checks(self): return self.status_checks.filter(active=False) def all_passing_checks(self): return self.active_status_checks().filter(calculated_status=self.CALCULATED_PASSING_STATUS) def all_failing_checks(self): return self.active_status_checks().exclude(calculated_status=self.CALCULATED_PASSING_STATUS) class Service(CheckGroupMixin): def update_status(self): self.old_overall_status = self.overall_status # Only active checks feed into our calculation status_checks_failed_count = self.all_failing_checks().count() self.overall_status = self.most_severe(self.all_failing_checks()) self.snapshot = ServiceStatusSnapshot( service=self, num_checks_active=self.active_status_checks().count(), num_checks_passing=self.active_status_checks( ).count() - status_checks_failed_count, num_checks_failing=status_checks_failed_count, overall_status=self.overall_status, time=timezone.now(), ) self.snapshot.save() self.save() if not (self.overall_status == Service.PASSING_STATUS and self.old_overall_status == Service.PASSING_STATUS): self.alert() instances = models.ManyToManyField( 'Instance', blank=True, help_text='Instances this service is running on.', ) url = models.TextField( blank=True, help_text="URL of service." ) class Meta: ordering = ['name'] class Instance(CheckGroupMixin): def duplicate(self): checks = self.status_checks.all() new_instance = self new_instance.pk = None new_instance.id = None new_instance.name = u"Copy of %s" % self.name new_instance.save() for check in checks: check.duplicate(inst_set=(new_instance,), serv_set=()) return new_instance.pk def update_status(self): self.old_overall_status = self.overall_status # Only active checks feed into our calculation status_checks_failed_count = self.all_failing_checks().count() self.overall_status = self.most_severe(self.all_failing_checks()) self.snapshot = InstanceStatusSnapshot( instance=self, num_checks_active=self.active_status_checks().count(), num_checks_passing=self.active_status_checks( ).count() - status_checks_failed_count, num_checks_failing=status_checks_failed_count, overall_status=self.overall_status, time=timezone.now(), ) self.snapshot.save() self.save() class Meta: ordering = ['name'] address = models.TextField( blank=True, help_text="Address (IP/Hostname) of service." ) def icmp_status_checks(self): return self.status_checks.filter(polymorphic_ctype__model='icmpstatuscheck') def active_icmp_status_checks(self): return self.icmp_status_checks().filter(active=True) def delete(self, *args, **kwargs): self.icmp_status_checks().delete() return super(Instance, self).delete(*args, **kwargs) class Snapshot(models.Model): class Meta: abstract = True time = models.DateTimeField(db_index=True) num_checks_active = models.IntegerField(default=0) num_checks_passing = models.IntegerField(default=0) num_checks_failing = models.IntegerField(default=0) overall_status = models.TextField(default=Service.PASSING_STATUS) did_send_alert = models.IntegerField(default=False) class ServiceStatusSnapshot(Snapshot): service = models.ForeignKey(Service, related_name='snapshots') def __unicode__(self): return u"%s: %s" % (self.service.name, self.overall_status) class InstanceStatusSnapshot(Snapshot): instance = models.ForeignKey(Instance, related_name='snapshots') def __unicode__(self): return u"%s: %s" % (self.instance.name, self.overall_status) class StatusCheck(PolymorphicModel): """ Base class for polymorphic models. We're going to use proxy models for inheriting because it makes life much simpler, but this allows us to stick different methods etc on subclasses. You can work out what (sub)class a model is an instance of by accessing `instance.polymorphic_ctype.model` We are using django-polymorphic for polymorphism """ # Common attributes to all name = models.TextField() active = models.BooleanField( default=True, help_text='If not active, check will not be used to calculate service status and will not trigger alerts.', ) importance = models.CharField( max_length=30, choices=Service.IMPORTANCES, default=Service.ERROR_STATUS, help_text='Severity level of a failure. Critical alerts are for failures you want to wake you up at 2am, Errors are things you can sleep through but need to fix in the morning, and warnings for less important things.' ) frequency = models.IntegerField( default=5, help_text='Minutes between each check.', ) debounce = models.IntegerField( default=0, null=True, help_text='Number of successive failures permitted before check will be marked as failed. Default is 0, i.e. fail on first failure.' ) created_by = models.ForeignKey(User, null=True) calculated_status = models.CharField( max_length=50, choices=Service.STATUSES, default=Service.CALCULATED_PASSING_STATUS, blank=True) last_run = models.DateTimeField(null=True) cached_health = models.TextField(editable=False, null=True) # Graphite checks metric = models.TextField( null=True, help_text='fully.qualified.name of the Graphite metric you want to watch. This can be any valid Graphite expression, including wildcards, multiple hosts, etc.', ) check_type = models.CharField( choices=CHECK_TYPES, max_length=100, null=True, ) value = models.TextField( null=True, help_text='If this expression evaluates to true, the check will fail (possibly triggering an alert).', ) expected_num_hosts = models.IntegerField( default=0, null=True, help_text='The minimum number of data series (hosts) you expect to see.', ) allowed_num_failures = models.IntegerField( default=0, null=True, help_text='The maximum number of data series (metrics) you expect to fail. For example, you might be OK with 2 out of 3 webservers having OK load (1 failing), but not 1 out of 3 (2 failing).', ) # HTTP checks endpoint = models.TextField( null=True, help_text='HTTP(S) endpoint to poll.', ) username = models.TextField( blank=True, null=True, help_text='Basic auth username.', ) password = models.TextField( blank=True, null=True, help_text='Basic auth password.', ) text_match = models.TextField( blank=True, null=True, help_text='Regex to match against source of page.', ) status_code = models.TextField( default=200, null=True, help_text='Status code expected from endpoint.' ) timeout = models.IntegerField( default=30, null=True, help_text='Time out after this many seconds.', ) verify_ssl_certificate = models.BooleanField( default=True, help_text='Set to false to allow not try to verify ssl certificates (default True)', ) # Jenkins checks max_queued_build_time = models.IntegerField( null=True, blank=True, help_text='Alert if build queued for more than this many minutes.', ) class Meta(PolymorphicModel.Meta): ordering = ['name'] def __unicode__(self): return self.name def recent_results(self): # Not great to use id but we are getting lockups, possibly because of something to do with index # on time_complete return StatusCheckResult.objects.filter(check=self).order_by('-id').defer('raw_data')[:10] def last_result(self): try: return StatusCheckResult.objects.filter(check=self).order_by('-id').defer('raw_data')[0] except: return None def run(self): start = timezone.now() try: result = self._run() except SoftTimeLimitExceeded as e: result = StatusCheckResult(check=self) result.error = u'Error in performing check: Celery soft time limit exceeded' result.succeeded = False except Exception as e: result = StatusCheckResult(check=self) logger.error(u"Error performing check: %s" % (e.message,)) result.error = u'Error in performing check: %s' % (e.message,) result.succeeded = False finish = timezone.now() result.time = start result.time_complete = finish result.save() self.last_run = finish self.save() def _run(self): """ Implement on subclasses. Should return a `CheckResult` instance. """ raise NotImplementedError('Subclasses should implement') def save(self, *args, **kwargs): if self.last_run: recent_results = list(self.recent_results()) if calculate_debounced_passing(recent_results, self.debounce): self.calculated_status = Service.CALCULATED_PASSING_STATUS else: self.calculated_status = Service.CALCULATED_FAILING_STATUS self.cached_health = serialize_recent_results(recent_results) try: updated = StatusCheck.objects.get(pk=self.pk) except StatusCheck.DoesNotExist as e: logger.error('Cannot find myself (check %s) in the database, presumably have been deleted' % self.pk) return else: self.cached_health = '' self.calculated_status = Service.CALCULATED_PASSING_STATUS ret = super(StatusCheck, self).save(*args, **kwargs) self.update_related_services() self.update_related_instances() return ret def duplicate(self, inst_set=(), serv_set=()): new_check = self new_check.pk = None new_check.id = None new_check.last_run = None new_check.save() for linked in list(inst_set) + list(serv_set): linked.status_checks.add(new_check) return new_check.pk def update_related_services(self): services = self.service_set.all() for service in services: update_service.delay(service.id) def update_related_instances(self): instances = self.instance_set.all() for instance in instances: update_instance.delay(instance.id) class ICMPStatusCheck(StatusCheck): class Meta(StatusCheck.Meta): proxy = True @property def check_category(self): return "ICMP/Ping Check" def _run(self): result = StatusCheckResult(check=self) instances = self.instance_set.all() target = self.instance_set.get().address # We need to read both STDOUT and STDERR because ping can write to both, depending on the kind of error. Thanks a lot, ping. ping_process = subprocess.Popen("ping -c 1 " + target, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) response = ping_process.wait() if response == 0: result.succeeded = True else: output = ping_process.stdout.read() result.succeeded = False result.error = output<|fim▁hole|> return result class GraphiteStatusCheck(StatusCheck): class Meta(StatusCheck.Meta): proxy = True @property def check_category(self): return "Metric check" def format_error_message(self, failure_value, actual_hosts, actual_failures): """ A summary of why the check is failing for inclusion in short alert messages Returns something like: "5.0 > 4 | 1/2 hosts" """ if isinstance(failure_value, (list, tuple)): failure_value = ', '.join([u'%0.1f' % v for v in failure_value]) else: failure_value = u'%0.1f' % failure_value hosts_string = u'' failures_string = u'' if self.expected_num_hosts > 0: hosts_string = u' | %s/%s hosts' % (actual_hosts, self.expected_num_hosts) if self.expected_num_hosts > actual_hosts: return u'Hosts missing%s' % hosts_string if self.allowed_num_failures and actual_failures: failures_string = u' | %s/%s series failing (%s allowed)' % ( actual_failures, actual_hosts, self.allowed_num_failures, ) if failure_value is None: return "Failed to get metric from Graphite" return u"%s %s %0.1f%s%s" % ( failure_value, self.check_type, float(self.value), hosts_string, failures_string, ) def _run(self): result = StatusCheckResult(check=self) failures = [] graphite_output = parse_metric(self.metric, mins_to_check=self.frequency) if graphite_output['num_series_with_data'] > 0: result.average_value = graphite_output['average_value'] failed = False for s in graphite_output['series']: failure_value = None if self.check_type == '<': failed = float(s['min']) < float(self.value) if failed: failure_value = s['min'] elif self.check_type == '<=': failed = float(s['min']) <= float(self.value) if failed: failure_value = s['min'] elif self.check_type == '>': failed = float(s['max']) > float(self.value) if failed: failure_value = s['max'] elif self.check_type == '>=': failed = float(s['max']) >= float(self.value) if failed: failure_value = s['max'] elif self.check_type == '==': failed = float(self.value) in s['values'] if failed: failure_value = float(self.value) else: raise Exception(u'Check type %s not supported' % self.check_type) if not failure_value is None: failures.append(failure_value) allowed_num_failures = self.allowed_num_failures or 0 # If there are more than expected failures if len(failures) - self.allowed_num_failures > 0: result.succeeded = False else: if graphite_output['error']: result.succeeded = False if graphite_output['num_series_with_data'] < self.expected_num_hosts: result.succeeded = False else: result.succeeded = True try: result.raw_data = json.dumps(graphite_output['raw']) except: result.raw_data = graphite_output['raw'] if not result.succeeded: result.error = self.format_error_message( failures, graphite_output['num_series_with_data'], len(failures), ) return result class HttpStatusCheck(StatusCheck): class Meta(StatusCheck.Meta): proxy = True @property def check_category(self): return "HTTP check" def _run(self): result = StatusCheckResult(check=self) auth = None if self.username or self.password: auth = (self.username, self.password) try: resp = requests.get( self.endpoint, timeout=self.timeout, verify=self.verify_ssl_certificate, auth=auth, headers={ "User-Agent": settings.HTTP_USER_AGENT, }, ) except requests.RequestException as e: result.error = u'Request error occurred: %s' % (e.message,) result.succeeded = False else: if self.status_code and resp.status_code != int(self.status_code): result.error = u'Wrong code: got %s (expected %s)' % ( resp.status_code, int(self.status_code)) result.succeeded = False result.raw_data = resp.content elif self.text_match: if not re.search(self.text_match, resp.content): result.error = u'Failed to find match regex /%s/ in response body' % self.text_match result.raw_data = resp.content result.succeeded = False else: result.succeeded = True else: result.succeeded = True return result class JenkinsStatusCheck(StatusCheck): class Meta(StatusCheck.Meta): proxy = True @property def check_category(self): return "Jenkins check" @property def failing_short_status(self): return 'Job failing on Jenkins' def _run(self): result = StatusCheckResult(check=self) try: status = get_job_status(self.name) active = status['active'] result.job_number = status['job_number'] if status['status_code'] == 404: result.error = u'Job %s not found on Jenkins' % self.name result.succeeded = False return result elif status['status_code'] > 400: # Will fall through to next block raise Exception(u'returned %s' % status['status_code']) except Exception as e: # If something else goes wrong, we will *not* fail - otherwise # a lot of services seem to fail all at once. # Ugly to do it here but... result.error = u'Error fetching from Jenkins - %s' % e.message result.succeeded = True return result if not active: # We will fail if the job has been disabled result.error = u'Job "%s" disabled on Jenkins' % self.name result.succeeded = False else: if self.max_queued_build_time and status['blocked_build_time']: if status['blocked_build_time'] > self.max_queued_build_time * 60: result.succeeded = False result.error = u'Job "%s" has blocked build waiting for %ss (> %sm)' % ( self.name, int(status['blocked_build_time']), self.max_queued_build_time, ) else: result.succeeded = status['succeeded'] else: result.succeeded = status['succeeded'] if not status['succeeded']: if result.error: result.error += u'; Job "%s" failing on Jenkins' % self.name else: result.error = u'Job "%s" failing on Jenkins' % self.name result.raw_data = status return result class StatusCheckResult(models.Model): """ We use the same StatusCheckResult model for all check types, because really they are not so very different. Checks don't have to use all the fields, so most should be nullable """ check = models.ForeignKey(StatusCheck) time = models.DateTimeField(null=False, db_index=True) time_complete = models.DateTimeField(null=True, db_index=True) raw_data = models.TextField(null=True) succeeded = models.BooleanField(default=False) error = models.TextField(null=True) # Jenkins specific job_number = models.PositiveIntegerField(null=True) class Meta: ordering = ['-time_complete'] def __unicode__(self): return '%s: %s @%s' % (self.status, self.check.name, self.time) @property def status(self): if self.succeeded: return 'succeeded' else: return 'failed' @property def took(self): """ Time taken by check in ms """ try: diff = self.time_complete - self.time return (diff.microseconds + (diff.seconds + diff.days * 24 * 3600) * 10**6) / 1000 except: return None @property def short_error(self): snippet_len = 30 if len(self.error) > snippet_len: return u"%s..." % self.error[:snippet_len - 3] else: return self.error def save(self, *args, **kwargs): if isinstance(self.raw_data, basestring): self.raw_data = self.raw_data[:RAW_DATA_LIMIT] return super(StatusCheckResult, self).save(*args, **kwargs) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') def user_data(self): for user_data_subclass in AlertPluginUserData.__subclasses__(): user_data = user_data_subclass.objects.get_or_create(user=self, title=user_data_subclass.name) return AlertPluginUserData.objects.filter(user=self) def __unicode__(self): return 'User profile: %s' % self.user.username def save(self, *args, **kwargs): # Enforce uniqueness if self.fallback_alert_user: profiles = UserProfile.objects.exclude(id=self.id) profiles.update(fallback_alert_user=False) return super(UserProfile, self).save(*args, **kwargs) @property def prefixed_mobile_number(self): return '+%s' % self.mobile_number mobile_number = models.CharField(max_length=20, blank=True, default='') hipchat_alias = models.CharField(max_length=50, blank=True, default='') fallback_alert_user = models.BooleanField(default=False) class Shift(models.Model): start = models.DateTimeField() end = models.DateTimeField() user = models.ForeignKey(User) uid = models.TextField() deleted = models.BooleanField(default=False) def __unicode__(self): deleted = '' if self.deleted: deleted = ' (deleted)' return "%s: %s to %s%s" % (self.user.username, self.start, self.end, deleted) def get_duty_officers(at_time=None): """Returns a list of duty officers for a given time or now if none given""" duty_officers = [] if not at_time: at_time = timezone.now() current_shifts = Shift.objects.filter( deleted=False, start__lt=at_time, end__gt=at_time, ) if current_shifts: duty_officers = [shift.user for shift in current_shifts] return duty_officers else: try: u = UserProfile.objects.get(fallback_alert_user=True) return [u.user] except UserProfile.DoesNotExist: return [] def update_shifts(): events = get_events() users = User.objects.filter(is_active=True) user_lookup = {} for u in users: user_lookup[u.username.lower()] = u future_shifts = Shift.objects.filter(start__gt=timezone.now()) future_shifts.update(deleted=True) for event in events: e = event['summary'].lower().strip() if e in user_lookup: user = user_lookup[e] try: s = Shift.objects.get(uid=event['uid']) except Shift.DoesNotExist: s = Shift(uid=event['uid']) s.start = event['start'] s.end = event['end'] s.user = user s.deleted = False s.save()<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .config import Config, HentaiHavenConfig, HAnimeConfig, Section<|fim▁hole|><|fim▁end|>
from .last_entry import LastEntry
<|file_name|>module-6-comp.component.spec.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license<|fim▁hole|>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Module6CompComponent } from './module-6-comp.component'; describe('Module6CompComponent', () => { let component: Module6CompComponent; let fixture: ComponentFixture<Module6CompComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Module6CompComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Module6CompComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });<|fim▁end|>
*/
<|file_name|>app.routing.ts<|end_file_name|><|fim▁begin|>import { PageComponent } from './pages/page.component'; import { ModuleWithProviders, NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; export const appRoutes: Routes = [ { path: '', redirectTo: 'page', pathMatch: 'full' }, { path: 'page', //loadChildren: './pages/page.module#PageModule', loadChildren: () => new Promise(function (resolve) { (require as any).ensure([], function (require: any) { resolve(require('./pages/page.module').default); }); }) }, ]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes) ],<|fim▁hole|> export class routing { }<|fim▁end|>
exports: [ RouterModule ] })
<|file_name|>Problem_4.java<|end_file_name|><|fim▁begin|>package codejam2016_1st; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Comparator; import java.util.Scanner; import java.util.Stack; class Pair { int _node; int _dist; Pair(int node, int dist) { _node = node; _dist = dist; } public int getDist() { return _dist; } public int getNode() { return _node; } public void setDist(int dist) { _dist = dist; } } class Comp implements Comparator<Pair>{ @Override public int compare(Pair o1, Pair o2) { if(o1.getNode() < o2.getNode()) { return -1; } else if(o1.getNode() > o2.getNode()) { return 1; } else if(o1.getDist() < o2.getDist()) { return -1; } return 1; } } public class Problem_4 { public static void main(String[] args) { try { //start(args[0]); start("problem_4_Set1.in"); } catch (FileNotFoundException e) { e.printStackTrace(); } } static ArrayList<Pair> pairList[]; static ArrayList<Integer> addedCity; static int addedDist[]; static int N; static int Q, M, sum1, sum2; static int dist[]; static void start(String filename) throws FileNotFoundException { Scanner sc = new Scanner(new BufferedInputStream(new FileInputStream(filename))); int tc = sc.nextInt(); while(tc-- > 0) { addedCity = new ArrayList<Integer>(); pairList = new ArrayList[1000000]; addedDist = new int[1000000]; sum1 = 0; sum2 = 0; N = sc.nextInt(); for(int i=0;i<N;i++) { pairList[i] = new ArrayList<Pair>(); } Q = sc.nextInt(); for(int i=0; i<N-1; i++) { int t = sc.nextInt(); int d = sc.nextInt(); pairList[i+1].add(new Pair(t-1, d)); pairList[t-1].add(new Pair(i+1, d)); } // get M for(int i=1;i<N; i++) { if(pairList[i].size() == 1) { addedCity.add(i); } } M = addedCity.size(); for(int i=0; i<M; i++) { int m = sc.nextInt(); addedDist[addedCity.get(i)] = m; } ArrayList<Integer> from = new ArrayList<Integer>(); ArrayList<Integer> to = new ArrayList<Integer>(); for(int i=0; i<Q; i++) { from.add(sc.nextInt()-1); to.add(sc.nextInt()-1); } for(int i=0; i<Q; i++) { // need to ordering if(from.get(i) != to.get(i)) { getShortestDist(from.get(i), to.get(i)); } } // update new road for(int i=0; i<M; i++) { boolean found = false; int m = addedCity.get(i); for(int j=0; j<pairList[0].size(); j++) { if(pairList[0].get(j).getNode() == m) { found = true; pairList[0].get(j).setDist(addedDist[addedCity.get(i)]); } } if(found == false) pairList[0].add(new Pair(m, addedDist[addedCity.get(i)])); found = false; for(int j=0; j<pairList[m].size(); j++) { if(pairList[m].get(j).getNode() == m) { found = true; pairList[m].get(j).setDist(addedDist[addedCity.get(i)]); <|fim▁hole|> } if(found == false) pairList[m].add(new Pair(0, addedDist[addedCity.get(i)])); } for(int i=0; i<Q; i++) { // need to ordering if(from.get(i) != to.get(i)) { getShortestDistAdded(from.get(i), to.get(i)); } } System.out.println(sum1 + " " + sum2); } } static void getShortestDist(int from, int to) { int visited[] = new int[1000000]; dist = new int[1000000]; int n = 0, d; Stack<Integer> path = new Stack<Integer>(); int currentIndex = 0; path.push(from); visited[from] = 1; while(!path.isEmpty()) { // 1. add next ordering by dist currentIndex = path.pop(); ArrayList<Pair> current = pairList[currentIndex]; for(int j=0; j<current.size(); j++) { n = current.get(j).getNode(); d = current.get(j).getDist(); if (visited[n] == 0 || (dist[n] == 0 || dist[currentIndex] + d < dist[n])) { dist[n] = dist[currentIndex] + d; path.push(n); visited[n] = 1; //System.out.println("from:" + currentIndex + " to:" + n); } } } //System.out.println("sum1:" + dist[to]); sum1 += dist[to]; } static void getShortestDistAdded(int from, int to) { int visited[] = new int[1000000]; dist = new int[1000000]; int n = 0, d; Stack<Integer> path = new Stack<Integer>(); int currentIndex = 0; path.push(from); visited[from] = 1; while(!path.isEmpty()) { // 1. add next ordering by dist currentIndex = path.pop(); ArrayList<Pair> current = pairList[currentIndex]; for(int j=0; j<current.size(); j++) { n = current.get(j).getNode(); d = current.get(j).getDist(); if (visited[n] == 0 || (dist[n] == 0 || dist[currentIndex] + d < dist[n])) { dist[n] = dist[currentIndex] + d; path.push(n); visited[n] = 1; //System.out.println("visit2:" + n); } } } //System.out.println("sum2:" + dist[to]); sum2 += dist[to]; } }<|fim▁end|>
}
<|file_name|>lc0124_binary_tree_maximum_path_sum.py<|end_file_name|><|fim▁begin|>"""Leetcode 124. Binary Tree Maximum Path Sum Hard URL: https://leetcode.com/problems/binary-tree-maximum-path-sum/ Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] 1 / \ 2 3 Output: 6 Example 2: Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42 """ # Definition for a binary tree node. class TreeNode(object):<|fim▁hole|> self.val = val self.left = None self.right = None class SolutionLeftRightMaxPathDownSumRecur(object): def _maxPathDownSum(self, root): # Edge case. if not root: return 0 # Collect max path sum from root value, down paths from left/right nodes. # If one branch sum is less than 0, do not connect that branch by max(0, .). left_max_down_sum = max(0, self._maxPathDownSum(root.left)) right_max_down_sum = max(0, self._maxPathDownSum(root.right)) self.max_path_sum = max( left_max_down_sum + root.val + right_max_down_sum, self.max_path_sum) # Return max path down sum from left or right, including root values. return root.val + max(left_max_down_sum, right_max_down_sum) def maxPathSum(self, root): """ :type root: TreeNode :rtype: int Time complexity: O(n). Space complexity: O(logn) for balanced tree, O(n) for singly linked list. """ # Use global max path sum for memorization. self.max_path_sum = -float('inf') # Collect max path down sum from left or right and update global max sum. self._maxPathDownSum(root) return self.max_path_sum def main(): # Output: 6 # 1 # / \ # 2 3 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) print SolutionLeftRightMaxPathDownSumRecur().maxPathSum(root) # Output: 42 # -10 # / \ # 9 20 # / \ # 15 7 root = TreeNode(-10) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print SolutionLeftRightMaxPathDownSumRecur().maxPathSum(root) if __name__ == '__main__': main()<|fim▁end|>
def __init__(self, val):
<|file_name|>hijack.go<|end_file_name|><|fim▁begin|>package client import ( "bufio" "crypto/tls" "fmt" "net" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/tlsconfig" "github.com/docker/go-connections/sockets" "github.com/pkg/errors" "golang.org/x/net/context" ) // tlsClientCon holds tls information and a dialed connection. type tlsClientCon struct { *tls.Conn rawConn net.Conn } func (c *tlsClientCon) CloseWrite() error { // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it<|fim▁hole|> return conn.CloseWrite() } return nil } // postHijacked sends a POST request and hijacks the connection. func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { bodyEncoded, err := encodeData(body) if err != nil { return types.HijackedResponse{}, err } apiPath := cli.getAPIPath(path, query) req, err := http.NewRequest("POST", apiPath, bodyEncoded) if err != nil { return types.HijackedResponse{}, err } req = cli.addHeaders(req, headers) conn, err := cli.setupHijackConn(req, "tcp") if err != nil { return types.HijackedResponse{}, err } return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err } func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { return tlsDialWithDialer(new(net.Dialer), network, addr, config) } // We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in // order to return our custom tlsClientCon struct which holds both the tls.Conn // object _and_ its underlying raw connection. The rationale for this is that // we need to be able to close the write end of the connection when attaching, // which tls.Conn does not provide. func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { // We want the Timeout and Deadline values from dialer to cover the // whole process: TCP connection and TLS handshake. This means that we // also need to start our own timers now. timeout := dialer.Timeout if !dialer.Deadline.IsZero() { deadlineTimeout := dialer.Deadline.Sub(time.Now()) if timeout == 0 || deadlineTimeout < timeout { timeout = deadlineTimeout } } var errChannel chan error if timeout != 0 { errChannel = make(chan error, 2) time.AfterFunc(timeout, func() { errChannel <- errors.New("") }) } proxyDialer, err := sockets.DialerFromEnvironment(dialer) if err != nil { return nil, err } rawConn, err := proxyDialer.Dial(network, addr) if err != nil { return nil, err } // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain // network setups may cause ECONNTIMEOUT, leaving the client in an unknown // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := rawConn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(30 * time.Second) } colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } hostname := addr[:colonPos] // If no ServerName is set, infer the ServerName // from the hostname we're connecting to. if config.ServerName == "" { // Make a copy to avoid polluting argument or default. config = tlsconfig.Clone(config) config.ServerName = hostname } conn := tls.Client(rawConn, config) if timeout == 0 { err = conn.Handshake() } else { go func() { errChannel <- conn.Handshake() }() err = <-errChannel } if err != nil { rawConn.Close() return nil, err } // This is Docker difference with standard's crypto/tls package: returned a // wrapper which holds both the TLS and raw connections. return &tlsClientCon{conn, rawConn}, nil } func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { if tlsConfig != nil && proto != "unix" && proto != "npipe" { // Notice this isn't Go standard's tls.Dial function return tlsDial(proto, addr, tlsConfig) } if proto == "npipe" { return sockets.DialPipe(addr, 32*time.Second) } return net.Dial(proto, addr) } func (cli *Client) setupHijackConn(req *http.Request, proto string) (net.Conn, error) { req.Host = cli.addr req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", proto) conn, err := dial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport)) if err != nil { return nil, errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") } // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain // network setups may cause ECONNTIMEOUT, leaving the client in an unknown // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := conn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(30 * time.Second) } clientconn := httputil.NewClientConn(conn, nil) defer clientconn.Close() // Server hijacks the connection, error 'connection closed' expected resp, err := clientconn.Do(req) if err != httputil.ErrPersistEOF { if err != nil { return nil, err } if resp.StatusCode != http.StatusSwitchingProtocols { resp.Body.Close() return nil, fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) } } c, br := clientconn.Hijack() if br.Buffered() > 0 { // If there is buffered content, wrap the connection c = &hijackedConn{c, br} } else { br.Reset(nil) } return c, nil } type hijackedConn struct { net.Conn r *bufio.Reader } func (c *hijackedConn) Read(b []byte) (int, error) { return c.r.Read(b) }<|fim▁end|>
// on its underlying connection. if conn, ok := c.rawConn.(types.CloseWriter); ok {
<|file_name|>index.js<|end_file_name|><|fim▁begin|>module.exports = { "methods": { "wiki": function(msg, sender, api) { var query = msg.match(/\".+\"/)[0]; query = query.substring(1, query.length-1); var base = "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&rawcontinue&redirects&titles="+encodeURIComponent(query); api.request(base, function(err, res, body) { var info = JSON.parse(body); var page; for (f in info.query.pages) { page = info.query.pages[f]; } if (page.missing === undefined) { var text; var testpos = 0; while (true) { var pos = page.extract.indexOf(".", testpos); if (pos === -1) { api.randomMessage("oddresult", {"query": query}); return;<|fim▁hole|> text = page.extract.substr(0, pos+1); var bstart = text.lastIndexOf("<b>"); var bend = text.lastIndexOf("</b>"); if (bstart < bend || (bstart === -1 && bend === -1)) break; testpos = pos + 1; } text = text.replace(/<\/?[^>]+(>|$)/g, ""); if (text.indexOf("\n") > 0) text = text.substr(0, text.indexOf("\n")); else if (text.indexOf("\n") === 0) text = text.substr(1); if (text.length === text.lastIndexOf("may refer to:") + 13) { api.randomMessage("oddresult", {"query": query}); return; } api.say(text); } else { api.randomMessage("nodefs", {"query": query}); } }); } } }<|fim▁end|>
}
<|file_name|>FormInputs.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { FormGroup, ControlLabel, FormControl, Row } from 'react-bootstrap'; function FieldGroup({ label, ...props }: any) { return ( <FormGroup> <ControlLabel>{label}</ControlLabel> <FormControl {...props} /> </FormGroup> ); } export class FormInputs extends React.Component<any, any> { render() {<|fim▁hole|> <FieldGroup {...this.props.proprieties[i]} /> </div> ); } return <Row>{row}</Row>; } } export default FormInputs;<|fim▁end|>
var row = []; for (var i = 0; i < this.props.ncols.length; i++) { row.push( <div key={i} className={this.props.ncols[i]}>
<|file_name|>core_config.py<|end_file_name|><|fim▁begin|>from __future__ import print_function, unicode_literals core_store_students_programs = False core_store_students_programs_path = 'files_stored' core_experiment_poll_time = 350 # seconds # Ports core_facade_port = 28345 core_facade_server_route = 'provider1-route' # Will only work in JSON in this config file :-( core_server_url = 'http://127.0.0.1:%s/weblab/' % core_facade_port # Scheduling<|fim▁hole|>core_coordinator_db_password = 'weblab' core_coordinator_laboratory_servers = { "laboratory:main_instance@provider1_machine" : { "exp1|dummy1|Dummy experiments" : "dummy1@dummy1_local", "exp1|dummy3_with_other_name|Dummy experiments" : "dummy3_with_other_name@dummy3_with_other_name", } } core_coordinator_external_servers = { 'dummy1@Dummy experiments' : [ 'dummy1_external' ], 'dummy4@Dummy experiments' : [ 'dummy4' ], } _provider2_scheduling_config = ("EXTERNAL_WEBLAB_DEUSTO", { 'baseurl' : 'http://127.0.0.1:38345/weblab/', 'username' : 'provider1', 'password' : 'password', }) core_scheduling_systems = { "dummy1_local" : ("PRIORITY_QUEUE", {}), "dummy3_with_other_name" : ("PRIORITY_QUEUE", {}), "dummy4" : _provider2_scheduling_config, "dummy1_external" : _provider2_scheduling_config, } core_weblabdeusto_federation_retrieval_period = 0.1<|fim▁end|>
core_coordinator_db_name = 'WebLabCoordination2' core_coordinator_db_username = 'weblab'
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" The most important object in the Gratipay object model is Participant, and the second most important one is Ccommunity. There are a few others, but those are the most important two. Participant, in particular, is at the center of everything on Gratipay. """ from contextlib import contextmanager from postgres import Postgres import psycopg2.extras @contextmanager def just_yield(obj): yield obj class GratipayDB(Postgres): def get_cursor(self, cursor=None, **kw): if cursor: if kw: raise ValueError('cannot change options when reusing a cursor') return just_yield(cursor) return super(GratipayDB, self).get_cursor(**kw) def self_check(self): with self.get_cursor() as cursor: check_db(cursor) def check_db(cursor): """Runs all available self checks on the given cursor. """ _check_balances(cursor) _check_no_team_balances(cursor) _check_tips(cursor) _check_orphans(cursor) _check_orphans_no_tips(cursor) _check_paydays_volumes(cursor) def _check_tips(cursor): """ Checks that there are no rows in tips with duplicate (tipper, tippee, mtime). https://github.com/gratipay/gratipay.com/issues/1704 """ conflicting_tips = cursor.one(""" SELECT count(*) FROM ( SELECT * FROM tips EXCEPT SELECT DISTINCT ON(tipper, tippee, mtime) * FROM tips ORDER BY tipper, tippee, mtime ) AS foo """) assert conflicting_tips == 0 def _check_balances(cursor): """ Recalculates balances for all participants from transfers and exchanges. https://github.com/gratipay/gratipay.com/issues/1118 """ b = cursor.all(""" select p.username, expected, balance as actual from ( select username, sum(a) as expected from ( select participant as username, sum(amount) as a from exchanges where amount > 0 and (status is null or status = 'succeeded') group by participant union all select participant as username, sum(amount-fee) as a from exchanges where amount < 0 and (status is null or status <> 'failed') group by participant union all select tipper as username, sum(-amount) as a from transfers group by tipper union all select participant as username, sum(amount) as a from payments where direction='to-participant' group by participant union all select participant as username, sum(-amount) as a from payments where direction='to-team' group by participant union all select tippee as username, sum(amount) as a from transfers group by tippee ) as foo group by username ) as foo2 join participants p on p.username = foo2.username where expected <> p.balance """) assert len(b) == 0, "conflicting balances: {}".format(b) def _check_no_team_balances(cursor): if cursor.one("select exists (select * from paydays where ts_end < ts_start) as running"): # payday is running return teams = cursor.all(""" SELECT t.slug, balance FROM ( SELECT team, sum(delta) as balance FROM ( SELECT team, sum(-amount) AS delta FROM payments WHERE direction='to-participant' GROUP BY team UNION ALL SELECT team, sum(amount) AS delta FROM payments WHERE direction='to-team' GROUP BY team ) AS foo GROUP BY team ) AS foo2 JOIN teams t ON t.slug = foo2.team WHERE balance <> 0 """) assert len(teams) == 0, "teams with non-zero balance: {}".format(teams) def _check_orphans(cursor): """ Finds participants that * does not have corresponding elsewhere account * have not been absorbed by other participant These are broken because new participants arise from elsewhere and elsewhere is detached only by take over which makes a note in absorptions if it removes the last elsewhere account. Especially bad case is when also claimed_time is set because there must have been elsewhere account attached and used to sign in. https://github.com/gratipay/gratipay.com/issues/617 """ orphans = cursor.all(""" select username from participants where not exists (select * from elsewhere where elsewhere.participant=username) and not exists (select * from absorptions where archived_as=username) """) assert len(orphans) == 0, "missing elsewheres: {}".format(list(orphans)) def _check_orphans_no_tips(cursor): """ Finds participants * without elsewhere account attached * having non zero outstanding tip This should not happen because when we remove the last elsewhere account in take_over we also zero out all tips. """ orphans_with_tips = cursor.all(""" WITH valid_tips AS (SELECT * FROM current_tips WHERE amount > 0) SELECT username FROM (SELECT tipper AS username FROM valid_tips UNION SELECT tippee AS username FROM valid_tips) foo WHERE NOT EXISTS (SELECT 1 FROM elsewhere WHERE participant=username) """) assert len(orphans_with_tips) == 0, orphans_with_tips def _check_paydays_volumes(cursor): """<|fim▁hole|> if cursor.one("select exists (select * from paydays where ts_end < ts_start) as running"): # payday is running return charge_volume = cursor.all(""" select * from ( select id, ts_start, charge_volume, ( select coalesce(sum(amount+fee), 0) from exchanges where timestamp > ts_start and timestamp < ts_end and amount > 0 and recorder is null and (status is null or status <> 'failed') ) as ref from paydays order by id ) as foo where charge_volume != ref """) assert len(charge_volume) == 0 charge_fees_volume = cursor.all(""" select * from ( select id, ts_start, charge_fees_volume, ( select coalesce(sum(fee), 0) from exchanges where timestamp > ts_start and timestamp < ts_end and amount > 0 and recorder is null and (status is null or status <> 'failed') ) as ref from paydays order by id ) as foo where charge_fees_volume != ref """) assert len(charge_fees_volume) == 0 ach_volume = cursor.all(""" select * from ( select id, ts_start, ach_volume, ( select coalesce(sum(amount), 0) from exchanges where timestamp > ts_start and timestamp < ts_end and amount < 0 and recorder is null ) as ref from paydays order by id ) as foo where ach_volume != ref """) assert len(ach_volume) == 0 ach_fees_volume = cursor.all(""" select * from ( select id, ts_start, ach_fees_volume, ( select coalesce(sum(fee), 0) from exchanges where timestamp > ts_start and timestamp < ts_end and amount < 0 and recorder is null ) as ref from paydays order by id ) as foo where ach_fees_volume != ref """) assert len(ach_fees_volume) == 0 def add_event(c, type, payload): SQL = """ INSERT INTO events (type, payload) VALUES (%s, %s) """ c.run(SQL, (type, psycopg2.extras.Json(payload)))<|fim▁end|>
Recalculate *_volume fields in paydays table using exchanges table. """
<|file_name|>capitalize.pipe.ts<|end_file_name|><|fim▁begin|>import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'capitalize' }) export class CapitalizePipe implements PipeTransform { public transform(data: any) { if (data === null || data === undefined || data === '') return ''; if (typeof data !== 'string') throw new Error('Need a string, got ' + data);<|fim▁hole|> } }<|fim▁end|>
if (data.length === 1) return data.charAt(0).toUpperCase(); return data.charAt(0).toUpperCase() + data.slice(1);
<|file_name|>construct.rs<|end_file_name|><|fim▁begin|>/* 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/. */ //! Creates flows and fragments from a DOM tree via a bottom-up, incremental traversal of the DOM. //! //! Each step of the traversal considers the node and existing flow, if there is one. If a node is //! not dirty and an existing flow exists, then the traversal reuses that flow. Otherwise, it //! proceeds to construct either a flow or a `ConstructionItem`. A construction item is a piece of //! intermediate data that goes with a DOM node and hasn't found its "home" yet-maybe it's a box, //! maybe it's an absolute or fixed position thing that hasn't found its containing block yet. //! Construction items bubble up the tree from children to parents until they find their homes. #![deny(unsafe_code)] use ServoArc; use block::BlockFlow; use context::{LayoutContext, with_thread_local_font_context}; use data::{LayoutDataFlags, LayoutData}; use display_list::items::OpaqueNode; use flex::FlexFlow; use floats::FloatKind; use flow::{AbsoluteDescendants, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils}; use flow::{FlowFlags, MutableFlowUtils, MutableOwnedFlowUtils}; use flow_ref::FlowRef; use fragment::{CanvasFragmentInfo, ImageFragmentInfo, InlineAbsoluteFragmentInfo, SvgFragmentInfo}; use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo, FragmentFlags}; use fragment::{InlineAbsoluteHypotheticalFragmentInfo, TableColumnFragmentInfo}; use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; use fragment::WhitespaceStrippingResult; use inline::{InlineFlow, InlineFragmentNodeInfo, InlineFragmentNodeFlags}; use linked_list::prepend_from; use list_item::{ListItemFlow, ListStyleTypeContent}; use multicol::{MulticolColumnFlow, MulticolFlow}; use parallel; use script_layout_interface::{LayoutElementType, LayoutNodeType, is_image_data}; use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use servo_config::opts; use servo_url::ServoUrl; use std::collections::LinkedList; use std::marker::PhantomData; use std::mem; use std::sync::Arc; use std::sync::atomic::Ordering; use style::computed_values::caption_side::T as CaptionSide; use style::computed_values::display::T as Display; use style::computed_values::empty_cells::T as EmptyCells; use style::computed_values::float::T as Float; use style::computed_values::list_style_position::T as ListStylePosition; use style::computed_values::position::T as Position; use style::context::SharedStyleContext; use style::dom::TElement; use style::logical_geometry::Direction; use style::properties::ComputedValues; use style::selector_parser::{PseudoElement, RestyleDamage}; use style::servo::restyle_damage::ServoRestyleDamage; use style::values::computed::counters::ContentItem; use style::values::generics::url::UrlOrNone as ImageUrlOrNone; use table::TableFlow; use table_caption::TableCaptionFlow; use table_cell::TableCellFlow; use table_colgroup::TableColGroupFlow; use table_row::TableRowFlow; use table_rowgroup::TableRowGroupFlow; use table_wrapper::TableWrapperFlow; use text::TextRunScanner; use traversal::PostorderNodeMutTraversal; use wrapper::{LayoutNodeLayoutData, TextContent, ThreadSafeLayoutNodeHelpers}; /// The results of flow construction for a DOM node. #[derive(Clone)] pub enum ConstructionResult { /// This node contributes nothing at all (`display: none`). Alternately, this is what newly /// created nodes have their `ConstructionResult` set to. None, /// This node contributed a flow at the proper position in the tree. /// Nothing more needs to be done for this node. It has bubbled up fixed /// and absolute descendant flows that have a containing block above it. Flow(FlowRef, AbsoluteDescendants), /// This node contributed some object or objects that will be needed to construct a proper flow /// later up the tree, but these objects have not yet found their home. ConstructionItem(ConstructionItem), } impl ConstructionResult { pub fn get(&mut self) -> ConstructionResult { // FIXME(pcwalton): Stop doing this with inline fragments. Cloning fragments is very // inefficient! (*self).clone() } pub fn debug_id(&self) -> usize { match *self { ConstructionResult::None => 0, ConstructionResult::ConstructionItem(_) => 0, ConstructionResult::Flow(ref flow_ref, _) => flow_ref.base().debug_id(), } } } /// Represents the output of flow construction for a DOM node that has not yet resulted in a /// complete flow. Construction items bubble up the tree until they find a `Flow` to be attached /// to. #[derive(Clone)] pub enum ConstructionItem { /// Inline fragments and associated {ib} splits that have not yet found flows. InlineFragments(InlineFragmentsConstructionResult), /// Potentially ignorable whitespace. /// /// FIXME(emilio): How could whitespace have any PseudoElementType other /// than Normal? Whitespace(OpaqueNode, PseudoElementType, ServoArc<ComputedValues>, RestyleDamage), /// TableColumn Fragment TableColumnFragment(Fragment), } /// Represents inline fragments and {ib} splits that are bubbling up from an inline. #[derive(Clone)] pub struct InlineFragmentsConstructionResult { /// Any {ib} splits that we're bubbling up. pub splits: LinkedList<InlineBlockSplit>, /// Any fragments that succeed the {ib} splits. pub fragments: IntermediateInlineFragments, } /// Represents an {ib} split that has not yet found the containing block that it belongs to. This /// is somewhat tricky. An example may be helpful. For this DOM fragment: /// /// ```html /// <span> /// A /// <div>B</div> /// C /// </span> /// ``` /// /// The resulting `ConstructionItem` for the outer `span` will be: /// /// ```rust,ignore /// ConstructionItem::InlineFragments( /// InlineFragmentsConstructionResult { /// splits: linked_list![ /// InlineBlockSplit { /// predecessors: IntermediateInlineFragments { /// fragments: linked_list![A], /// absolute_descendents: AbsoluteDescendents { /// descendant_links: vec![] /// }, /// }, /// flow: B, /// } /// ], /// fragments: linked_list![C], /// }, /// ) /// ``` #[derive(Clone)] pub struct InlineBlockSplit { /// The inline fragments that precede the flow. pub predecessors: IntermediateInlineFragments, /// The flow that caused this {ib} split. pub flow: FlowRef, } impl InlineBlockSplit { /// Flushes the given accumulator to the new split and makes a new accumulator to hold any /// subsequent fragments. fn new<ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode>( fragment_accumulator: &mut InlineFragmentsAccumulator, node: &ConcreteThreadSafeLayoutNode, style_context: &SharedStyleContext, flow: FlowRef, ) -> InlineBlockSplit { fragment_accumulator.enclosing_node.as_mut().expect( "enclosing_node is None; Are {ib} splits being generated outside of an inline node?" ).flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT); let split = InlineBlockSplit { predecessors: mem::replace( fragment_accumulator, InlineFragmentsAccumulator::from_inline_node( node, style_context, )).to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>(style_context), flow: flow, }; fragment_accumulator.enclosing_node.as_mut().unwrap().flags.remove( InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT); split } } /// Holds inline fragments and absolute descendants. #[derive(Clone)] pub struct IntermediateInlineFragments { /// The list of fragments. pub fragments: LinkedList<Fragment>, /// The list of absolute descendants of those inline fragments. pub absolute_descendants: AbsoluteDescendants, } impl IntermediateInlineFragments { fn new() -> IntermediateInlineFragments { IntermediateInlineFragments { fragments: LinkedList::new(), absolute_descendants: AbsoluteDescendants::new(), } } fn is_empty(&self) -> bool { self.fragments.is_empty() && self.absolute_descendants.is_empty() } fn push_all(&mut self, mut other: IntermediateInlineFragments) { self.fragments.append(&mut other.fragments); self.absolute_descendants.push_descendants(other.absolute_descendants); } } /// Holds inline fragments that we're gathering for children of an inline node. struct InlineFragmentsAccumulator { /// The list of fragments. fragments: IntermediateInlineFragments, /// Information about the inline box directly enclosing the fragments being gathered, if any. /// /// `inline::InlineFragmentNodeInfo` also stores flags indicating whether a fragment is the /// first and/or last of the corresponding inline box. This `InlineFragmentsAccumulator` may /// represent only one side of an {ib} split, so we store these flags as if it represented only /// one fragment. `to_intermediate_inline_fragments` later splits this hypothetical fragment /// into pieces, leaving the `FIRST_FRAGMENT_OF_ELEMENT` and `LAST_FRAGMENT_OF_ELEMENT` flags, /// if present, on the first and last fragments of the output. enclosing_node: Option<InlineFragmentNodeInfo>, /// Restyle damage to use for fragments created in this node. restyle_damage: RestyleDamage, /// Bidi control characters to insert before and after these fragments. bidi_control_chars: Option<(&'static str, &'static str)>, } impl InlineFragmentsAccumulator { fn new() -> InlineFragmentsAccumulator { InlineFragmentsAccumulator { fragments: IntermediateInlineFragments::new(), enclosing_node: None, bidi_control_chars: None, restyle_damage: RestyleDamage::empty(), } } fn from_inline_node<N>(node: &N, style_context: &SharedStyleContext) -> InlineFragmentsAccumulator where N: ThreadSafeLayoutNode { InlineFragmentsAccumulator { fragments: IntermediateInlineFragments::new(), enclosing_node: Some(InlineFragmentNodeInfo { address: node.opaque(), pseudo: node.get_pseudo_element_type(), style: node.style(style_context), selected_style: node.selected_style(), flags: InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT | InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT, }), bidi_control_chars: None, restyle_damage: node.restyle_damage(), } } fn push(&mut self, fragment: Fragment) { self.fragments.fragments.push_back(fragment) } fn push_all(&mut self, mut fragments: IntermediateInlineFragments) { self.fragments.fragments.append(&mut fragments.fragments); self.fragments.absolute_descendants.push_descendants(fragments.absolute_descendants); } fn to_intermediate_inline_fragments<N>( self, context: &SharedStyleContext, ) -> IntermediateInlineFragments where N: ThreadSafeLayoutNode, { let InlineFragmentsAccumulator { mut fragments, enclosing_node, bidi_control_chars, restyle_damage, } = self; if let Some(mut enclosing_node) = enclosing_node { let fragment_count = fragments.fragments.len(); for (index, fragment) in fragments.fragments.iter_mut().enumerate() { let mut enclosing_node = enclosing_node.clone(); if index != 0 { enclosing_node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT) } if index != fragment_count - 1 { enclosing_node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT) } fragment.add_inline_context_style(enclosing_node); } // Control characters are later discarded in transform_text, so they don't affect the // is_first/is_last styles above. enclosing_node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT | InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT); if let Some((start, end)) = bidi_control_chars { fragments.fragments.push_front( control_chars_to_fragment::<N::ConcreteElement>( &enclosing_node, context, start, restyle_damage, ) ); fragments.fragments.push_back( control_chars_to_fragment::<N::ConcreteElement>( &enclosing_node, context, end, restyle_damage, ) ); } } fragments } } /// An object that knows how to create flows. pub struct FlowConstructor<'a, N: ThreadSafeLayoutNode> { /// The layout context. pub layout_context: &'a LayoutContext<'a>, /// Satisfy the compiler about the unused parameters, which we use to improve the ergonomics of /// the ensuing impl {} by removing the need to parameterize all the methods individually. phantom2: PhantomData<N>, } impl<'a, ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode> FlowConstructor<'a, ConcreteThreadSafeLayoutNode> { /// Creates a new flow constructor. pub fn new(layout_context: &'a LayoutContext<'a>) -> Self { FlowConstructor { layout_context: layout_context, phantom2: PhantomData, } } #[inline] fn style_context(&self) -> &SharedStyleContext { self.layout_context.shared_context() } #[inline] fn set_flow_construction_result(&self, node: &ConcreteThreadSafeLayoutNode, result: ConstructionResult) { node.set_flow_construction_result(result); } /// Builds the fragment for the given block or subclass thereof. fn build_fragment_for_block(&self, node: &ConcreteThreadSafeLayoutNode) -> Fragment { let specific_fragment_info = match node.type_id() { Some(LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement)) => { SpecificFragmentInfo::Iframe(IframeFragmentInfo::new(node)) } Some(LayoutNodeType::Element(LayoutElementType::HTMLImageElement)) => { let image_info = Box::new(ImageFragmentInfo::new( node.image_url(), node, &self.layout_context )); SpecificFragmentInfo::Image(image_info) } Some(LayoutNodeType::Element(LayoutElementType::HTMLObjectElement)) => { let image_info = Box::new(ImageFragmentInfo::new( node.object_data(), node, &self.layout_context )); SpecificFragmentInfo::Image(image_info) } Some(LayoutNodeType::Element(LayoutElementType::HTMLTableElement)) => { SpecificFragmentInfo::TableWrapper } Some(LayoutNodeType::Element(LayoutElementType::HTMLTableColElement)) => { SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)) } Some(LayoutNodeType::Element(LayoutElementType::HTMLTableCellElement)) => { SpecificFragmentInfo::TableCell } Some(LayoutNodeType::Element(LayoutElementType::HTMLTableRowElement)) | Some(LayoutNodeType::Element(LayoutElementType::HTMLTableSectionElement)) => { SpecificFragmentInfo::TableRow } Some(LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement)) => { let data = node.canvas_data().unwrap(); SpecificFragmentInfo::Canvas(Box::new(CanvasFragmentInfo::new(data))) } Some(LayoutNodeType::Element(LayoutElementType::SVGSVGElement)) => { let data = node.svg_data().unwrap(); SpecificFragmentInfo::Svg(Box::new(SvgFragmentInfo::new(data))) } _ => { // This includes pseudo-elements. SpecificFragmentInfo::Generic } }; Fragment::new(node, specific_fragment_info, self.layout_context) } /// Creates an inline flow from a set of inline fragments, then adds it as a child of the given /// flow or pushes it onto the given flow list. /// /// `#[inline(always)]` because this is performance critical and LLVM will not inline it /// otherwise. #[inline(always)] fn flush_inline_fragments_to_flow( &mut self, fragment_accumulator: InlineFragmentsAccumulator, flow: &mut FlowRef, absolute_descendants: &mut AbsoluteDescendants, legalizer: &mut Legalizer, node: &ConcreteThreadSafeLayoutNode, ) { let mut fragments = fragment_accumulator.to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>( self.style_context(), ); if fragments.is_empty() { return }; strip_ignorable_whitespace_from_start(&mut fragments.fragments); strip_ignorable_whitespace_from_end(&mut fragments.fragments); if fragments.fragments.is_empty() { absolute_descendants.push_descendants(fragments.absolute_descendants); return } // Build a list of all the inline-block fragments before fragments is moved. let mut inline_block_flows = vec!(); for fragment in &fragments.fragments { match fragment.specific { SpecificFragmentInfo::InlineBlock(ref info) => { inline_block_flows.push(info.flow_ref.clone()) } SpecificFragmentInfo::InlineAbsoluteHypothetical(ref info) => { inline_block_flows.push(info.flow_ref.clone()) } SpecificFragmentInfo::InlineAbsolute(ref info) => { inline_block_flows.push(info.flow_ref.clone()) } _ => {} } } // We must scan for runs before computing minimum ascent and descent because scanning // for runs might collapse so much whitespace away that only hypothetical fragments // remain. In that case the inline flow will compute its ascent and descent to be zero. let scanned_fragments = with_thread_local_font_context(self.layout_context, |font_context| { TextRunScanner::new().scan_for_runs(font_context, mem::replace(&mut fragments.fragments, LinkedList::new())) }); let mut inline_flow_ref = FlowRef::new(Arc::new(InlineFlow::from_fragments(scanned_fragments, node.style(self.style_context()).writing_mode))); // Add all the inline-block fragments as children of the inline flow. for inline_block_flow in &inline_block_flows { inline_flow_ref.add_new_child(inline_block_flow.clone()); } // Set up absolute descendants as necessary. // // The inline flow itself may need to become the containing block for absolute descendants // in order to handle cases like: // // <div> // <span style="position: relative"> // <span style="position: absolute; ..."></span> // </span> // </div> // // See the comment above `flow::AbsoluteDescendantInfo` for more information. inline_flow_ref.take_applicable_absolute_descendants(&mut fragments.absolute_descendants); absolute_descendants.push_descendants(fragments.absolute_descendants); { // FIXME(#6503): Use Arc::get_mut().unwrap() here. let inline_flow = FlowRef::deref_mut(&mut inline_flow_ref).as_mut_inline(); inline_flow.minimum_line_metrics = with_thread_local_font_context(self.layout_context, |font_context| { inline_flow.minimum_line_metrics(font_context, &node.style(self.style_context())) }); } inline_flow_ref.finish(); legalizer.add_child::<ConcreteThreadSafeLayoutNode::ConcreteElement>( self.style_context(), flow, inline_flow_ref, ) } fn build_block_flow_using_construction_result_of_child( &mut self, flow: &mut FlowRef, node: &ConcreteThreadSafeLayoutNode, kid: ConcreteThreadSafeLayoutNode, inline_fragment_accumulator: &mut InlineFragmentsAccumulator, abs_descendants: &mut AbsoluteDescendants, legalizer: &mut Legalizer) { match kid.get_construction_result() { ConstructionResult::None => {} ConstructionResult::Flow(kid_flow, kid_abs_descendants) => { // If kid_flow is TableCaptionFlow, kid_flow should be added under // TableWrapperFlow. if flow.is_table() && kid_flow.is_table_caption() { let construction_result = ConstructionResult::Flow(kid_flow, AbsoluteDescendants::new()); self.set_flow_construction_result(&kid, construction_result) } else { if !kid_flow.base().flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { // Flush any inline fragments that we were gathering up. This allows us to // handle {ib} splits. let old_inline_fragment_accumulator = mem::replace(inline_fragment_accumulator, InlineFragmentsAccumulator::new()); self.flush_inline_fragments_to_flow(old_inline_fragment_accumulator, flow, abs_descendants, legalizer, node); } legalizer.add_child::<ConcreteThreadSafeLayoutNode::ConcreteElement>( self.style_context(), flow, kid_flow, ) } abs_descendants.push_descendants(kid_abs_descendants); } ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits, fragments: successor_fragments, })) => { // Add any {ib} splits. for split in splits { // Pull apart the {ib} split object and push its predecessor fragments // onto the list. let InlineBlockSplit { predecessors, flow: kid_flow } = split; inline_fragment_accumulator.push_all(predecessors); // Flush any inline fragments that we were gathering up. debug!("flushing {} inline box(es) to flow A", inline_fragment_accumulator.fragments.fragments.len()); let old_inline_fragment_accumulator = mem::replace(inline_fragment_accumulator, InlineFragmentsAccumulator::new()); let absolute_descendants = &mut inline_fragment_accumulator.fragments.absolute_descendants; self.flush_inline_fragments_to_flow(old_inline_fragment_accumulator, flow, absolute_descendants, legalizer, node); // Push the flow generated by the {ib} split onto our list of flows. legalizer.add_child::<ConcreteThreadSafeLayoutNode::ConcreteElement>( self.style_context(), flow, kid_flow, ) } // Add the fragments to the list we're maintaining. inline_fragment_accumulator.push_all(successor_fragments); } ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( whitespace_node, whitespace_pseudo, whitespace_style, whitespace_damage)) => { // Add whitespace results. They will be stripped out later on when // between block elements, and retained when between inline elements. let fragment_info = SpecificFragmentInfo::UnscannedText( Box::new(UnscannedTextFragmentInfo::new(Box::<str>::from(" "), None)) ); let fragment = Fragment::from_opaque_node_and_style(whitespace_node, whitespace_pseudo, whitespace_style, node.selected_style(), whitespace_damage, fragment_info); inline_fragment_accumulator.fragments.fragments.push_back(fragment); } ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment(_)) => { // TODO: Implement anonymous table objects for missing parents // CSS 2.1 § 17.2.1, step 3-2 } } } /// Constructs a block flow, beginning with the given `initial_fragments` if present and then /// appending the construction results of children to the child list of the block flow. {ib} /// splits and absolutely-positioned descendants are handled correctly. fn build_flow_for_block_starting_with_fragments( &mut self, mut flow: FlowRef, node: &ConcreteThreadSafeLayoutNode, initial_fragments: IntermediateInlineFragments) -> ConstructionResult { // Gather up fragments for the inline flows we might need to create. let mut inline_fragment_accumulator = InlineFragmentsAccumulator::new(); inline_fragment_accumulator.fragments.push_all(initial_fragments); // List of absolute descendants, in tree order. let mut abs_descendants = AbsoluteDescendants::new(); let mut legalizer = Legalizer::new(); if !node.is_replaced_content() { for kid in node.children() { if kid.get_pseudo_element_type() != PseudoElementType::Normal { self.process(&kid); } self.build_block_flow_using_construction_result_of_child( &mut flow, node, kid, &mut inline_fragment_accumulator, &mut abs_descendants, &mut legalizer); } } // Perform a final flush of any inline fragments that we were gathering up to handle {ib} // splits, after stripping ignorable whitespace. self.flush_inline_fragments_to_flow(inline_fragment_accumulator, &mut flow, &mut abs_descendants, &mut legalizer, node); // The flow is done. legalizer.finish(&mut flow); flow.finish(); // Set up the absolute descendants. if flow.is_absolute_containing_block() { // This is the containing block for all the absolute descendants. flow.set_absolute_descendants(abs_descendants); abs_descendants = AbsoluteDescendants::new(); if flow.base().flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { // This is now the only absolute flow in the subtree which hasn't yet // reached its CB. abs_descendants.push(flow.clone()); } } ConstructionResult::Flow(flow, abs_descendants) } /// Constructs a flow for the given block node and its children. This method creates an /// initial fragment as appropriate and then dispatches to /// `build_flow_for_block_starting_with_fragments`. Currently the following kinds of flows get /// initial content: /// /// * Generated content gets the initial content specified by the `content` attribute of the /// CSS. /// * `<input>` and `<textarea>` elements get their content. /// /// FIXME(pcwalton): It is not clear to me that there isn't a cleaner way to handle /// `<textarea>`. fn build_flow_for_block_like(&mut self, flow: FlowRef, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let mut fragments = IntermediateInlineFragments::new(); let node_is_input_or_text_area = node.type_id() == Some(LayoutNodeType::Element(LayoutElementType::HTMLInputElement)) || node.type_id() == Some(LayoutNodeType::Element(LayoutElementType::HTMLTextAreaElement)); if node.get_pseudo_element_type().is_replaced_content() || node_is_input_or_text_area { // A TextArea's text contents are displayed through the input text // box, so don't construct them. if node.type_id() == Some(LayoutNodeType::Element(LayoutElementType::HTMLTextAreaElement)) { for kid in node.children() { self.set_flow_construction_result(&kid, ConstructionResult::None) } } let context = self.style_context(); let mut style = node.style(context); style = context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &context.guards, &PseudoElement::ServoText, &style, ); if node_is_input_or_text_area { style = context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &context.guards, &PseudoElement::ServoInputText, &style, ) } self.create_fragments_for_node_text_content(&mut fragments, node, &style) } self.build_flow_for_block_starting_with_fragments(flow, node, fragments) } /// Pushes fragments appropriate for the content of the given node onto the given list. fn create_fragments_for_node_text_content(&self, fragments: &mut IntermediateInlineFragments, node: &ConcreteThreadSafeLayoutNode, style: &ServoArc<ComputedValues>) { // Fast path: If there is no text content, return immediately. let text_content = node.text_content(); if text_content.is_empty() { return } let style = (*style).clone(); let selected_style = node.selected_style(); match text_content { TextContent::Text(string) => { let info = Box::new(UnscannedTextFragmentInfo::new(string, node.selection())); let specific_fragment_info = SpecificFragmentInfo::UnscannedText(info); fragments.fragments.push_back(Fragment::from_opaque_node_and_style( node.opaque(), node.get_pseudo_element_type(), style, selected_style, node.restyle_damage(), specific_fragment_info)) } TextContent::GeneratedContent(content_items) => { for content_item in content_items.into_iter() { let specific_fragment_info = match content_item { ContentItem::String(string) => { let info = Box::new(UnscannedTextFragmentInfo::new(string, None)); SpecificFragmentInfo::UnscannedText(info) }, content_item => { let content_item = Box::new(GeneratedContentInfo::ContentItem(content_item)); SpecificFragmentInfo::GeneratedContent(content_item) } }; fragments.fragments.push_back(Fragment::from_opaque_node_and_style( node.opaque(), node.get_pseudo_element_type(), style.clone(), selected_style.clone(), node.restyle_damage(), specific_fragment_info)) } } } } /// Builds a flow for a node with `display: block`. This yields a `BlockFlow` with possibly /// other `BlockFlow`s or `InlineFlow`s underneath it, depending on whether {ib} splits needed /// to happen. fn build_flow_for_block(&mut self, node: &ConcreteThreadSafeLayoutNode, float_kind: Option<FloatKind>) -> ConstructionResult { if node.style(self.style_context()).is_multicol() { return self.build_flow_for_multicol(node, float_kind) } let fragment = self.build_fragment_for_block(node); let flow = FlowRef::new(Arc::new(BlockFlow::from_fragment_and_float_kind(fragment, float_kind))); self.build_flow_for_block_like(flow, node) } /// Bubbles up {ib} splits. fn accumulate_inline_block_splits(&mut self, splits: LinkedList<InlineBlockSplit>, node: &ConcreteThreadSafeLayoutNode, fragment_accumulator: &mut InlineFragmentsAccumulator, opt_inline_block_splits: &mut LinkedList<InlineBlockSplit>) { for split in splits { let InlineBlockSplit { predecessors, flow: kid_flow } = split; fragment_accumulator.push_all(predecessors); opt_inline_block_splits.push_back( InlineBlockSplit::new(fragment_accumulator, node, self.style_context(), kid_flow)); } } /// Concatenates the fragments of kids, adding in our own borders/padding/margins if necessary. /// Returns the `InlineFragmentsConstructionResult`, if any. There will be no /// `InlineFragmentsConstructionResult` if this node consisted entirely of ignorable /// whitespace. fn build_fragments_for_nonreplaced_inline_content(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let mut opt_inline_block_splits: LinkedList<InlineBlockSplit> = LinkedList::new(); let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node(node, self.style_context()); fragment_accumulator.bidi_control_chars = bidi_control_chars(&node.style(self.style_context())); let mut abs_descendants = AbsoluteDescendants::new(); // Concatenate all the fragments of our kids, creating {ib} splits as necessary. let mut is_empty = true; for kid in node.children() { is_empty = false;<|fim▁hole|> } match kid.get_construction_result() { ConstructionResult::None => {} ConstructionResult::Flow(flow, kid_abs_descendants) => { if !flow.base().flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { opt_inline_block_splits.push_back(InlineBlockSplit::new( &mut fragment_accumulator, node, self.style_context(), flow)); abs_descendants.push_descendants(kid_abs_descendants); } else { // Push the absolutely-positioned kid as an inline containing block. let kid_node = flow.as_block().fragment.node; let kid_pseudo = flow.as_block().fragment.pseudo.clone(); let kid_style = flow.as_block().fragment.style.clone(); let kid_selected_style = flow.as_block().fragment.selected_style.clone(); let kid_restyle_damage = flow.as_block().fragment.restyle_damage; let fragment_info = SpecificFragmentInfo::InlineAbsolute( InlineAbsoluteFragmentInfo::new(flow)); fragment_accumulator.push(Fragment::from_opaque_node_and_style( kid_node, kid_pseudo, kid_style, kid_selected_style, kid_restyle_damage, fragment_info)); fragment_accumulator.fragments .absolute_descendants .push_descendants(kid_abs_descendants); } } ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits, fragments: successors, })) => { // Bubble up {ib} splits. self.accumulate_inline_block_splits(splits, node, &mut fragment_accumulator, &mut opt_inline_block_splits); // Push residual fragments. fragment_accumulator.push_all(successors); } ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( whitespace_node, whitespace_pseudo, whitespace_style, whitespace_damage)) => { // Instantiate the whitespace fragment. let fragment_info = SpecificFragmentInfo::UnscannedText( Box::new(UnscannedTextFragmentInfo::new(Box::<str>::from(" "), None)) ); let fragment = Fragment::from_opaque_node_and_style(whitespace_node, whitespace_pseudo, whitespace_style, node.selected_style(), whitespace_damage, fragment_info); fragment_accumulator.fragments.fragments.push_back(fragment) } ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment(_)) => { // TODO: Implement anonymous table objects for missing parents // CSS 2.1 § 17.2.1, step 3-2 } } } let node_style = node.style(self.style_context()); if is_empty && node_style.has_padding_or_border() { // An empty inline box needs at least one fragment to draw its background and borders. let info = SpecificFragmentInfo::UnscannedText( Box::new(UnscannedTextFragmentInfo::new(Box::<str>::from(""), None)) ); let fragment = Fragment::from_opaque_node_and_style(node.opaque(), node.get_pseudo_element_type(), node_style.clone(), node.selected_style(), node.restyle_damage(), info); fragment_accumulator.fragments.fragments.push_back(fragment) } // Finally, make a new construction result. if opt_inline_block_splits.len() > 0 || !fragment_accumulator.fragments.is_empty() || abs_descendants.len() > 0 { fragment_accumulator.fragments.absolute_descendants.push_descendants(abs_descendants); // If the node is positioned, then it's the containing block for all absolutely- // positioned descendants. if node_style.get_box().position != Position::Static { fragment_accumulator.fragments .absolute_descendants .mark_as_having_reached_containing_block(); } let construction_item = ConstructionItem::InlineFragments( InlineFragmentsConstructionResult { splits: opt_inline_block_splits, fragments: fragment_accumulator.to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>( self.style_context(), ), }); ConstructionResult::ConstructionItem(construction_item) } else { ConstructionResult::None } } /// Creates an `InlineFragmentsConstructionResult` for replaced content. Replaced content /// doesn't render its children, so this just nukes a child's fragments and creates a /// `Fragment`. fn build_fragments_for_replaced_inline_content(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { for kid in node.children() { self.set_flow_construction_result(&kid, ConstructionResult::None) } let context = self.style_context(); let style = node.style(context); // If this node is ignorable whitespace, bail out now. if node.is_ignorable_whitespace(context) { return ConstructionResult::ConstructionItem(ConstructionItem::Whitespace( node.opaque(), node.get_pseudo_element_type(), context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &context.guards, &PseudoElement::ServoText, &style, ), node.restyle_damage(), )) } // If this is generated content, then we need to initialize the accumulator with the // fragment corresponding to that content. Otherwise, just initialize with the ordinary // fragment that needs to be generated for this inline node. let mut fragments = IntermediateInlineFragments::new(); match (node.get_pseudo_element_type(), node.type_id()) { (_, Some(LayoutNodeType::Text)) => { let text_style = context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &context.guards, &PseudoElement::ServoText, &style, ); self.create_fragments_for_node_text_content(&mut fragments, node, &text_style) } (PseudoElementType::Normal, _) => { fragments.fragments.push_back(self.build_fragment_for_block(node)); } (_, _) => self.create_fragments_for_node_text_content(&mut fragments, node, &style), } let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: LinkedList::new(), fragments: fragments, }); ConstructionResult::ConstructionItem(construction_item) } /// Build the fragment for an inline-block or inline-flex, based on the `display` flag fn build_fragment_for_inline_block_or_inline_flex( &mut self, node: &ConcreteThreadSafeLayoutNode, display: Display, ) -> ConstructionResult { let block_flow_result = match display { Display::InlineBlock => self.build_flow_for_block(node, None), Display::InlineFlex => self.build_flow_for_flex(node, None), _ => panic!("The flag should be inline-block or inline-flex") }; let (block_flow, abs_descendants) = match block_flow_result { ConstructionResult::Flow(block_flow, abs_descendants) => (block_flow, abs_descendants), _ => unreachable!() }; let context = self.style_context(); let style = node.style(context); let style = context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &context.guards, &PseudoElement::ServoInlineBlockWrapper, &style, ); let fragment_info = SpecificFragmentInfo::InlineBlock(InlineBlockFragmentInfo::new( block_flow)); let fragment = Fragment::from_opaque_node_and_style(node.opaque(), node.get_pseudo_element_type(), style, node.selected_style(), node.restyle_damage(), fragment_info); let mut fragment_accumulator = InlineFragmentsAccumulator::new(); fragment_accumulator.fragments.fragments.push_back(fragment); fragment_accumulator.fragments.absolute_descendants.push_descendants(abs_descendants); let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: LinkedList::new(), fragments: fragment_accumulator .to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>(context), }); ConstructionResult::ConstructionItem(construction_item) } /// This is an annoying case, because the computed `display` value is `block`, but the /// hypothetical box is inline. fn build_fragment_for_absolutely_positioned_inline(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let block_flow_result = self.build_flow_for_block(node, None); let (block_flow, abs_descendants) = match block_flow_result { ConstructionResult::Flow(block_flow, abs_descendants) => (block_flow, abs_descendants), _ => unreachable!() }; let fragment_info = SpecificFragmentInfo::InlineAbsoluteHypothetical( InlineAbsoluteHypotheticalFragmentInfo::new(block_flow)); let style_context = self.style_context(); let style = node.style(style_context); let style = style_context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &style_context.guards, &PseudoElement::ServoInlineAbsolute, &style, ); let fragment = Fragment::from_opaque_node_and_style(node.opaque(), PseudoElementType::Normal, style, node.selected_style(), node.restyle_damage(), fragment_info); let mut fragment_accumulator = InlineFragmentsAccumulator::from_inline_node(node, self.style_context()); fragment_accumulator.fragments.fragments.push_back(fragment); fragment_accumulator.fragments.absolute_descendants.push_descendants(abs_descendants); let construction_item = ConstructionItem::InlineFragments(InlineFragmentsConstructionResult { splits: LinkedList::new(), fragments: fragment_accumulator .to_intermediate_inline_fragments::<ConcreteThreadSafeLayoutNode>(style_context), }); ConstructionResult::ConstructionItem(construction_item) } /// Builds one or more fragments for a node with `display: inline`. This yields an /// `InlineFragmentsConstructionResult`. fn build_fragments_for_inline(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { // Is this node replaced content? if !node.is_replaced_content() { // Go to a path that concatenates our kids' fragments. self.build_fragments_for_nonreplaced_inline_content(node) } else { // Otherwise, just nuke our kids' fragments, create our fragment if any, and be done // with it. self.build_fragments_for_replaced_inline_content(node) } } /// Places any table captions found under the given table wrapper, if the value of their /// `caption-side` property is equal to the given `side`. fn place_table_caption_under_table_wrapper_on_side(&mut self, table_wrapper_flow: &mut FlowRef, node: &ConcreteThreadSafeLayoutNode, side: CaptionSide) { // Only flows that are table captions are matched here. for kid in node.children() { match kid.get_construction_result() { ConstructionResult::Flow(kid_flow, _) => { if kid_flow.is_table_caption() && kid_flow.as_block() .fragment .style() .get_inheritedtable() .caption_side == side { table_wrapper_flow.add_new_child(kid_flow); } } ConstructionResult::None | ConstructionResult::ConstructionItem(_) => {} } } } /// Builds a flow for a node with `column-count` or `column-width` non-`auto`. /// This yields a `MulticolFlow` with a single `MulticolColumnFlow` underneath it. fn build_flow_for_multicol(&mut self, node: &ConcreteThreadSafeLayoutNode, float_kind: Option<FloatKind>) -> ConstructionResult { let fragment = Fragment::new(node, SpecificFragmentInfo::Multicol, self.layout_context); let mut flow = FlowRef::new(Arc::new(MulticolFlow::from_fragment(fragment, float_kind))); let column_fragment = Fragment::new(node, SpecificFragmentInfo::MulticolColumn, self.layout_context); let column_flow = FlowRef::new(Arc::new(MulticolColumnFlow::from_fragment(column_fragment))); // First populate the column flow with its children. let construction_result = self.build_flow_for_block_like(column_flow, node); let mut abs_descendants = AbsoluteDescendants::new(); if let ConstructionResult::Flow(column_flow, column_abs_descendants) = construction_result { flow.add_new_child(column_flow); abs_descendants.push_descendants(column_abs_descendants); } // The flow is done. flow.finish(); if flow.is_absolute_containing_block() { // This is the containing block for all the absolute descendants. flow.set_absolute_descendants(abs_descendants); abs_descendants = AbsoluteDescendants::new(); if flow.base().flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { // This is now the only absolute flow in the subtree which hasn't yet // reached its containing block. abs_descendants.push(flow.clone()); } } ConstructionResult::Flow(flow, abs_descendants) } /// Builds a flow for a node with `display: table`. This yields a `TableWrapperFlow` with /// possibly other `TableCaptionFlow`s or `TableFlow`s underneath it. fn build_flow_for_table(&mut self, node: &ConcreteThreadSafeLayoutNode, float_value: Float) -> ConstructionResult { let mut legalizer = Legalizer::new(); let table_style; let wrapper_style; { let context = self.style_context(); table_style = node.style(context); wrapper_style = context.stylist.style_for_anonymous::<ConcreteThreadSafeLayoutNode::ConcreteElement>( &context.guards, &PseudoElement::ServoTableWrapper, &table_style, ); } let wrapper_fragment = Fragment::from_opaque_node_and_style(node.opaque(), PseudoElementType::Normal, wrapper_style, node.selected_style(), node.restyle_damage(), SpecificFragmentInfo::TableWrapper); let wrapper_float_kind = FloatKind::from_property(float_value); let mut wrapper_flow = FlowRef::new(Arc::new(TableWrapperFlow::from_fragment_and_float_kind(wrapper_fragment, wrapper_float_kind))); let table_fragment = Fragment::new(node, SpecificFragmentInfo::Table, self.layout_context); let table_flow = FlowRef::new(Arc::new(TableFlow::from_fragment(table_fragment))); // First populate the table flow with its children. let construction_result = self.build_flow_for_block_like(table_flow, node); let mut abs_descendants = AbsoluteDescendants::new(); // The order of the caption and the table are not necessarily the same order as in the DOM // tree. All caption blocks are placed before or after the table flow, depending on the // value of `caption-side`. self.place_table_caption_under_table_wrapper_on_side(&mut wrapper_flow, node, CaptionSide::Top); if let ConstructionResult::Flow(table_flow, table_abs_descendants) = construction_result { legalizer.add_child::<ConcreteThreadSafeLayoutNode::ConcreteElement>( self.style_context(), &mut wrapper_flow, table_flow, ); abs_descendants.push_descendants(table_abs_descendants); } // If the value of `caption-side` is `bottom`, place it now. self.place_table_caption_under_table_wrapper_on_side(&mut wrapper_flow, node, CaptionSide::Bottom); // The flow is done. legalizer.finish(&mut wrapper_flow); wrapper_flow.finish(); if wrapper_flow.is_absolute_containing_block() { // This is the containing block for all the absolute descendants. wrapper_flow.set_absolute_descendants(abs_descendants); abs_descendants = AbsoluteDescendants::new(); if wrapper_flow.base().flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) { // This is now the only absolute flow in the subtree which hasn't yet // reached its containing block. abs_descendants.push(wrapper_flow.clone()); } } ConstructionResult::Flow(wrapper_flow, abs_descendants) } /// Builds a flow for a node with `display: table-caption`. This yields a `TableCaptionFlow` /// with possibly other `BlockFlow`s or `InlineFlow`s underneath it. fn build_flow_for_table_caption(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let fragment = self.build_fragment_for_block(node); let flow = FlowRef::new(Arc::new(TableCaptionFlow::from_fragment(fragment))); self.build_flow_for_block_like(flow, node) } /// Builds a flow for a node with `display: table-row-group`. This yields a `TableRowGroupFlow` /// with possibly other `TableRowFlow`s underneath it. fn build_flow_for_table_rowgroup(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let fragment = Fragment::new(node, SpecificFragmentInfo::TableRow, self.layout_context); let flow = FlowRef::new(Arc::new(TableRowGroupFlow::from_fragment(fragment))); self.build_flow_for_block_like(flow, node) } /// Builds a flow for a node with `display: table-row`. This yields a `TableRowFlow` with /// possibly other `TableCellFlow`s underneath it. fn build_flow_for_table_row(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let fragment = Fragment::new(node, SpecificFragmentInfo::TableRow, self.layout_context); let flow = FlowRef::new(Arc::new(TableRowFlow::from_fragment(fragment))); self.build_flow_for_block_like(flow, node) } /// Builds a flow for a node with `display: table-cell`. This yields a `TableCellFlow` with /// possibly other `BlockFlow`s or `InlineFlow`s underneath it. fn build_flow_for_table_cell(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let fragment = Fragment::new(node, SpecificFragmentInfo::TableCell, self.layout_context); // Determine if the table cell should be hidden. Per CSS 2.1 § 17.6.1.1, this will be true // if the cell has any in-flow elements (even empty ones!) and has `empty-cells` set to // `hide`. let hide = node.style(self.style_context()).get_inheritedtable().empty_cells == EmptyCells::Hide && node.children().all(|kid| { let position = kid.style(self.style_context()).get_box().position; !kid.is_content() || position == Position::Absolute || position == Position::Fixed }); let flow = FlowRef::new(Arc::new( TableCellFlow::from_node_fragment_and_visibility_flag(node, fragment, !hide))); self.build_flow_for_block_like(flow, node) } /// Builds a flow for a node with `display: list-item`. This yields a `ListItemFlow` with /// possibly other `BlockFlow`s or `InlineFlow`s underneath it. fn build_flow_for_list_item(&mut self, node: &ConcreteThreadSafeLayoutNode, flotation: Float) -> ConstructionResult { let flotation = FloatKind::from_property(flotation); let marker_fragments = match node.style(self.style_context()).get_list().list_style_image { ImageUrlOrNone::Url(ref url_value) => { let image_info = Box::new(ImageFragmentInfo::new( url_value.url().map(|u| u.clone()), node, &self.layout_context )); vec![Fragment::new(node, SpecificFragmentInfo::Image(image_info), self.layout_context)] } ImageUrlOrNone::None => { match ListStyleTypeContent::from_list_style_type(node.style(self.style_context()) .get_list() .list_style_type) { ListStyleTypeContent::None => Vec::new(), ListStyleTypeContent::StaticText(ch) => { let text = format!("{}\u{a0}", ch); let mut unscanned_marker_fragments = LinkedList::new(); unscanned_marker_fragments.push_back(Fragment::new( node, SpecificFragmentInfo::UnscannedText( Box::new(UnscannedTextFragmentInfo::new(Box::<str>::from(text), None)) ), self.layout_context)); let marker_fragments = with_thread_local_font_context(self.layout_context, |mut font_context| { TextRunScanner::new().scan_for_runs(&mut font_context, unscanned_marker_fragments) }); marker_fragments.fragments } ListStyleTypeContent::GeneratedContent(info) => { vec![Fragment::new(node, SpecificFragmentInfo::GeneratedContent(info), self.layout_context)] } } } }; // If the list marker is outside, it becomes the special "outside fragment" that list item // flows have. If it's inside, it's just a plain old fragment. Note that this means that // we adopt Gecko's behavior rather than WebKit's when the marker causes an {ib} split, // which has caused some malaise (Bugzilla #36854) but CSS 2.1 § 12.5.1 lets me do it, so // there. let mut initial_fragments = IntermediateInlineFragments::new(); let main_fragment = self.build_fragment_for_block(node); let flow = match node.style(self.style_context()).get_list().list_style_position { ListStylePosition::Outside => { Arc::new(ListItemFlow::from_fragments_and_flotation( main_fragment, marker_fragments, flotation)) } ListStylePosition::Inside => { for marker_fragment in marker_fragments { initial_fragments.fragments.push_back(marker_fragment) } Arc::new(ListItemFlow::from_fragments_and_flotation( main_fragment, vec![], flotation)) } }; self.build_flow_for_block_starting_with_fragments(FlowRef::new(flow), node, initial_fragments) } /// Creates a fragment for a node with `display: table-column`. fn build_fragments_for_table_column(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { // CSS 2.1 § 17.2.1. Treat all child fragments of a `table-column` as `display: none`. for kid in node.children() { self.set_flow_construction_result(&kid, ConstructionResult::None) } let specific = SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)); let construction_item = ConstructionItem::TableColumnFragment(Fragment::new(node, specific, self.layout_context)); ConstructionResult::ConstructionItem(construction_item) } /// Builds a flow for a node with `display: table-column-group`. /// This yields a `TableColGroupFlow`. fn build_flow_for_table_colgroup(&mut self, node: &ConcreteThreadSafeLayoutNode) -> ConstructionResult { let fragment = Fragment::new(node, SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)), self.layout_context); let mut col_fragments = vec!(); for kid in node.children() { // CSS 2.1 § 17.2.1. Treat all non-column child fragments of `table-column-group` // as `display: none`. if let ConstructionResult::ConstructionItem(ConstructionItem::TableColumnFragment(fragment)) = kid.get_construction_result() { col_fragments.push(fragment) } } if col_fragments.is_empty() { debug!("add SpecificFragmentInfo::TableColumn for empty colgroup"); let specific = SpecificFragmentInfo::TableColumn(TableColumnFragmentInfo::new(node)); col_fragments.push(Fragment::new(node, specific, self.layout_context)); } let mut flow = FlowRef::new(Arc::new(TableColGroupFlow::from_fragments(fragment, col_fragments))); flow.finish(); ConstructionResult::Flow(flow, AbsoluteDescendants::new()) } /// Builds a flow for a node with 'display: flex'. fn build_flow_for_flex(&mut self, node: &ConcreteThreadSafeLayoutNode, float_kind: Option<FloatKind>) -> ConstructionResult { let fragment = self.build_fragment_for_block(node); let flow = FlowRef::new(Arc::new(FlexFlow::from_fragment(fragment, float_kind))); self.build_flow_for_block_like(flow, node) } /// Attempts to perform incremental repair to account for recent changes to this node. This /// can fail and return false, indicating that flows will need to be reconstructed. /// /// TODO(pcwalton): Add some more fast paths, like toggling `display: none`, adding block kids /// to block parents with no {ib} splits, adding out-of-flow kids, etc. pub fn repair_if_possible(&mut self, node: &ConcreteThreadSafeLayoutNode) -> bool { // We can skip reconstructing the flow if we don't have to reconstruct and none of our kids // did either. // // We visit the kids first and reset their HAS_NEWLY_CONSTRUCTED_FLOW flags after checking // them. NOTE: Make sure not to bail out early before resetting all the flags! let mut need_to_reconstruct = false; // If the node has display: none, it's possible that we haven't even // styled the children once, so we need to bailout early here. if node.style(self.style_context()).get_box().clone_display() == Display::None { return false; } for kid in node.children() { if kid.flags().contains(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW) { kid.remove_flags(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW); need_to_reconstruct = true } } if need_to_reconstruct { return false } if node.restyle_damage().contains(ServoRestyleDamage::RECONSTRUCT_FLOW) { return false } let mut set_has_newly_constructed_flow_flag = false; let result = { let style = node.style(self.style_context()); if style.can_be_fragmented() || style.is_multicol() { return false } let damage = node.restyle_damage(); let mut data = node.mutate_layout_data().unwrap(); match *node.construction_result_mut(&mut *data) { ConstructionResult::None => true, ConstructionResult::Flow(ref mut flow, _) => { // The node's flow is of the same type and has the same set of children and can // therefore be repaired by simply propagating damage and style to the flow. if !flow.is_block_flow() { return false } let flow = FlowRef::deref_mut(flow); flow.mut_base().restyle_damage.insert(damage); flow.repair_style_and_bubble_inline_sizes(&style); true } ConstructionResult::ConstructionItem(ConstructionItem::InlineFragments( ref mut inline_fragments_construction_result)) => { if !inline_fragments_construction_result.splits.is_empty() { return false } for fragment in inline_fragments_construction_result.fragments .fragments .iter_mut() { // Only mutate the styles of fragments that represent the dirty node (including // pseudo-element). if fragment.node != node.opaque() { continue } if fragment.pseudo != node.get_pseudo_element_type() { continue } match fragment.specific { SpecificFragmentInfo::InlineBlock(ref mut inline_block_fragment) => { let flow_ref = FlowRef::deref_mut(&mut inline_block_fragment.flow_ref); flow_ref.mut_base().restyle_damage.insert(damage); // FIXME(pcwalton): Fragment restyle damage too? flow_ref.repair_style_and_bubble_inline_sizes(&style); } SpecificFragmentInfo::InlineAbsoluteHypothetical( ref mut inline_absolute_hypothetical_fragment) => { let flow_ref = FlowRef::deref_mut( &mut inline_absolute_hypothetical_fragment.flow_ref); flow_ref.mut_base().restyle_damage.insert(damage); // FIXME(pcwalton): Fragment restyle damage too? flow_ref.repair_style_and_bubble_inline_sizes(&style); } SpecificFragmentInfo::InlineAbsolute(ref mut inline_absolute_fragment) => { let flow_ref = FlowRef::deref_mut( &mut inline_absolute_fragment.flow_ref); flow_ref.mut_base().restyle_damage.insert(damage); // FIXME(pcwalton): Fragment restyle damage too? flow_ref.repair_style_and_bubble_inline_sizes(&style); } SpecificFragmentInfo::ScannedText(_) => { // Text fragments in ConstructionResult haven't been scanned yet unreachable!() } SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::UnscannedText(_) => { // We can't repair this unscanned text; we need to update the // scanned text fragments. // // TODO: Add code to find and repair the ScannedText fragments? return false } _ => { fragment.repair_style(&style); set_has_newly_constructed_flow_flag = true; } } } true } ConstructionResult::ConstructionItem(_) => { false } } }; if set_has_newly_constructed_flow_flag { node.insert_flags(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW); } return result; } } impl<'a, ConcreteThreadSafeLayoutNode> PostorderNodeMutTraversal<ConcreteThreadSafeLayoutNode> for FlowConstructor<'a, ConcreteThreadSafeLayoutNode> where ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode { // Construct Flow based on 'display', 'position', and 'float' values. // // CSS 2.1 Section 9.7 // // TODO: This should actually consult the table in that section to get the // final computed value for 'display'. fn process(&mut self, node: &ConcreteThreadSafeLayoutNode) { node.insert_flags(LayoutDataFlags::HAS_NEWLY_CONSTRUCTED_FLOW); let style = node.style(self.style_context()); // Bail out if this node has an ancestor with display: none. if style.is_in_display_none_subtree() { self.set_flow_construction_result(node, ConstructionResult::None); return; } // Get the `display` property for this node, and determine whether this node is floated. let (display, float, positioning) = match node.type_id() { None => { // Pseudo-element. (style.get_box().display, style.get_box().float, style.get_box().position) } Some(LayoutNodeType::Element(_)) => { let original_display = style.get_box().original_display; // FIXME(emilio, #19771): This munged_display business is pretty // wrong. After we fix this we should be able to unify the // pseudo-element path too. let munged_display = match original_display { Display::Inline | Display::InlineBlock => original_display, _ => style.get_box().display, }; (munged_display, style.get_box().float, style.get_box().position) } Some(LayoutNodeType::Text) => (Display::Inline, Float::None, Position::Static), }; debug!("building flow for node: {:?} {:?} {:?} {:?}", display, float, positioning, node.type_id()); // Switch on display and floatedness. match (display, float, positioning) { // `display: none` contributes no flow construction result. (Display::None, _, _) => { self.set_flow_construction_result(node, ConstructionResult::None); } // Table items contribute table flow construction results. (Display::Table, float_value, _) => { let construction_result = self.build_flow_for_table(node, float_value); self.set_flow_construction_result(node, construction_result) } // Absolutely positioned elements will have computed value of // `float` as 'none' and `display` as per the table. // Only match here for block items. If an item is absolutely // positioned, but inline we shouldn't try to construct a block // flow here - instead, let it match the inline case // below. (Display::Block, _, Position::Absolute) | (Display::Block, _, Position::Fixed) => { let construction_result = self.build_flow_for_block(node, None); self.set_flow_construction_result(node, construction_result) } // List items contribute their own special flows. (Display::ListItem, float_value, _) => { let construction_result = self.build_flow_for_list_item(node, float_value); self.set_flow_construction_result(node, construction_result) } // Inline items that are absolutely-positioned contribute inline fragment construction // results with a hypothetical fragment. (Display::Inline, _, Position::Absolute) | (Display::InlineBlock, _, Position::Absolute) => { let construction_result = self.build_fragment_for_absolutely_positioned_inline(node); self.set_flow_construction_result(node, construction_result) } // Inline items contribute inline fragment construction results. // // FIXME(pcwalton, #3307): This is not sufficient to handle floated generated content. (Display::Inline, Float::None, _) => { let construction_result = self.build_fragments_for_inline(node); self.set_flow_construction_result(node, construction_result) } // Inline-block items contribute inline fragment construction results. (Display::InlineBlock, Float::None, _) => { let construction_result = self.build_fragment_for_inline_block_or_inline_flex(node, Display::InlineBlock); self.set_flow_construction_result(node, construction_result) } // Table items contribute table flow construction results. (Display::TableCaption, _, _) => { let construction_result = self.build_flow_for_table_caption(node); self.set_flow_construction_result(node, construction_result) } // Table items contribute table flow construction results. (Display::TableColumnGroup, _, _) => { let construction_result = self.build_flow_for_table_colgroup(node); self.set_flow_construction_result(node, construction_result) } // Table items contribute table flow construction results. (Display::TableColumn, _, _) => { let construction_result = self.build_fragments_for_table_column(node); self.set_flow_construction_result(node, construction_result) } // Table items contribute table flow construction results. (Display::TableRowGroup, _, _) | (Display::TableHeaderGroup, _, _) | (Display::TableFooterGroup, _, _) => { let construction_result = self.build_flow_for_table_rowgroup(node); self.set_flow_construction_result(node, construction_result) } // Table items contribute table flow construction results. (Display::TableRow, _, _) => { let construction_result = self.build_flow_for_table_row(node); self.set_flow_construction_result(node, construction_result) } // Table items contribute table flow construction results. (Display::TableCell, _, _) => { let construction_result = self.build_flow_for_table_cell(node); self.set_flow_construction_result(node, construction_result) } // Flex items contribute flex flow construction results. (Display::Flex, float_value, _) => { let float_kind = FloatKind::from_property(float_value); let construction_result = self.build_flow_for_flex(node, float_kind); self.set_flow_construction_result(node, construction_result) } (Display::InlineFlex, _, _) => { let construction_result = self.build_fragment_for_inline_block_or_inline_flex(node, Display::InlineFlex); self.set_flow_construction_result(node, construction_result) } // Block flows that are not floated contribute block flow construction results. // // TODO(pcwalton): Make this only trigger for blocks and handle the other `display` // properties separately. (_, float_value, _) => { let float_kind = FloatKind::from_property(float_value); let construction_result = self.build_flow_for_block(node, float_kind); self.set_flow_construction_result(node, construction_result) } } } } /// A utility trait with some useful methods for node queries. trait NodeUtils { /// Returns true if this node doesn't render its kids and false otherwise. fn is_replaced_content(&self) -> bool; fn construction_result_mut(self, layout_data: &mut LayoutData) -> &mut ConstructionResult; /// Sets the construction result of a flow. fn set_flow_construction_result(self, result: ConstructionResult); /// Returns the construction result for this node. fn get_construction_result(self) -> ConstructionResult; } impl<ConcreteThreadSafeLayoutNode> NodeUtils for ConcreteThreadSafeLayoutNode where ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode { fn is_replaced_content(&self) -> bool { match self.type_id() { Some(LayoutNodeType::Text) | Some(LayoutNodeType::Element(LayoutElementType::HTMLImageElement)) | Some(LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement)) | Some(LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement)) | Some(LayoutNodeType::Element(LayoutElementType::SVGSVGElement)) => true, Some(LayoutNodeType::Element(LayoutElementType::HTMLObjectElement)) => self.has_object_data(), Some(LayoutNodeType::Element(_)) => false, None => self.get_pseudo_element_type().is_replaced_content(), } } fn construction_result_mut(self, data: &mut LayoutData) -> &mut ConstructionResult { match self.get_pseudo_element_type() { PseudoElementType::Before => &mut data.before_flow_construction_result, PseudoElementType::After => &mut data.after_flow_construction_result, PseudoElementType::DetailsSummary => &mut data.details_summary_flow_construction_result, PseudoElementType::DetailsContent => &mut data.details_content_flow_construction_result, PseudoElementType::Normal => &mut data.flow_construction_result, } } #[inline(always)] fn set_flow_construction_result(self, result: ConstructionResult) { let mut layout_data = self.mutate_layout_data().unwrap(); let dst = self.construction_result_mut(&mut *layout_data); *dst = result; } #[inline(always)] fn get_construction_result(self) -> ConstructionResult { let mut layout_data = self.mutate_layout_data().unwrap(); self.construction_result_mut(&mut *layout_data).get() } } /// Methods for interacting with HTMLObjectElement nodes trait ObjectElement { /// Returns true if this node has object data that is correct uri. fn has_object_data(&self) -> bool; /// Returns the "data" attribute value parsed as a URL fn object_data(&self) -> Option<ServoUrl>; } impl<N> ObjectElement for N where N: ThreadSafeLayoutNode { fn has_object_data(&self) -> bool { let elem = self.as_element().unwrap(); let type_and_data = ( elem.get_attr(&ns!(), &local_name!("type")), elem.get_attr(&ns!(), &local_name!("data")), ); match type_and_data { (None, Some(uri)) => is_image_data(uri), _ => false } } fn object_data(&self) -> Option<ServoUrl> { let elem = self.as_element().unwrap(); let type_and_data = ( elem.get_attr(&ns!(), &local_name!("type")), elem.get_attr(&ns!(), &local_name!("data")), ); match type_and_data { (None, Some(uri)) if is_image_data(uri) => ServoUrl::parse(uri).ok(), _ => None } } } // This must not be public because only the layout constructor can call these // methods. trait FlowConstructionUtils { /// Adds a new flow as a child of this flow. Removes the flow from the given leaf set if /// it's present. fn add_new_child(&mut self, new_child: FlowRef); /// Finishes a flow. Once a flow is finished, no more child flows or boxes may be added to it. /// This will normally run the bubble-inline-sizes (minimum and preferred -- i.e. intrinsic -- /// inline-size) calculation, unless the global `bubble_inline-sizes_separately` flag is on. /// /// All flows must be finished at some point, or they will not have their intrinsic inline- /// sizes properly computed. (This is not, however, a memory safety problem.) fn finish(&mut self); } impl FlowConstructionUtils for FlowRef { /// Adds a new flow as a child of this flow. Fails if this flow is marked as a leaf. fn add_new_child(&mut self, mut new_child: FlowRef) { { let kid_base = FlowRef::deref_mut(&mut new_child).mut_base(); kid_base.parallel.parent = parallel::mut_owned_flow_to_unsafe_flow(self); } let base = FlowRef::deref_mut(self).mut_base(); base.children.push_back(new_child); let _ = base.parallel.children_count.fetch_add(1, Ordering::Relaxed); } /// Finishes a flow. Once a flow is finished, no more child flows or fragments may be added to /// it. This will normally run the bubble-inline-sizes (minimum and preferred -- i.e. intrinsic /// -- inline-size) calculation, unless the global `bubble_inline-sizes_separately` flag is on. /// /// All flows must be finished at some point, or they will not have their intrinsic inline-sizes /// properly computed. (This is not, however, a memory safety problem.) fn finish(&mut self) { if !opts::get().bubble_inline_sizes_separately { FlowRef::deref_mut(self).bubble_inline_sizes(); FlowRef::deref_mut(self).mut_base().restyle_damage.remove(ServoRestyleDamage::BUBBLE_ISIZES); } } } /// Strips ignorable whitespace from the start of a list of fragments. pub fn strip_ignorable_whitespace_from_start(this: &mut LinkedList<Fragment>) { if this.is_empty() { return // Fast path. } let mut leading_fragments_consisting_of_solely_bidi_control_characters = LinkedList::new(); while !this.is_empty() { match this.front_mut().as_mut().unwrap().strip_leading_whitespace_if_necessary() { WhitespaceStrippingResult::RetainFragment => break, WhitespaceStrippingResult::FragmentContainedOnlyBidiControlCharacters => { leading_fragments_consisting_of_solely_bidi_control_characters.push_back( this.pop_front().unwrap()) } WhitespaceStrippingResult::FragmentContainedOnlyWhitespace => { let removed_fragment = this.pop_front().unwrap(); if let Some(ref mut remaining_fragment) = this.front_mut() { remaining_fragment.meld_with_prev_inline_fragment(&removed_fragment); } } } } prepend_from(this, &mut leading_fragments_consisting_of_solely_bidi_control_characters); } /// Strips ignorable whitespace from the end of a list of fragments. pub fn strip_ignorable_whitespace_from_end(this: &mut LinkedList<Fragment>) { if this.is_empty() { return } let mut trailing_fragments_consisting_of_solely_bidi_control_characters = LinkedList::new(); while !this.is_empty() { match this.back_mut().as_mut().unwrap().strip_trailing_whitespace_if_necessary() { WhitespaceStrippingResult::RetainFragment => break, WhitespaceStrippingResult::FragmentContainedOnlyBidiControlCharacters => { trailing_fragments_consisting_of_solely_bidi_control_characters.push_front( this.pop_back().unwrap()) } WhitespaceStrippingResult::FragmentContainedOnlyWhitespace => { let removed_fragment = this.pop_back().unwrap(); if let Some(ref mut remaining_fragment) = this.back_mut() { remaining_fragment.meld_with_next_inline_fragment(&removed_fragment); } } } } this.append(&mut trailing_fragments_consisting_of_solely_bidi_control_characters); } /// If the 'unicode-bidi' property has a value other than 'normal', return the bidi control codes /// to inject before and after the text content of the element. fn bidi_control_chars(style: &ServoArc<ComputedValues>) -> Option<(&'static str, &'static str)> { use style::computed_values::direction::T::*; use style::computed_values::unicode_bidi::T::*; let unicode_bidi = style.get_text().unicode_bidi; let direction = style.get_inheritedbox().direction; // See the table in http://dev.w3.org/csswg/css-writing-modes/#unicode-bidi match (unicode_bidi, direction) { (Normal, _) => None, (Embed, Ltr) => Some(("\u{202A}", "\u{202C}")), (Embed, Rtl) => Some(("\u{202B}", "\u{202C}")), (Isolate, Ltr) => Some(("\u{2066}", "\u{2069}")), (Isolate, Rtl) => Some(("\u{2067}", "\u{2069}")), (BidiOverride, Ltr) => Some(("\u{202D}", "\u{202C}")), (BidiOverride, Rtl) => Some(("\u{202E}", "\u{202C}")), (IsolateOverride, Ltr) => Some(("\u{2068}\u{202D}", "\u{202C}\u{2069}")), (IsolateOverride, Rtl) => Some(("\u{2068}\u{202E}", "\u{202C}\u{2069}")), (Plaintext, _) => Some(("\u{2068}", "\u{2069}")), } } fn control_chars_to_fragment<E>( node: &InlineFragmentNodeInfo, context: &SharedStyleContext, text: &str, restyle_damage: RestyleDamage, ) -> Fragment where E: TElement, { let info = SpecificFragmentInfo::UnscannedText( Box::new(UnscannedTextFragmentInfo::new(Box::<str>::from(text), None)) ); let text_style = context.stylist.style_for_anonymous::<E>( &context.guards, &PseudoElement::ServoText, &node.style, ); Fragment::from_opaque_node_and_style(node.address, node.pseudo, text_style, node.selected_style.clone(), restyle_damage, info) } /// Convenience methods for computed CSS values trait ComputedValueUtils { /// Returns true if this node has non-zero padding or border. fn has_padding_or_border(&self) -> bool; } impl ComputedValueUtils for ComputedValues { fn has_padding_or_border(&self) -> bool { let padding = self.get_padding(); let border = self.get_border(); !padding.padding_top.is_definitely_zero() || !padding.padding_right.is_definitely_zero() || !padding.padding_bottom.is_definitely_zero() || !padding.padding_left.is_definitely_zero() || border.border_top_width.px() != 0. || border.border_right_width.px() != 0. || border.border_bottom_width.px() != 0. || border.border_left_width.px() != 0. } } /// Maintains a stack of anonymous boxes needed to ensure that the flow tree is *legal*. The tree /// is legal if it follows the rules in CSS 2.1 § 17.2.1. /// /// As an example, the legalizer makes sure that table row flows contain only table cells. If the /// flow constructor attempts to place, say, a block flow directly underneath the table row, the /// legalizer generates an anonymous table cell in between to hold the block. /// /// Generally, the flow constructor should use `Legalizer::add_child()` instead of calling /// `Flow::add_new_child()` directly. This ensures that the flow tree remains legal at all times /// and centralizes the anonymous flow generation logic in one place. struct Legalizer { /// A stack of anonymous flows that have yet to be finalized (i.e. that still could acquire new /// children). stack: Vec<FlowRef>, } impl Legalizer { /// Creates a new legalizer. fn new() -> Legalizer { Legalizer { stack: vec![], } } /// Makes the `child` flow a new child of `parent`. Anonymous flows are automatically inserted /// to keep the tree legal. fn add_child<E>( &mut self, context: &SharedStyleContext, parent: &mut FlowRef, mut child: FlowRef, ) where E: TElement, { while !self.stack.is_empty() { if self.try_to_add_child::<E>(context, parent, &mut child) { return } self.flush_top_of_stack(parent) } while !self.try_to_add_child::<E>(context, parent, &mut child) { self.push_next_anonymous_flow::<E>(context, parent) } } /// Flushes all flows we've been gathering up. fn finish(mut self, parent: &mut FlowRef) { while !self.stack.is_empty() { self.flush_top_of_stack(parent) } } /// Attempts to make `child` a child of `parent`. On success, this returns true. If this would /// make the tree illegal, this method does nothing and returns false. /// /// This method attempts to create anonymous blocks in between `parent` and `child` if and only /// if those blocks will only ever have `child` as their sole child. At present, this is only /// true for anonymous block children of flex flows. fn try_to_add_child<E>( &mut self, context: &SharedStyleContext, parent: &mut FlowRef, child: &mut FlowRef, ) -> bool where E: TElement, { let parent = self.stack.last_mut().unwrap_or(parent); let (parent_class, child_class) = (parent.class(), child.class()); match (parent_class, child_class) { (FlowClass::TableWrapper, FlowClass::Table) | (FlowClass::Table, FlowClass::TableColGroup) | (FlowClass::Table, FlowClass::TableRowGroup) | (FlowClass::Table, FlowClass::TableRow) | (FlowClass::Table, FlowClass::TableCaption) | (FlowClass::TableRowGroup, FlowClass::TableRow) | (FlowClass::TableRow, FlowClass::TableCell) => { parent.add_new_child((*child).clone()); true } (FlowClass::TableWrapper, _) | (FlowClass::Table, _) | (FlowClass::TableRowGroup, _) | (FlowClass::TableRow, _) | (_, FlowClass::Table) | (_, FlowClass::TableColGroup) | (_, FlowClass::TableRowGroup) | (_, FlowClass::TableRow) | (_, FlowClass::TableCaption) | (_, FlowClass::TableCell) => { false } (FlowClass::Flex, FlowClass::Inline) => { FlowRef::deref_mut(child).mut_base().flags.insert(FlowFlags::MARGINS_CANNOT_COLLAPSE); let mut block_wrapper = Legalizer::create_anonymous_flow::<E, _>( context, parent, &[PseudoElement::ServoAnonymousBlock], SpecificFragmentInfo::Generic, BlockFlow::from_fragment, ); { let flag = if parent.as_flex().main_mode() == Direction::Inline { FragmentFlags::IS_INLINE_FLEX_ITEM } else { FragmentFlags::IS_BLOCK_FLEX_ITEM }; let block = FlowRef::deref_mut(&mut block_wrapper).as_mut_block(); block.base.flags.insert(FlowFlags::MARGINS_CANNOT_COLLAPSE); block.fragment.flags.insert(flag); } block_wrapper.add_new_child((*child).clone()); block_wrapper.finish(); parent.add_new_child(block_wrapper); true } (FlowClass::Flex, _) => { { let flag = if parent.as_flex().main_mode() == Direction::Inline { FragmentFlags::IS_INLINE_FLEX_ITEM } else { FragmentFlags::IS_BLOCK_FLEX_ITEM }; let block = FlowRef::deref_mut(child).as_mut_block(); block.base.flags.insert(FlowFlags::MARGINS_CANNOT_COLLAPSE); block.fragment.flags.insert(flag); } parent.add_new_child((*child).clone()); true } _ => { parent.add_new_child((*child).clone()); true } } } /// Finalizes the flow on the top of the stack. fn flush_top_of_stack(&mut self, parent: &mut FlowRef) { let mut child = self.stack.pop().expect("flush_top_of_stack(): stack empty"); child.finish(); self.stack.last_mut().unwrap_or(parent).add_new_child(child) } /// Adds the anonymous flow that would be necessary to make an illegal child of `parent` legal /// to the stack. fn push_next_anonymous_flow<E>( &mut self, context: &SharedStyleContext, parent: &FlowRef, ) where E: TElement, { let parent_class = self.stack.last().unwrap_or(parent).class(); match parent_class { FlowClass::TableRow => { self.push_new_anonymous_flow::<E, _>( context, parent, &[PseudoElement::ServoAnonymousTableCell], SpecificFragmentInfo::TableCell, TableCellFlow::from_fragment, ) } FlowClass::Table | FlowClass::TableRowGroup => { self.push_new_anonymous_flow::<E, _>( context, parent, &[PseudoElement::ServoAnonymousTableRow], SpecificFragmentInfo::TableRow, TableRowFlow::from_fragment, ) } FlowClass::TableWrapper => { self.push_new_anonymous_flow::<E, _>( context, parent, &[PseudoElement::ServoAnonymousTable], SpecificFragmentInfo::Table, TableFlow::from_fragment, ) } _ => { self.push_new_anonymous_flow::<E, _>( context, parent, &[PseudoElement::ServoTableWrapper, PseudoElement::ServoAnonymousTableWrapper], SpecificFragmentInfo::TableWrapper, TableWrapperFlow::from_fragment, ) } } } /// Creates an anonymous flow and pushes it onto the stack. fn push_new_anonymous_flow<E, F>( &mut self, context: &SharedStyleContext, reference: &FlowRef, pseudos: &[PseudoElement], specific_fragment_info: SpecificFragmentInfo, constructor: extern "Rust" fn(Fragment) -> F, ) where E: TElement, F: Flow, { let new_flow = Self::create_anonymous_flow::<E, _>( context, reference, pseudos, specific_fragment_info, constructor, ); self.stack.push(new_flow) } /// Creates a new anonymous flow. The new flow is identical to `reference` except with all /// styles applying to every pseudo-element in `pseudos` applied. /// /// This method invokes the supplied constructor function on the given specific fragment info /// in order to actually generate the flow. fn create_anonymous_flow<E, F>( context: &SharedStyleContext, reference: &FlowRef, pseudos: &[PseudoElement], specific_fragment_info: SpecificFragmentInfo, constructor: extern "Rust" fn(Fragment) -> F, ) -> FlowRef where E: TElement, F: Flow, { let reference_block = reference.as_block(); let mut new_style = reference_block.fragment.style.clone(); for pseudo in pseudos { new_style = context.stylist.style_for_anonymous::<E>( &context.guards, pseudo, &new_style, ); } let fragment = reference_block.fragment.create_similar_anonymous_fragment( new_style, specific_fragment_info, ); FlowRef::new(Arc::new(constructor(fragment))) } }<|fim▁end|>
if kid.get_pseudo_element_type() != PseudoElementType::Normal { self.process(&kid);
<|file_name|>bitcoin_es_MX.ts<|end_file_name|><|fim▁begin|><TS language="es_MX" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Click derecho para editar tu dirección o etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una dirección nueva</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Nuevo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copiar</translation> </message> <message> <source>C&amp;lose</source> <translation>Cerrar</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Eliminar la dirección actualmente seleccionada de la lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar la información en la tabla actual a un archivo</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Borrar</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Dialogo de contraseña</translation> </message> <message> <source>Enter passphrase</source> <translation>Ingrese la contraseña</translation> </message> <message> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Máscara de red</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Firmar &amp;mensaje</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronizando con la red...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vista previa</translation> </message> <message> <source>Node</source> <translation>Nodo</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostrar la vista previa general de la cartera</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <source>Browse transaction history</source> <translation>Explorar el historial de transacciones</translation> </message> <message> <source>E&amp;xit</source> <translation>S&amp;alir</translation> </message> <message> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Mostrar información acerca de Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opciones</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Encriptar cartera</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Respaldar cartera</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar contraseña...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>Direcciones de &amp;envío...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Direcciones de &amp;recepción...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Abrir &amp;URL...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindexando bloques en el disco...</translation> </message> <message> <source>Send coins to a Litecoin address</source> <translation>Enviar monedas a una dirección Litecoin</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Respaldar cartera en otra ubicación</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña usada para la encriptación de la cartera</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Depurar ventana</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de depuración y diagnostico</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaje...</translation> </message> <message> <source>Litecoin</source> <translation>Litecoin</translation> </message> <message> <source>Wallet</source> <translation>Cartera</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Recibir</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Mostrar / Ocultar</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Configuraciones</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ayuda</translation> </message> <message> <source>Tabs toolbar</source> <translation>Pestañas</translation> </message> <message> <source>&amp;Command-line options</source> <translation>opciones de la &amp;Linea de comandos</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message> <source>Warning</source> <translation>Aviso</translation> </message> <message> <source>Information</source> <translation>Información </translation> </message> <message> <source>Up to date</source> <translation>Actualizado al dia </translation> </message> <message> <source>Catching up...</source> <translation>Recibiendo...</translation> </message> <message> <source>Sent transaction</source> <translation>Enviar Transacción</translation> </message> <message> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;desbloqueada&lt;/b&gt; actualmente </translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>La cartera esta &lt;b&gt;encriptada&lt;/b&gt; y &lt;b&gt;bloqueada&lt;/b&gt; actualmente </translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>Cantidad</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Monto:</translation> </message><|fim▁hole|> <translation>Cuota:</translation> </message> <message> <source>After Fee:</source> <translation>Después de los cargos por comisión. </translation> </message> <message> <source>Change:</source> <translation>Cambio</translation> </message> <message> <source>Amount</source> <translation>Monto</translation> </message> <message> <source>Date</source> <translation>Fecha</translation> </message> <message> <source>Confirmed</source> <translation>Confirmado </translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Editar dirección</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>name</source> <translation>nombre</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>versión</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>Command-line options</source> <translation>opciones de la Linea de comandos</translation> </message> <message> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <source>command-line options</source> <translation>Opciones de comando de lineas</translation> </message> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>Error</translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Formulario</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opciones</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Activar las opciones de linea de comando que sobre escriben las siguientes opciones:</translation> </message> <message> <source>W&amp;allet</source> <translation>Cartera</translation> </message> <message> <source>none</source> <translation>Ninguno </translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulario</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Monto</translation> </message> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>Debug window</source> <translation>Depurar ventana</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>Monto:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>&amp;Message:</source> <translation>Mensaje:</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Litecoin network.</source> <translation>Mensaje opcional para agregar a la solicitud de pago, el cual será mostrado cuando la solicitud este abierta. Nota: El mensaje no se manda con el pago a travéz de la red de Litecoin.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Use este formulario para la solicitud de pagos. Todos los campos son &lt;b&gt;opcionales&lt;/b&gt;</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Monto opcional a solicitar. Dejarlo vacion o en cero no solicita un monto especifico.</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Copy &amp;Address</source> <translation>&amp;Copiar dirección</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Enviar monedas</translation> </message> <message> <source>Quantity:</source> <translation>Cantidad</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Monto:</translation> </message> <message> <source>Fee:</source> <translation>Cuota:</translation> </message> <message> <source>After Fee:</source> <translation>Después de los cargos por comisión. </translation> </message> <message> <source>Change:</source> <translation>Cambio</translation> </message> <message> <source>fast</source> <translation>rápido</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples receptores a la vez</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirme la acción de enviar</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>M&amp;onto</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Pagar &amp;a:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiqueta</translation> </message> <message> <source>This is a normal payment.</source> <translation>Este es un pago normal</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Quitar esta entrada</translation> </message> <message> <source>Message:</source> <translation>Mensaje:</translation> </message> <message> <source>Pay To:</source> <translation>Pago para:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>No apague su computadora hasta que esta ventana desaparesca.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Pegar dirección del portapapeles</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Signature</source> <translation>Firma</translation> </message> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Este panel muestras una descripción detallada de la transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Enviar monedas</translation> </message> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Opciones:</translation> </message> <message> <source>Litecoin Core</source> <translation>nucleo Litecoin</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;categoria&gt; puede ser:</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verificando bloques...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verificando cartera...</translation> </message> <message> <source>Wallet options:</source> <translation>Opciones de cartera:</translation> </message> <message> <source>Information</source> <translation>Información </translation> </message> <message> <source>Warning</source> <translation>Aviso</translation> </message> <message> <source>Loading addresses...</source> <translation>Cargando direcciones...</translation> </message> <message> <source>Loading block index...</source> <translation>Cargando indice de bloques... </translation> </message> <message> <source>Loading wallet...</source> <translation>Cargando billetera...</translation> </message> <message> <source>Done loading</source> <translation>Carga completa</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> </context> </TS><|fim▁end|>
<message> <source>Fee:</source>
<|file_name|>float.rs<|end_file_name|><|fim▁begin|>//! Implements vertical floating-point math operations. #[macro_use] mod abs; #[macro_use] mod cos; #[macro_use] mod exp; #[macro_use] mod powf; #[macro_use] mod ln; <|fim▁hole|> #[macro_use] mod mul_adde; #[macro_use] mod recpre; #[macro_use] mod rsqrte; #[macro_use] mod sin; #[macro_use] mod sqrt; #[macro_use] mod sqrte;<|fim▁end|>
#[macro_use] mod mul_add;
<|file_name|>toolbar-controller.js<|end_file_name|><|fim▁begin|>/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; angular.module('flowableModeler') .controller('ToolbarController', ['$scope', '$http', '$modal', '$q', '$rootScope', '$translate', '$location', 'editorManager', function ($scope, $http, $modal, $q, $rootScope, $translate, $location, editorManager) { $scope.editorFactory.promise.then(function () { var toolbarItems = FLOWABLE.TOOLBAR_CONFIG.items; $scope.items = []; for (var i = 0; i < toolbarItems.length; i++) { if ($rootScope.modelData.model.modelType === 'form') { if (!toolbarItems[i].disableInForm) { $scope.items.push(toolbarItems[i]); } } else { $scope.items.push(toolbarItems[i]); } } }); $scope.secondaryItems = FLOWABLE.TOOLBAR_CONFIG.secondaryItems; // Call configurable click handler (From http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) var executeFunctionByName = function(functionName, context /*, args */) { var args = Array.prototype.slice.call(arguments).splice(2); var namespaces = functionName.split("."); var func = namespaces.pop(); for(var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } return context[func].apply(this, args); }; // Click handler for toolbar buttons $scope.toolbarButtonClicked = function(buttonIndex) { // Default behaviour var buttonClicked = $scope.items[buttonIndex]; var services = { '$scope' : $scope, '$rootScope' : $rootScope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, 'editorManager' : editorManager}; executeFunctionByName(buttonClicked.action, window, services); // Other events var event = { type : FLOWABLE.eventBus.EVENT_TYPE_TOOLBAR_BUTTON_CLICKED, toolbarItem : buttonClicked }; FLOWABLE.eventBus.dispatch(event.type, event); }; // Click handler for secondary toolbar buttons $scope.toolbarSecondaryButtonClicked = function(buttonIndex) { var buttonClicked = $scope.secondaryItems[buttonIndex]; var services = { '$scope' : $scope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, '$location': $location, 'editorManager' : editorManager}; executeFunctionByName(buttonClicked.action, window, services); }; /* Key bindings */ Mousetrap.bind('mod+z', function(e) { var services = { '$scope' : $scope, '$rootScope' : $rootScope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, 'editorManager' : editorManager}; FLOWABLE.TOOLBAR.ACTIONS.undo(services); return false; }); Mousetrap.bind('mod+y', function(e) {<|fim▁hole|> }); Mousetrap.bind('mod+c', function(e) { var services = { '$scope' : $scope, '$rootScope' : $rootScope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, 'editorManager' : editorManager}; FLOWABLE.TOOLBAR.ACTIONS.copy(services); return false; }); Mousetrap.bind('mod+v', function(e) { var services = { '$scope' : $scope, '$rootScope' : $rootScope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, 'editorManager' : editorManager}; FLOWABLE.TOOLBAR.ACTIONS.paste(services); return false; }); Mousetrap.bind(['del'], function(e) { var services = { '$scope' : $scope, '$rootScope' : $rootScope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, 'editorManager' : editorManager}; FLOWABLE.TOOLBAR.ACTIONS.deleteItem(services); return false; }); /* Undo logic */ $scope.undoStack = []; $scope.redoStack = []; FLOWABLE.eventBus.addListener(FLOWABLE.eventBus.EVENT_TYPE_UNDO_REDO_RESET,function($scope){ this.undoStack = []; this.redoStack = []; if (this.items) { for(var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item.action === 'FLOWABLE.TOOLBAR.ACTIONS.undo' || item.action === "FLOWABLE.TOOLBAR.ACTIONS.redo"){ item.enabled = false; } } } },$scope); $scope.editorFactory.promise.then(function() { // Catch all command that are executed and store them on the respective stacks editorManager.registerOnEvent(ORYX.CONFIG.EVENT_EXECUTE_COMMANDS, function( evt ){ // If the event has commands if( !evt.commands ){ return; } $scope.undoStack.push( evt.commands ); $scope.redoStack = []; for(var i = 0; i < $scope.items.length; i++) { var item = $scope.items[i]; if (item.action === 'FLOWABLE.TOOLBAR.ACTIONS.undo') { item.enabled = true; } else if (item.action === 'FLOWABLE.TOOLBAR.ACTIONS.redo') { item.enabled = false; } } // Update editorManager.getCanvas().update(); editorManager.updateSelection(); }); }); // Handle enable/disable toolbar buttons $scope.editorFactory.promise.then(function() { editorManager.registerOnEvent(ORYX.CONFIG.EVENT_SELECTION_CHANGED, function( evt ){ var elements = evt.elements; for(var i = 0; i < $scope.items.length; i++) { var item = $scope.items[i]; if (item.enabledAction && item.enabledAction === 'element') { var minLength = 1; if (item.minSelectionCount) { minLength = item.minSelectionCount; } if (elements.length >= minLength && !item.enabled) { $scope.safeApply(function () { item.enabled = true; }); } else if (elements.length == 0 && item.enabled) { $scope.safeApply(function () { item.enabled = false; }); } } } }); }); }]);<|fim▁end|>
var services = { '$scope' : $scope, '$rootScope' : $rootScope, '$http' : $http, '$modal' : $modal, '$q' : $q, '$translate' : $translate, 'editorManager' : editorManager}; FLOWABLE.TOOLBAR.ACTIONS.redo(services); return false;
<|file_name|>methods.py<|end_file_name|><|fim▁begin|>import json from math import ceil from asyncpg import Connection from qllr.common import MATCH_LIST_ITEM_COUNT from qllr.db import cache from qllr.settings import PLAYER_COUNT_PER_PAGE<|fim▁hole|> KEEPING_TIME = 60 * 60 * 24 * 30 SQL_TOP_PLAYERS_BY_GAMETYPE = """ SELECT p.steam_id, p.name, p.model, gr.rating, gr.deviation, gr.n, count(*) OVER () AS count, ROW_NUMBER() OVER (ORDER BY gr.rating DESC) AS rank FROM players p LEFT JOIN (SUBQUERY) gr ON gr.steam_id = p.steam_id WHERE gr.n >= 10 AND gr.last_played_timestamp > LEAST( $1, ( SELECT timestamp FROM matches WHERE gametype_id = $2 ORDER BY timestamp DESC LIMIT 1 OFFSET {OFFSET} )) AND gr.gametype_id = $2 ORDER BY gr.rating DESC """.format( OFFSET=int(MATCH_LIST_ITEM_COUNT) ).replace( "(SUBQUERY)", "({SUBQUERY})" ) SQL_TOP_PLAYERS_BY_GAMETYPE_R1 = SQL_TOP_PLAYERS_BY_GAMETYPE.format( SUBQUERY=""" SELECT steam_id, r1_mean AS rating, r1_deviation AS deviation, last_played_timestamp, gametype_id, n FROM gametype_ratings """ ) SQL_TOP_PLAYERS_BY_GAMETYPE_R2 = SQL_TOP_PLAYERS_BY_GAMETYPE.format( SUBQUERY=""" SELECT steam_id, r2_value AS rating, 0 AS deviation, last_played_timestamp, gametype_id, n FROM gametype_ratings """ ) def get_sql_top_players_query_by_gametype_id(gametype_id: int): if cache.USE_AVG_PERF[gametype_id]: return SQL_TOP_PLAYERS_BY_GAMETYPE_R2 else: return SQL_TOP_PLAYERS_BY_GAMETYPE_R1 async def get_list(con: Connection, gametype_id: int, page: int, show_inactive=False): await con.set_type_codec( "json", encoder=json.dumps, decoder=json.loads, schema="pg_catalog" ) query = get_sql_top_players_query_by_gametype_id( gametype_id ) + "LIMIT {LIMIT} OFFSET {OFFSET}".format( LIMIT=int(PLAYER_COUNT_PER_PAGE), OFFSET=int(PLAYER_COUNT_PER_PAGE * page) ) start_timestamp = 0 if show_inactive is False: start_timestamp = cache.LAST_GAME_TIMESTAMPS[gametype_id] - KEEPING_TIME result = [] player_count = 0 async for row in con.cursor(query, start_timestamp, gametype_id): if row[0] != None: result.append( { "_id": str(row[0]), "name": row[1], "model": ( row[2] + ("/default" if row[2].find("/") == -1 else "") ).lower(), "rating": round(row[3], 2), "rd": round(row[4], 2), "n": row[5], "rank": row[7], } ) player_count = row[6] steam_ids = list(map(lambda player: int(player["_id"]), result)) query = """ SELECT s.steam_id, CEIL(AVG(CASE WHEN m.team1_score > m.team2_score AND s.team = 1 THEN 1 WHEN m.team2_score > m.team1_score AND s.team = 2 THEN 1 ELSE 0 END)*100) FROM matches m LEFT JOIN scoreboards s ON s.match_id = m.match_id WHERE m.gametype_id = $1 AND s.steam_id = ANY($2) GROUP BY s.steam_id; """ for row in await con.fetch(query, gametype_id, steam_ids): try: result_index = steam_ids.index(row[0]) result[result_index]["win_ratio"] = int(row[1]) except ValueError: pass # must not happen return { "ok": True, "response": result, "page_count": ceil(player_count / PLAYER_COUNT_PER_PAGE), }<|fim▁end|>
<|file_name|>nth.rs<|end_file_name|><|fim▁begin|>/* 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 std::ascii::AsciiExt; use super::{Token, Parser, ParserInput, BasicParseError}; /// Parse the *An+B* notation, as found in the `:nth-child()` selector. /// The input is typically the arguments of a function, /// in which case the caller needs to check if the arguments’ parser is exhausted. /// Return `Ok((A, B))`, or `Err(())` for a syntax error. pub fn parse_nth<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(i32, i32), BasicParseError<'i>> { // FIXME: remove .clone() when lifetimes are non-lexical. match input.next()?.clone() { Token::Number { int_value: Some(b), .. } => { Ok((0, b)) } Token::Dimension { int_value: Some(a), unit, .. } => { match_ignore_ascii_case! { &unit, "n" => Ok(try!(parse_b(input, a))), "n-" => Ok(try!(parse_signless_b(input, a, -1))), _ => match parse_n_dash_digits(&*unit) { Ok(b) => Ok((a, b)), Err(()) => Err(input.new_basic_unexpected_token_error(Token::Ident(unit.clone()))) } } } Token::Ident(value) => { match_ignore_ascii_case! { &value, "even" => Ok((2, 0)), "odd" => Ok((2, 1)), "n" => Ok(try!(parse_b(input, 1))), "-n" => Ok(try!(parse_b(input, -1))), "n-" => Ok(try!(parse_signless_b(input, 1, -1))), "-n-" => Ok(try!(parse_signless_b(input, -1, -1))), _ => { let (slice, a) = if value.starts_with("-") { (&value[1..], -1) } else { (&*value, 1) }; match parse_n_dash_digits(slice) { Ok(b) => Ok((a, b)), Err(()) => Err(input.new_basic_unexpected_token_error(Token::Ident(value.clone()))) } } } } // FIXME: remove .clone() when lifetimes are non-lexical. Token::Delim('+') => match input.next_including_whitespace()?.clone() { Token::Ident(value) => { match_ignore_ascii_case! { &value,<|fim▁hole|> Err(()) => Err(input.new_basic_unexpected_token_error(Token::Ident(value.clone()))) } } } token => Err(input.new_basic_unexpected_token_error(token)), }, token => Err(input.new_basic_unexpected_token_error(token)), } } fn parse_b<'i, 't>(input: &mut Parser<'i, 't>, a: i32) -> Result<(i32, i32), BasicParseError<'i>> { let start = input.state(); match input.next() { Ok(&Token::Delim('+')) => parse_signless_b(input, a, 1), Ok(&Token::Delim('-')) => parse_signless_b(input, a, -1), Ok(&Token::Number { has_sign: true, int_value: Some(b), .. }) => Ok((a, b)), _ => { input.reset(&start); Ok((a, 0)) } } } fn parse_signless_b<'i, 't>(input: &mut Parser<'i, 't>, a: i32, b_sign: i32) -> Result<(i32, i32), BasicParseError<'i>> { // FIXME: remove .clone() when lifetimes are non-lexical. match input.next()?.clone() { Token::Number { has_sign: false, int_value: Some(b), .. } => Ok((a, b_sign * b)), token => Err(input.new_basic_unexpected_token_error(token)) } } fn parse_n_dash_digits(string: &str) -> Result<i32, ()> { let bytes = string.as_bytes(); if bytes.len() >= 3 && bytes[..2].eq_ignore_ascii_case(b"n-") && bytes[2..].iter().all(|&c| matches!(c, b'0'...b'9')) { Ok(parse_number_saturate(&string[1..]).unwrap()) // Include the minus sign } else { Err(()) } } fn parse_number_saturate(string: &str) -> Result<i32, ()> { let mut input = ParserInput::new(string); let mut parser = Parser::new(&mut input); let int = if let Ok(&Token::Number {int_value: Some(int), ..}) = parser.next_including_whitespace_and_comments() { int } else { return Err(()) }; if !parser.is_exhausted() { return Err(()) } Ok(int) }<|fim▁end|>
"n" => parse_b(input, 1), "n-" => parse_signless_b(input, 1, -1), _ => match parse_n_dash_digits(&*value) { Ok(b) => Ok((1, b)),
<|file_name|>state.py<|end_file_name|><|fim▁begin|># SPDX-License-Identifier: GPL-2.0+ # Copyright 2018 Google, Inc # Written by Simon Glass <[email protected]> # # Holds and modifies the state information held by binman # import hashlib import re from dtoc import fdt import os from patman import tools from patman import tout # Records the device-tree files known to binman, keyed by entry type (e.g. # 'u-boot-spl-dtb'). These are the output FDT files, which can be updated by # binman. They have been copied to <xxx>.out files. # # key: entry type # value: tuple: # Fdt object # Filename # Entry object, or None if not known output_fdt_info = {} # Prefix to add to an fdtmap path to turn it into a path to the /binman node fdt_path_prefix = '' # Arguments passed to binman to provide arguments to entries entry_args = {} # True to use fake device-tree files for testing (see U_BOOT_DTB_DATA in # ftest.py) use_fake_dtb = False # The DTB which contains the full image information main_dtb = None # Allow entries to expand after they have been packed. This is detected and # forces a re-pack. If not allowed, any attempted expansion causes an error in # Entry.ProcessContentsUpdate() allow_entry_expansion = True # Don't allow entries to contract after they have been packed. Instead just # leave some wasted space. If allowed, this is detected and forces a re-pack, # but may result in entries that oscillate in size, thus causing a pack error. # An example is a compressed device tree where the original offset values # result in a larger compressed size than the new ones, but then after updating # to the new ones, the compressed size increases, etc. allow_entry_contraction = False def GetFdtForEtype(etype): """Get the Fdt object for a particular device-tree entry Binman keeps track of at least one device-tree file called u-boot.dtb but can also have others (e.g. for SPL). This function looks up the given entry and returns the associated Fdt object. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Fdt object associated with the entry type """ value = output_fdt_info.get(etype); if not value: return None return value[0] def GetFdtPath(etype): """Get the full pathname of a particular Fdt object Similar to GetFdtForEtype() but returns the pathname associated with the Fdt. Args: etype: Entry type of device tree (e.g. 'u-boot-dtb') Returns: Full path name to the associated Fdt """ return output_fdt_info[etype][0]._fname def GetFdtContents(etype='u-boot-dtb'): """Looks up the FDT pathname and contents This is used to obtain the Fdt pathname and contents when needed by an entry. It supports a 'fake' dtb, allowing tests to substitute test data for the real dtb. Args: etype: Entry type to look up (e.g. 'u-boot.dtb'). Returns: tuple: pathname to Fdt Fdt data (as bytes) """ if etype not in output_fdt_info: return None, None if not use_fake_dtb: pathname = GetFdtPath(etype) data = GetFdtForEtype(etype).GetContents() else: fname = output_fdt_info[etype][1] pathname = tools.GetInputFilename(fname) data = tools.ReadFile(pathname) return pathname, data def UpdateFdtContents(etype, data): """Update the contents of a particular device tree The device tree is updated and written back to its file. This affects what is returned from future called to GetFdtContents(), etc. Args: etype: Entry type (e.g. 'u-boot-dtb') data: Data to replace the DTB with """ dtb, fname, entry = output_fdt_info[etype] dtb_fname = dtb.GetFilename() tools.WriteFile(dtb_fname, data) dtb = fdt.FdtScan(dtb_fname) output_fdt_info[etype] = [dtb, fname, entry] def SetEntryArgs(args): """Set the value of the entry args This sets up the entry_args dict which is used to supply entry arguments to entries. Args: args: List of entry arguments, each in the format "name=value" """ global entry_args entry_args = {} if args: for arg in args: m = re.match('([^=]*)=(.*)', arg) if not m: raise ValueError("Invalid entry arguemnt '%s'" % arg) entry_args[m.group(1)] = m.group(2) def GetEntryArg(name): """Get the value of an entry argument Args: name: Name of argument to retrieve Returns: String value of argument """ return entry_args.get(name) def Prepare(images, dtb): """Get device tree files ready for use This sets up a set of device tree files that can be retrieved by GetAllFdts(). This includes U-Boot proper and any SPL device trees. Args: images: List of images being used dtb: Main dtb """ global output_fdt_info, main_dtb, fdt_path_prefix # Import these here in case libfdt.py is not available, in which case # the above help option still works. from dtoc import fdt from dtoc import fdt_util # If we are updating the DTBs we need to put these updated versions # where Entry_blob_dtb can find them. We can ignore 'u-boot.dtb' # since it is assumed to be the one passed in with options.dt, and # was handled just above. main_dtb = dtb output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['u-boot-dtb'] = [dtb, 'u-boot.dtb', None] output_fdt_info['u-boot-spl-dtb'] = [dtb, 'spl/u-boot-spl.dtb', None] output_fdt_info['u-boot-tpl-dtb'] = [dtb, 'tpl/u-boot-tpl.dtb', None] if not use_fake_dtb: fdt_set = {} for image in images.values(): fdt_set.update(image.GetFdts()) for etype, other in fdt_set.items(): entry, other_fname = other infile = tools.GetInputFilename(other_fname) other_fname_dtb = fdt_util.EnsureCompiled(infile) out_fname = tools.GetOutputFilename('%s.out' % os.path.split(other_fname)[1]) tools.WriteFile(out_fname, tools.ReadFile(other_fname_dtb)) other_dtb = fdt.FdtScan(out_fname) output_fdt_info[etype] = [other_dtb, out_fname, entry] def PrepareFromLoadedData(image): """Get device tree files ready for use with a loaded image Loaded images are different from images that are being created by binman, since there is generally already an fdtmap and we read the description from that. This provides the position and size of every entry in the image with no calculation required. This function uses the same output_fdt_info[] as Prepare(). It finds the device tree files, adds a reference to the fdtmap and sets the FDT path prefix to translate from the fdtmap (where the root node is the image node) to the normal device tree (where the image node is under a /binman node). Args: images: List of images being used """ global output_fdt_info, main_dtb, fdt_path_prefix tout.Info('Preparing device trees') output_fdt_info.clear() fdt_path_prefix = '' output_fdt_info['fdtmap'] = [image.fdtmap_dtb, 'u-boot.dtb', None] main_dtb = None tout.Info(" Found device tree type 'fdtmap' '%s'" % image.fdtmap_dtb.name) for etype, value in image.GetFdts().items(): entry, fname = value out_fname = tools.GetOutputFilename('%s.dtb' % entry.etype) tout.Info(" Found device tree type '%s' at '%s' path '%s'" % (etype, out_fname, entry.GetPath())) entry._filename = entry.GetDefaultFilename() data = entry.ReadData() tools.WriteFile(out_fname, data) dtb = fdt.Fdt(out_fname) dtb.Scan() image_node = dtb.GetNode('/binman') if 'multiple-images' in image_node.props: image_node = dtb.GetNode('/binman/%s' % image.image_node) fdt_path_prefix = image_node.path output_fdt_info[etype] = [dtb, None, entry] tout.Info(" FDT path prefix '%s'" % fdt_path_prefix) def GetAllFdts(): """Yield all device tree files being used by binman Yields: Device trees being used (U-Boot proper, SPL, TPL) """ if main_dtb: yield main_dtb for etype in output_fdt_info: dtb = output_fdt_info[etype][0]<|fim▁hole|> def GetUpdateNodes(node, for_repack=False): """Yield all the nodes that need to be updated in all device trees The property referenced by this node is added to any device trees which have the given node. Due to removable of unwanted notes, SPL and TPL may not have this node. Args: node: Node object in the main device tree to look up for_repack: True if we want only nodes which need 'repack' properties added to them (e.g. 'orig-offset'), False to return all nodes. We don't add repack properties to SPL/TPL device trees. Yields: Node objects in each device tree that is in use (U-Boot proper, which is node, SPL and TPL) """ yield node for dtb, fname, entry in output_fdt_info.values(): if dtb != node.GetFdt(): if for_repack and entry.etype != 'u-boot-dtb': continue other_node = dtb.GetNode(fdt_path_prefix + node.path) #print(' try', fdt_path_prefix + node.path, other_node) if other_node: yield other_node def AddZeroProp(node, prop, for_repack=False): """Add a new property to affected device trees with an integer value of 0. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): n.AddZeroProp(prop) def AddSubnode(node, name): """Add a new subnode to a node in affected device trees Args: node: Node to add to name: name of node to add Returns: New subnode that was created in main tree """ first = None for n in GetUpdateNodes(node): subnode = n.AddSubnode(name) if not first: first = subnode return first def AddString(node, prop, value): """Add a new string property to affected device trees Args: prop_name: Name of property value: String value (which will be \0-terminated in the DT) """ for n in GetUpdateNodes(node): n.AddString(prop, value) def SetInt(node, prop, value, for_repack=False): """Update an integer property in affected device trees with an integer value This is not allowed to change the size of the FDT. Args: prop_name: Name of property for_repack: True is this property is only needed for repacking """ for n in GetUpdateNodes(node, for_repack): tout.Detail("File %s: Update node '%s' prop '%s' to %#x" % (n.GetFdt().name, n.path, prop, value)) n.SetInt(prop, value) def CheckAddHashProp(node): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo') if not algo: return "Missing 'algo' property for hash node" if algo.value == 'sha256': size = 32 else: return "Unknown hash algorithm '%s'" % algo for n in GetUpdateNodes(hash_node): n.AddEmptyProp('value', size) def CheckSetHashValue(node, get_data_func): hash_node = node.FindNode('hash') if hash_node: algo = hash_node.props.get('algo').value if algo == 'sha256': m = hashlib.sha256() m.update(get_data_func()) data = m.digest() for n in GetUpdateNodes(hash_node): n.SetData('value', data) def SetAllowEntryExpansion(allow): """Set whether post-pack expansion of entries is allowed Args: allow: True to allow expansion, False to raise an exception """ global allow_entry_expansion allow_entry_expansion = allow def AllowEntryExpansion(): """Check whether post-pack expansion of entries is allowed Returns: True if expansion should be allowed, False if an exception should be raised """ return allow_entry_expansion def SetAllowEntryContraction(allow): """Set whether post-pack contraction of entries is allowed Args: allow: True to allow contraction, False to raise an exception """ global allow_entry_contraction allow_entry_contraction = allow def AllowEntryContraction(): """Check whether post-pack contraction of entries is allowed Returns: True if contraction should be allowed, False if an exception should be raised """ return allow_entry_contraction<|fim▁end|>
if dtb != main_dtb: yield dtb
<|file_name|>views.py<|end_file_name|><|fim▁begin|># Copyright 2013, Big Switch Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tabs from horizon.utils import memoized from horizon import workflows from openstack_dashboard import api from openstack_dashboard.dashboards.project.firewalls \ import forms as fw_forms from openstack_dashboard.dashboards.project.firewalls \ import tabs as fw_tabs from openstack_dashboard.dashboards.project.firewalls \ import workflows as fw_workflows AddRouterToFirewall = fw_forms.AddRouterToFirewall InsertRuleToPolicy = fw_forms.InsertRuleToPolicy RemoveRouterFromFirewall = fw_forms.RemoveRouterFromFirewall RemoveRuleFromPolicy = fw_forms.RemoveRuleFromPolicy UpdateFirewall = fw_forms.UpdateFirewall UpdatePolicy = fw_forms.UpdatePolicy UpdateRule = fw_forms.UpdateRule FirewallDetailsTabs = fw_tabs.FirewallDetailsTabs FirewallTabs = fw_tabs.FirewallTabs PolicyDetailsTabs = fw_tabs.PolicyDetailsTabs RuleDetailsTabs = fw_tabs.RuleDetailsTabs AddFirewall = fw_workflows.AddFirewall AddPolicy = fw_workflows.AddPolicy AddRule = fw_workflows.AddRule class IndexView(tabs.TabView): tab_group_class = (FirewallTabs) template_name = 'project/firewalls/details_tabs.html' page_title = _("Firewalls") def post(self, request, *args, **kwargs): obj_ids = request.POST.getlist('object_ids') action = request.POST['action'] obj_type = re.search('.delete([a-z]+)', action).group(1) if not obj_ids: obj_ids.append(re.search('([0-9a-z-]+)$', action).group(1)) if obj_type == 'rule': for obj_id in obj_ids: try: api.fwaas.rule_delete(request, obj_id) messages.success(request, _('Deleted rule %s') % obj_id) except Exception as e: exceptions.handle(request, _('Unable to delete rule. %s') % e) if obj_type == 'policy': for obj_id in obj_ids: try: api.fwaas.policy_delete(request, obj_id) messages.success(request, _('Deleted policy %s') % obj_id) except Exception as e: exceptions.handle(request, _('Unable to delete policy. %s') % e) if obj_type == 'firewall': for obj_id in obj_ids: try: api.fwaas.firewall_delete(request, obj_id) messages.success(request, _('Deleted firewall %s') % obj_id) except Exception as e: exceptions.handle(request, _('Unable to delete firewall. %s') % e) return self.get(request, *args, **kwargs) class AddRuleView(workflows.WorkflowView): workflow_class = AddRule template_name = "project/firewalls/addrule.html" page_title = _("Add New Rule") class AddPolicyView(workflows.WorkflowView): workflow_class = AddPolicy template_name = "project/firewalls/addpolicy.html" page_title = _("Add New Policy") class AddFirewallView(workflows.WorkflowView): workflow_class = AddFirewall template_name = "project/firewalls/addfirewall.html" page_title = _("Add New Firewall") def get_workflow(self): if api.neutron.is_extension_supported(self.request, 'fwaasrouterinsertion'): AddFirewall.register(fw_workflows.SelectRoutersStep) workflow = super(AddFirewallView, self).get_workflow() return workflow class FireWallDetailTabs(tabs.TabView): template_name = 'project/firewalls/details_tabs.html' class RuleDetailsView(FireWallDetailTabs): tab_group_class = (RuleDetailsTabs) page_title = _("Firewall Rule Details") class PolicyDetailsView(FireWallDetailTabs): tab_group_class = (PolicyDetailsTabs) page_title = _("Firewall Policy Details") class FirewallDetailsView(FireWallDetailTabs): tab_group_class = (FirewallDetailsTabs) page_title = _("Firewall Details") class UpdateRuleView(forms.ModalFormView): form_class = UpdateRule form_id = "update_rule_form" template_name = "project/firewalls/updaterule.html" context_object_name = 'rule' modal_header = _("Edit Rule") submit_label = _("Save Changes") submit_url = "horizon:project:firewalls:updaterule" success_url = reverse_lazy("horizon:project:firewalls:index") page_title = _("Edit Rule {{ name }}") def get_context_data(self, **kwargs): context = super(UpdateRuleView, self).get_context_data(**kwargs) context['rule_id'] = self.kwargs['rule_id'] args = (self.kwargs['rule_id'],) context['submit_url'] = reverse(self.submit_url, args=args) obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): rule_id = self.kwargs['rule_id'] try: rule = api.fwaas.rule_get(self.request, rule_id) return rule except Exception: redirect = self.success_url msg = _('Unable to retrieve rule details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): rule = self._get_object() initial = rule.get_dict() protocol = initial['protocol'] initial['protocol'] = protocol.upper() if protocol else 'ANY' initial['action'] = initial['action'].upper() return initial class UpdatePolicyView(forms.ModalFormView): form_class = UpdatePolicy form_id = "update_policy_form" template_name = "project/firewalls/updatepolicy.html" context_object_name = 'policy' modal_header = _("Edit Policy") submit_label = _("Save Changes") submit_url = "horizon:project:firewalls:updatepolicy" success_url = reverse_lazy("horizon:project:firewalls:index") page_title = _("Edit Policy {{ name }}") def get_context_data(self, **kwargs): context = super(UpdatePolicyView, self).get_context_data(**kwargs) context["policy_id"] = self.kwargs['policy_id'] args = (self.kwargs['policy_id'],) context['submit_url'] = reverse(self.submit_url, args=args) obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): policy_id = self.kwargs['policy_id'] try: policy = api.fwaas.policy_get(self.request, policy_id)<|fim▁hole|> exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): policy = self._get_object() initial = policy.get_dict() return initial class UpdateFirewallView(forms.ModalFormView): form_class = UpdateFirewall form_id = "update_firewall_form" template_name = "project/firewalls/updatefirewall.html" context_object_name = 'firewall' modal_header = _("Edit Firewall") submit_label = _("Save Changes") submit_url = "horizon:project:firewalls:updatefirewall" success_url = reverse_lazy("horizon:project:firewalls:index") page_title = _("Edit Firewall {{ name }}") def get_context_data(self, **kwargs): context = super(UpdateFirewallView, self).get_context_data(**kwargs) context["firewall_id"] = self.kwargs['firewall_id'] args = (self.kwargs['firewall_id'],) context['submit_url'] = reverse(self.submit_url, args=args) obj = self._get_object() if obj: context['name'] = obj.name return context @memoized.memoized_method def _get_object(self, *args, **kwargs): firewall_id = self.kwargs['firewall_id'] try: firewall = api.fwaas.firewall_get(self.request, firewall_id) return firewall except Exception: redirect = self.success_url msg = _('Unable to retrieve firewall details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): firewall = self._get_object() initial = firewall.get_dict() return initial class InsertRuleToPolicyView(forms.ModalFormView): form_class = InsertRuleToPolicy form_id = "update_policy_form" modal_header = _("Insert Rule into Policy") template_name = "project/firewalls/insert_rule_to_policy.html" context_object_name = 'policy' submit_url = "horizon:project:firewalls:insertrule" submit_label = _("Save Changes") success_url = reverse_lazy("horizon:project:firewalls:index") page_title = _("Insert Rule to Policy") def get_context_data(self, **kwargs): context = super(InsertRuleToPolicyView, self).get_context_data(**kwargs) context["policy_id"] = self.kwargs['policy_id'] args = (self.kwargs['policy_id'],) context['submit_url'] = reverse(self.submit_url, args=args) obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): policy_id = self.kwargs['policy_id'] try: policy = api.fwaas.policy_get(self.request, policy_id) return policy except Exception: redirect = self.success_url msg = _('Unable to retrieve policy details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): policy = self._get_object() initial = policy.get_dict() initial['policy_id'] = initial['id'] return initial class RemoveRuleFromPolicyView(forms.ModalFormView): form_class = RemoveRuleFromPolicy form_id = "update_policy_form" modal_header = _("Remove Rule from Policy") template_name = "project/firewalls/remove_rule_from_policy.html" context_object_name = 'policy' submit_label = _("Save Changes") submit_url = "horizon:project:firewalls:removerule" success_url = reverse_lazy("horizon:project:firewalls:index") page_title = _("Remove Rule from Policy") def get_context_data(self, **kwargs): context = super(RemoveRuleFromPolicyView, self).get_context_data(**kwargs) context["policy_id"] = self.kwargs['policy_id'] args = (self.kwargs['policy_id'],) context['submit_url'] = reverse(self.submit_url, args=args) obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): policy_id = self.kwargs['policy_id'] try: policy = api.fwaas.policy_get(self.request, policy_id) return policy except Exception: redirect = self.success_url msg = _('Unable to retrieve policy details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): policy = self._get_object() initial = policy.get_dict() initial['policy_id'] = initial['id'] return initial class RouterCommonView(forms.ModalFormView): form_id = "update_firewall_form" context_object_name = 'firewall' submit_label = _("Save Changes") success_url = reverse_lazy("horizon:project:firewalls:index") def get_context_data(self, **kwargs): context = super(RouterCommonView, self).get_context_data(**kwargs) context["firewall_id"] = self.kwargs['firewall_id'] args = (self.kwargs['firewall_id'],) context['submit_url'] = reverse(self.submit_url, args=args) obj = self._get_object() if obj: context['name'] = obj.name_or_id return context @memoized.memoized_method def _get_object(self, *args, **kwargs): firewall_id = self.kwargs['firewall_id'] try: firewall = api.fwaas.firewall_get(self.request, firewall_id) return firewall except Exception: redirect = self.success_url msg = _('Unable to retrieve firewall details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): firewall = self._get_object() initial = firewall.get_dict() return initial class AddRouterToFirewallView(RouterCommonView): form_class = AddRouterToFirewall modal_header = _("Add Router to Firewall") template_name = "project/firewalls/add_router_to_firewall.html" submit_url = "horizon:project:firewalls:addrouter" page_title = _("Add Router to Firewall") class RemoveRouterFromFirewallView(RouterCommonView): form_class = RemoveRouterFromFirewall modal_header = _("Remove Router from Firewall") template_name = "project/firewalls/remove_router_from_firewall.html" submit_url = "horizon:project:firewalls:removerouter" page_title = _("Remove Router from Firewall")<|fim▁end|>
return policy except Exception: redirect = self.success_url msg = _('Unable to retrieve policy details.')
<|file_name|>rooms.py<|end_file_name|><|fim▁begin|>from classes import * sign = Object('sign', 'To the left is a sign.', 'The sign says: Den of Evil') opening = Room('opening', 'You are standing in front of a cave.', {}, {'sign' : sign}) #sign.set_room(opening) opening_w = Room('opening_w', 'You are standing in front of an impassable jungle. There is nothing here you can do.') opening_w.add_room('east', opening) opening.add_room('west', opening_w) opening_e = Room('opening_e', 'You are standing in front of an impassable jungle. There is nothing here you can do.') opening_e.add_room('west', opening) opening.add_room('east', opening_e) lamp = Item('Lamp', 'On the ground is an old and rusty oil lamp.', False) shed = Room('shed', 'In the dim light from outside you can see a small and dirty room.', {'lamp':lamp}, {}, {}, 'The broken door blocks the entrance') door=Object('door','The door barely hangs in its place', None, 'The door explodes under your force.', None, shed) opening_s = Room('opening_s', 'There is a small shed at west side of the road. A path leads back to the north.', {}, {'door':door}) #door.set_room(opening_s) opening_s.add_room('north', opening) opening_s.add_room('west', shed) opening.add_room('south', opening_s) shed.add_room('east',opening_s) thief = Entity('thief','A filthy looking thief stands at the wall.') cave_entrance = Room('cave_entrance', 'You are entering a long tunnel going north, that is dimly lit by the light of your lamp.', {}, {}, {'thief':thief}, 'It is to dark to see anything.') cave_entrance.add_room('south', opening) opening.add_room('north', cave_entrance) rooms = { 'opening' : opening, 'opening_w' : opening_w,<|fim▁hole|> 'opening_s' : opening_s, 'cave_entrance' : cave_entrance, 'shed' : shed }<|fim▁end|>
'opening_e' : opening_e,
<|file_name|>DataReaderWriterProvider.java<|end_file_name|><|fim▁begin|>/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.io; import jetbrains.exodus.core.dataStructures.Pair; import jetbrains.exodus.env.Environment; import jetbrains.exodus.env.EnvironmentConfig; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ServiceLoader; /** * Service provider interface for creation instances of {@linkplain DataReader} and {@linkplain DataWriter}. * {@linkplain DataReader} and {@linkplain DataWriter} are used by {@code Log} implementation to perform basic * operations with {@linkplain Block blocks} ({@code .xd} files) and basic read/write/delete operations. * * Service provider interface is identified by a fully-qualified name of its implementation. When opening an * {@linkplain Environment}, {@linkplain #DEFAULT_READER_WRITER_PROVIDER} is used as default provide name. To use a * custom I/O provider, specify its fully-qualified name as a parameter of {@linkplain EnvironmentConfig#setLogDataReaderWriterProvider}. * * On {@linkplain Environment} creation new instance of {@code DataReaderWriterProvider} is created. * * @see Block * @see DataReader * @see DataWriter * @see EnvironmentConfig#getLogDataReaderWriterProvider * @see EnvironmentConfig#setLogDataReaderWriterProvider * @since 1.3.0 */ public abstract class DataReaderWriterProvider { /** * Fully-qualified name of default {@code DataReaderWriteProvider}. */ public static final String DEFAULT_READER_WRITER_PROVIDER = "jetbrains.exodus.io.FileDataReaderWriterProvider"; /** * Fully-qualified name of read-only watching {@code DataReaderWriteProvider}. */<|fim▁hole|> public static final String WATCHING_READER_WRITER_PROVIDER = "jetbrains.exodus.io.WatchingFileDataReaderWriterProvider"; /** * Fully-qualified name of in-memory {@code DataReaderWriteProvider}. */ public static final String IN_MEMORY_READER_WRITER_PROVIDER = "jetbrains.exodus.io.MemoryDataReaderWriterProvider"; /** * Creates pair of new instances of {@linkplain DataReader} and {@linkplain DataWriter} by specified location. * What is location depends on the implementation of {@code DataReaderWriterProvider}, e.g. for {@code FileDataReaderWriterProvider} * location is a full path on local file system where the database is located. * * @param location identifies the database in this {@code DataReaderWriterProvider} * @return pair of new instances of {@linkplain DataReader} and {@linkplain DataWriter} */ public abstract Pair<DataReader, DataWriter> newReaderWriter(@NotNull final String location); /** * Returns {@code true} if the {@code DataReaderWriterProvider} creates in-memory {@linkplain DataReader} and {@linkplain DataWriter}. * * @return {@code true} if the {@code DataReaderWriterProvider} creates in-memory {@linkplain DataReader} and {@linkplain DataWriter} */ public boolean isInMemory() { return false; } /** * Returns {@code true} if the {@code DataReaderWriterProvider} creates read-only {@linkplain DataWriter}. * * @return {@code true} if the {@code DataReaderWriterProvider} creates read-only {@linkplain DataWriter} */ public boolean isReadonly() { return false; } /** * Callback method which is called when an environment is been opened/created. Can be used in implementation of * the {@code DataReaderWriterProvider} to access directly an {@linkplain Environment} instance, * its {@linkplain Environment#getEnvironmentConfig() config}, etc. Creation of {@code environment} is not * completed when the method is called. * * @param environment {@linkplain Environment} instance which is been opened/created using this * {@code DataReaderWriterProvider} */ public void onEnvironmentCreated(@NotNull final Environment environment) { } /** * Gets a {@code DataReaderWriterProvider} implementation by specified provider name. * * @param providerName fully-qualified name of {@code DataReaderWriterProvider} implementation * @return {@code DataReaderWriterProvider} implementation or {@code null} if the service could not be loaded */ @Nullable public static DataReaderWriterProvider getProvider(@NotNull final String providerName) { ServiceLoader<DataReaderWriterProvider> serviceLoader = ServiceLoader.load(DataReaderWriterProvider.class); if (!serviceLoader.iterator().hasNext()) { serviceLoader = ServiceLoader.load(DataReaderWriterProvider.class, DataReaderWriterProvider.class.getClassLoader()); } for (DataReaderWriterProvider provider : serviceLoader) { if (provider.getClass().getCanonicalName().equalsIgnoreCase(providerName)) { return provider; } } return null; } }<|fim▁end|>
<|file_name|>BezierCurveEditor.js<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, nomen: true, regexp: true, maxerr: 50 */ /*global define, brackets, $, window */ define(function (require, exports, module) { "use strict"; var KeyEvent = brackets.getModule("utils/KeyEvent"), Strings = brackets.getModule("strings"), Mustache = brackets.getModule("thirdparty/mustache/mustache"); var TimingFunctionUtils = require("TimingFunctionUtils"); /** Mustache template that forms the bare DOM structure of the UI */ var BezierCurveEditorTemplate = require("text!BezierCurveEditorTemplate.html"); /** @const @type {number} */ var HEIGHT_ABOVE = 75, // extra height above main grid HEIGHT_BELOW = 75, // extra height below main grid HEIGHT_MAIN = 150, // height of main grid WIDTH_MAIN = 150; // width of main grid var animationRequest = null; /** * CubicBezier object constructor * * @param {string|Array.number[4]} coordinates Four parameters passes to cubic-bezier() * either in string or array format. */ function CubicBezier(coordinates) { if (typeof coordinates === "string") { this.coordinates = coordinates.split(","); } else { this.coordinates = coordinates; } if (!this.coordinates) { throw "No offsets were defined"; } this.coordinates = this.coordinates.map(function (n) { return +n; }); var i; for (i = 3; i >= 0; i--) { var xy = this.coordinates[i]; if (isNaN(xy) || (((i % 2) === 0) && (xy < 0 || xy > 1))) { throw "Wrong coordinate at " + i + "(" + xy + ")"; } } } /** * BezierCanvas object constructor * * @param {Element} canvas Inline editor <canvas> element * @param {CubicBezier} bezier Associated CubicBezier object * @param {number|Array.number} padding Element padding */ function BezierCanvas(canvas, bezier, padding) { this.canvas = canvas; this.bezier = bezier; this.padding = this.getPadding(padding); // Convert to a cartesian coordinate system with axes from 0 to 1 var ctx = this.canvas.getContext("2d"), p = this.padding; ctx.scale(canvas.width * (1 - p[1] - p[3]), -canvas.height * 0.5 * (1 - p[0] - p[2])); ctx.translate(p[3] / (1 - p[1] - p[3]), (-1 - p[0] / (1 - p[0] - p[2])) - 0.5); } BezierCanvas.prototype = { /** * Calculates CSS offsets for <canvas> element * * @return {left:string, top:string} */ getOffsets: function () { var p = this.padding, w = this.canvas.width, h = this.canvas.height * 0.5; return [{ left: w * (this.bezier.coordinates[0] * (1 - p[3] - p[1]) - p[3]) + "px", top: h * (1 - this.bezier.coordinates[1] * (1 - p[0] - p[2]) - p[0]) + "px" }, { left: w * (this.bezier.coordinates[2] * (1 - p[3] - p[1]) - p[3]) + "px", top: h * (1 - this.bezier.coordinates[3] * (1 - p[0] - p[2]) - p[0]) + "px" }]; }, /** * Round off number to hundreths place, convert to string, and strip leading zero * * @param {number} v Value * @return {string} */ prettify: function (v) { return (Math.round(v * 100) / 100).toString().replace(/^0\./, "."); }, /** * Get CSS left, top offsets for endpoint handle * * @param {Element} element Endpoint handle <button> element * @return {Array.string[2]} */ offsetsToCoordinates: function (element) { var p = this.padding, w = this.canvas.width, h = this.canvas.height * 0.5; // Convert padding percentage to actual padding p = p.map(function (a, i) { return a * ((i % 2) ? w : h); }); return [ this.prettify((parseInt($(element).css("left"), 10) - p[3]) / (w + p[1] + p[3])), this.prettify((h - parseInt($(element).css("top"), 10) - p[2]) / (h - p[0] - p[2])) ]; }, /**<|fim▁hole|> * @param {Object} settings Paint settings */ plot: function (settings) { var xy = this.bezier.coordinates, ctx = this.canvas.getContext("2d"), setting; var defaultSettings = { handleTimingFunction: "#2893ef", handleThickness: 0.008, vBorderThickness: 0.02, hBorderThickness: 0.01, bezierTimingFunction: "#2893ef", bezierThickness: 0.03 }; settings = settings || {}; for (setting in defaultSettings) { if (defaultSettings.hasOwnProperty(setting)) { if (!settings.hasOwnProperty(setting)) { settings[setting] = defaultSettings[setting]; } } } ctx.clearRect(-0.5, -0.5, 2, 2); // Draw control handles ctx.beginPath(); ctx.fillStyle = settings.handleTimingFunction; ctx.lineWidth = settings.handleThickness; ctx.strokeStyle = settings.handleTimingFunction; ctx.moveTo(0, 0); ctx.lineTo(xy[0], xy[1]); ctx.moveTo(1, 1); ctx.lineTo(xy[2], xy[3]); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.arc(xy[0], xy[1], 1.5 * settings.handleThickness, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.arc(xy[2], xy[3], 1.5 * settings.handleThickness, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fill(); // Draw bezier curve ctx.beginPath(); ctx.lineWidth = settings.bezierThickness; ctx.strokeStyle = settings.bezierColor; ctx.moveTo(0, 0); ctx.bezierCurveTo(xy[0], xy[1], xy[2], xy[3], 1, 1); ctx.stroke(); ctx.closePath(); }, /** * Convert CSS padding shorthand to longhand * * @param {number|Array.number} padding Element padding * @return {Array.number} */ getPadding: function (padding) { var p = (typeof padding === "number") ? [padding] : padding; if (p.length === 1) { p[1] = p[0]; } if (p.length === 2) { p[2] = p[0]; } if (p.length === 3) { p[3] = p[1]; } return p; } }; // Event handlers /** * Handle click in <canvas> element * * @param {Event} e Mouse click event */ function _curveClick(e) { var self = e.target, bezierEditor = self.bezierEditor; var curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE, $P1 = $(bezierEditor.P1), $P2 = $(bezierEditor.P2); // Helper function to calculate distance between 2-D points function distance(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } // Find which point is closer var distP1 = distance(x, y, parseInt($P1.css("left"), 10), parseInt($P1.css("top"), 10)), distP2 = distance(x, y, parseInt($P2.css("left"), 10), parseInt($P2.css("top"), 10)), $P = (distP1 < distP2) ? $P1 : $P2; $P.css({ left: x + "px", top: y + "px" }); $P.get(0).focus(); // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); } /** * Helper function for handling point move * * @param {Event} e Mouse move event * @param {number} x New horizontal position * @param {number} y New vertical position */ function handlePointMove(e, x, y) { var self = e.target, bezierEditor = self.bezierEditor; // Helper function to redraw curve function mouseMoveRedraw() { if (!bezierEditor.dragElement) { animationRequest = null; return; } // Update code bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); animationRequest = window.requestAnimationFrame(mouseMoveRedraw); } // This is a dragging state, but left button is no longer down, so mouse // exited element, was released, and re-entered element. Treat like a drop. if (bezierEditor.dragElement && (e.which !== 1)) { bezierEditor.dragElement = null; bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); bezierEditor = null; return; } // Constrain time (x-axis) to 0 to 1 range. Progression (y-axis) is // theoretically not constrained, although canvas to drawing curve is // arbitrarily constrained to -0.5 to 1.5 range. x = Math.min(Math.max(0, x), WIDTH_MAIN); if (bezierEditor.dragElement) { $(bezierEditor.dragElement).css({ left: x + "px", top: y + "px" }); } // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); if (!animationRequest) { animationRequest = window.requestAnimationFrame(mouseMoveRedraw); } } /** * Update Time (x-axis) and Progression (y-axis) data for mouse position * * @param {Element} canvas <canvas> element * @param {number} x Horizontal position * @param {number} y Vertical position */ function updateTimeProgression(curve, x, y) { var percentX = Math.round(100 * x / WIDTH_MAIN), percentY = Math.round(100 * ((HEIGHT_MAIN - y) / HEIGHT_MAIN)); // Constrain horizontal percentage to [0, 100] range percentX = Math.min(Math.max(0, percentX), 100); curve.parentNode.setAttribute("data-time", percentX); curve.parentNode.setAttribute("data-progression", percentY); } /** * Handle mouse move in <canvas> element * * @param {Event} e Mouse move event */ function _curveMouseMove(e) { var self = e.target, bezierEditor = self.bezierEditor, curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE; updateTimeProgression(self, x, y); if (bezierEditor.dragElement) { if (e.pageX === 0 && e.pageY === 0) { return; } handlePointMove(e, x, y); } } /** * Handle mouse move in <button> element * * @param {Event} e Mouse move event */ function _pointMouseMove(e) { var self = e.target, bezierEditor = self.bezierEditor, curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE; updateTimeProgression(bezierEditor.curve, x, y); if (e.pageX === 0 && e.pageY === 0) { return; } handlePointMove(e, x, y); } /** * Handle mouse down in <button> element * * @param {Event} e Mouse down event */ function _pointMouseDown(e) { var self = e.target; self.bezierEditor.dragElement = self; } /** * Handle mouse up in <button> element * * @param {Event} e Mouse up event */ function _pointMouseUp(e) { var self = e.target; self.focus(); if (self.bezierEditor.dragElement) { self.bezierEditor.dragElement = null; self.bezierEditor._commitTimingFunction(); self.bezierEditor._updateCanvas(); } } /** * Handle key down in <button> element * * @param {Event} e Key down event */ function _pointKeyDown(e) { var code = e.keyCode, self = e.target, bezierEditor = self.bezierEditor; if (code >= KeyEvent.DOM_VK_LEFT && code <= KeyEvent.DOM_VK_DOWN) { e.preventDefault(); // Arrow keys pressed var $this = $(e.target), left = parseInt($this.css("left"), 10), top = parseInt($this.css("top"), 10), offset = (e.shiftKey ? 15 : 3), newVal; switch (code) { case KeyEvent.DOM_VK_LEFT: newVal = Math.max(0, left - offset); if (left === newVal) { return false; } $this.css({ left: newVal + "px" }); break; case KeyEvent.DOM_VK_UP: newVal = Math.max(-HEIGHT_ABOVE, top - offset); if (top === newVal) { return false; } $this.css({ top: newVal + "px" }); break; case KeyEvent.DOM_VK_RIGHT: newVal = Math.min(WIDTH_MAIN, left + offset); if (left === newVal) { return false; } $this.css({ left: newVal + "px" }); break; case KeyEvent.DOM_VK_DOWN: newVal = Math.min(HEIGHT_MAIN + HEIGHT_BELOW, top + offset); if (top === newVal) { return false; } $this.css({ top: newVal + "px" }); break; } // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); return true; } else if (code === KeyEvent.DOM_VK_ESCAPE) { return true; } else if (code === KeyEvent.DOM_VK_TAB && !e.ctrlKey && !e.metaKey && !e.altKey) { // Switch between the two points by tabbing if ($(e.target).hasClass("P1")) { $(".P2").focus(); } else { $(".P1").focus(); } e.preventDefault(); return true; } return false; } /** * Constructor for BezierCurveEditor Object. This control may be used standalone * or within an InlineTimingFunctionEditor inline widget. * * @param {!jQuery} $parent DOM node into which to append the root of the bezier curve editor UI * @param {!RegExpMatch} bezierCurve RegExp match object of initially selected bezierCurve * @param {!function(string)} callback Called whenever selected bezierCurve changes */ function BezierCurveEditor($parent, bezierCurve, callback) { // Create the DOM structure, filling in localized strings via Mustache this.$element = $(Mustache.render(BezierCurveEditorTemplate, Strings)); $parent.append(this.$element); this._callback = callback; this.dragElement = null; // current cubic-bezier() function params this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve); this.hint = {}; this.hint.elem = $(".hint", this.$element); // If function was auto-corrected, then originalString holds the original function, // and an informational message needs to be shown if (bezierCurve.originalString) { TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")"); } else { TimingFunctionUtils.showHideHint(this.hint, false); } this.P1 = this.$element.find(".P1")[0]; this.P2 = this.$element.find(".P2")[0]; this.curve = this.$element.find(".curve")[0]; this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = this; this.bezierCanvas = new BezierCanvas(this.curve, null, [0, 0]); // redraw canvas this._updateCanvas(); $(this.curve) .on("click", _curveClick) .on("mousemove", _curveMouseMove); $(this.P1) .on("mousemove", _pointMouseMove) .on("mousedown", _pointMouseDown) .on("mouseup", _pointMouseUp) .on("keydown", _pointKeyDown); $(this.P2) .on("mousemove", _pointMouseMove) .on("mousedown", _pointMouseDown) .on("mouseup", _pointMouseUp) .on("keydown", _pointKeyDown); } /** * Destructor called by InlineTimingFunctionEditor.onClosed() */ BezierCurveEditor.prototype.destroy = function () { this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = null; $(this.curve) .off("click", _curveClick) .off("mousemove", _curveMouseMove); $(this.P1) .off("mousemove", _pointMouseMove) .off("mousedown", _pointMouseDown) .off("mouseup", _pointMouseUp) .off("keydown", _pointKeyDown); $(this.P2) .off("mousemove", _pointMouseMove) .off("mousedown", _pointMouseDown) .off("mouseup", _pointMouseUp) .off("keydown", _pointKeyDown); }; /** Returns the root DOM node of the BezierCurveEditor UI */ BezierCurveEditor.prototype.getRootElement = function () { return this.$element; }; /** * Default focus needs to go somewhere, so give it to P1 */ BezierCurveEditor.prototype.focus = function () { this.P1.focus(); return true; }; /** * Generates cubic-bezier function based on coords, and updates the doc */ BezierCurveEditor.prototype._commitTimingFunction = function () { var bezierCurveVal = "cubic-bezier(" + this._cubicBezierCoords[0] + ", " + this._cubicBezierCoords[1] + ", " + this._cubicBezierCoords[2] + ", " + this._cubicBezierCoords[3] + ")"; this._callback(bezierCurveVal); TimingFunctionUtils.showHideHint(this.hint, false); }; /** * Handle all matches returned from TimingFunctionUtils.cubicBezierMatch() and * return array of coords * * @param {RegExp.match} match Matches returned from cubicBezierMatch() * @return {Array.number[4]} */ BezierCurveEditor.prototype._getCubicBezierCoords = function (match) { if (match[0].match(/^cubic-bezier/)) { // cubic-bezier() return match.slice(1, 5); } else { // handle special cases of cubic-bezier calls switch (match[0]) { case "linear": return [ "0", "0", "1", "1" ]; case "ease": return [ ".25", ".1", ".25", "1" ]; case "ease-in": return [ ".42", "0", "1", "1" ]; case "ease-out": return [ "0", "0", ".58", "1" ]; case "ease-in-out": return [ ".42", "0", ".58", "1" ]; } } window.console.log("brackets-cubic-bezier: getCubicBezierCoords() passed invalid RegExp match array"); return [ "0", "0", "0", "0" ]; }; /** * Get <canvas> element's bounding box * * @return {left: number, top: number, width: number, height: number} */ BezierCurveEditor.prototype._getCurveBoundingBox = function () { var $canvas = this.$element.find(".curve"), canvasOffset = $canvas.offset(); return { left: canvasOffset.left, top: canvasOffset.top, width: $canvas.width(), height: $canvas.height() }; }; /** * Update <canvas> after a change */ BezierCurveEditor.prototype._updateCanvas = function () { // collect data, build model if (this._cubicBezierCoords) { this.bezierCanvas.bezier = window.bezier = new CubicBezier(this._cubicBezierCoords); var offsets = this.bezierCanvas.getOffsets(); $(this.P1).css({ left: offsets[0].left, top: offsets[0].top }); $(this.P2).css({ left: offsets[1].left, top: offsets[1].top }); this.bezierCanvas.plot(); } }; /** * Handle external update * * @param {!RegExpMatch} bezierCurve RegExp match object of updated bezierCurve */ BezierCurveEditor.prototype.handleExternalUpdate = function (bezierCurve) { this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve); this._updateCanvas(); // If function was auto-corrected, then originalString holds the original function, // and an informational message needs to be shown if (bezierCurve.originalString) { TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")"); } else { TimingFunctionUtils.showHideHint(this.hint, false); } }; exports.BezierCurveEditor = BezierCurveEditor; });<|fim▁end|>
* Paint canvas *
<|file_name|>webframe_test.py<|end_file_name|><|fim▁begin|>import unittest import sys from PySide.QtCore import QObject, SIGNAL, QUrl from PySide.QtWebKit import * from PySide.QtNetwork import QNetworkRequest from helper import adjust_filename, UsesQApplication <|fim▁hole|> class TestWebFrame(UsesQApplication): def load_finished(self, ok): self.assert_(ok) page = self.view.page() self.assert_(page) frame = page.mainFrame() self.assert_(frame) meta = frame.metaData() self.assertEqual(meta['description'], ['PySide Test METADATA.']) self.app.quit() def testMetaData(self): self.view = QWebView() QObject.connect(self.view, SIGNAL('loadFinished(bool)'), self.load_finished) url = QUrl.fromLocalFile(adjust_filename('fox.html', __file__)) self.view.setUrl(url) self.app.exec_() if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>test_string.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import import bokeh.util.string as bus class Test_escape(object): def test_default_quote(self): assert bus.escape("foo'bar") == "foo&#x27;bar" assert bus.escape('foo"bar') == "foo&quot;bar" def test_quote_False(self): assert bus.escape("foo'bar", quote=False) == "foo'bar" assert bus.escape('foo"bar', quote=False) == 'foo"bar' def test_quote_custom(self): assert bus.escape("foo'bar", quote=('"'),) == "foo'bar" assert bus.escape("foo'bar", quote=("'"),) == "foo&#x27;bar" assert bus.escape('foo"bar', quote=("'"),) == 'foo"bar' assert bus.escape('foo"bar', quote=('"'),) == "foo&quot;bar" def test_amp(self): assert bus.escape("foo&bar") == "foo&amp;bar" def test_lt(self): assert bus.escape("foo<bar") == "foo&lt;bar" def test_gt(self): assert bus.escape("foo>bar") == "foo&gt;bar" class Test_format_doctring(object): def test_no_argument(self): doc__ = "hello world" assert bus.format_docstring(doc__) == doc__ doc__ = None assert bus.format_docstring(doc__) == None def test_arguments_unused(self): doc__ = "hello world" assert bus.format_docstring(doc__, 'hello ', not_used='world') == doc__ doc__ = None assert bus.format_docstring(doc__, 'hello ', not_used='world') == None def test_arguments(self): doc__ = "-- {}{as_parameter} --" assert bus.format_docstring(doc__, 'hello ', as_parameter='world') == "-- hello world --" doc__ = None assert bus.format_docstring(doc__, 'hello ', as_parameter='world') == None class Test_indent(object): TEXT = "some text\nto indent\n goes here" def test_default_args(self): assert bus.indent(self.TEXT) == " some text\n to indent\n goes here" def test_with_n(self): assert bus.indent(self.TEXT, n=3) == " some text\n to indent\n goes here" def test_with_ch(self): assert bus.indent(self.TEXT, ch="-") == "--some text\n--to indent\n-- goes here" class Test_nice_join(object): def test_default(self): assert bus.nice_join(["one"]) == "one" assert bus.nice_join(["one", "two"]) == "one or two" assert bus.nice_join(["one", "two", "three"]) == "one, two or three" assert bus.nice_join(["one", "two", "three", "four"]) == "one, two, three or four" def test_string_conjunction(self): assert bus.nice_join(["one"], conjuction="and") == "one" assert bus.nice_join(["one", "two"], conjuction="and") == "one and two" assert bus.nice_join(["one", "two", "three"], conjuction="and") == "one, two and three" assert bus.nice_join(["one", "two", "three", "four"], conjuction="and") == "one, two, three and four" def test_None_conjunction(self): assert bus.nice_join(["one"], conjuction=None) == "one" assert bus.nice_join(["one", "two"], conjuction=None) == "one, two" assert bus.nice_join(["one", "two", "three"], conjuction=None) == "one, two, three"<|fim▁hole|> assert bus.nice_join(["one"], sep='; ') == "one" assert bus.nice_join(["one", "two"], sep='; ') == "one or two" assert bus.nice_join(["one", "two", "three"], sep='; ') == "one; two or three" assert bus.nice_join(["one", "two", "three", "four"], sep="; ") == "one; two; three or four" def test_snakify(): assert bus.snakify("MyClassName") == "my_class_name" assert bus.snakify("My1Class23Name456") == "my1_class23_name456" assert bus.snakify("MySUPERClassName") == "my_super_class_name"<|fim▁end|>
assert bus.nice_join(["one", "two", "three", "four"], conjuction=None) == "one, two, three, four" def test_sep(self):
<|file_name|>es2020IntlAPIs.ts<|end_file_name|><|fim▁begin|>// @target: es2020 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation const count = 26254.39; const date = new Date("2012-05-24"); function log(locale: string) { console.log( `${new Intl.DateTimeFormat(locale).format(date)} ${new Intl.NumberFormat(locale).format(count)}` ); } log("en-US"); // expected output: 5/24/2012 26,254.39 log("de-DE"); // expected output: 24.5.2012 26.254,39 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat const rtf1 = new Intl.RelativeTimeFormat('en', { style: 'narrow' }); console.log(rtf1.format(3, 'quarter')); //expected output: "in 3 qtrs." console.log(rtf1.format(-1, 'day')); //expected output: "1 day ago" const rtf2 = new Intl.RelativeTimeFormat('es', { numeric: 'auto' }); console.log(rtf2.format(2, 'day')); //expected output: "pasado mañana" // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames const regionNamesInEnglish = new Intl.DisplayNames(['en'], { type: 'region' }); const regionNamesInTraditionalChinese = new Intl.DisplayNames(['zh-Hant'], { type: 'region' }); console.log(regionNamesInEnglish.of('US')); // expected output: "United States" console.log(regionNamesInTraditionalChinese.of('US')); // expected output: "美國" const locales1 = ['ban', 'id-u-co-pinyin', 'de-ID'];<|fim▁hole|>console.log(Intl.DisplayNames.supportedLocalesOf(locales1, options1).join(', ')); new Intl.Locale(); // should error new Intl.Locale(new Intl.Locale('en-US'));<|fim▁end|>
const options1 = { localeMatcher: 'lookup' } as const;
<|file_name|>makedep.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # $Id: makedep.py 1054 2008-12-03 00:38:43Z kena $ import sys import notes thenote = sys.argv[1] outfile = sys.argv[2] notes.init_repo(sys.argv[3:]) note = notes.repo.get(thenote) deps = note.get_deps()<|fim▁hole|>f = file(outfile, 'w') for d in deps: print >>f, d f.close()<|fim▁end|>
print "%s.txt(note) -> %s(referenced keys)" % (thenote, outfile)
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/** <|fim▁hole|> */ package com.seikomi.janus.services;<|fim▁end|>
* This package contains the services of the server and the locator. * * @author Nicolas SYMPHORIEN ([email protected]) *
<|file_name|>ColumnsView.java<|end_file_name|><|fim▁begin|>/* * Copyright 2009-2014 PrimeTek. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.<|fim▁hole|> * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.primefaces.adamantium.view.data.datatable; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import org.primefaces.adamantium.domain.Car; import org.primefaces.adamantium.service.CarService; @ManagedBean(name="dtColumnsView") @ViewScoped public class ColumnsView implements Serializable { private final static List<String> VALID_COLUMN_KEYS = Arrays.asList("id", "brand", "year", "color", "price"); private String columnTemplate = "id brand year"; private List<ColumnModel> columns; private List<Car> cars; private List<Car> filteredCars; @ManagedProperty("#{carService}") private CarService service; @PostConstruct public void init() { cars = service.createCars(10); createDynamicColumns(); } public List<Car> getCars() { return cars; } public List<Car> getFilteredCars() { return filteredCars; } public void setFilteredCars(List<Car> filteredCars) { this.filteredCars = filteredCars; } public void setService(CarService service) { this.service = service; } public String getColumnTemplate() { return columnTemplate; } public void setColumnTemplate(String columnTemplate) { this.columnTemplate = columnTemplate; } public List<ColumnModel> getColumns() { return columns; } private void createDynamicColumns() { String[] columnKeys = columnTemplate.split(" "); columns = new ArrayList<ColumnModel>(); for(String columnKey : columnKeys) { String key = columnKey.trim(); if(VALID_COLUMN_KEYS.contains(key)) { columns.add(new ColumnModel(columnKey.toUpperCase(), columnKey)); } } } public void updateColumns() { //reset table state UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":form:cars"); table.setValueExpression("sortBy", null); //update columns createDynamicColumns(); } static public class ColumnModel implements Serializable { private String header; private String property; public ColumnModel(String header, String property) { this.header = header; this.property = property; } public String getHeader() { return header; } public String getProperty() { return property; } } }<|fim▁end|>
* You may obtain a copy of the License at *
<|file_name|>test_authentication.py<|end_file_name|><|fim▁begin|># coding=utf-8 import logging from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase from django.conf import settings from accounts.authentication import PersonaAuthenticationBackend, PERSONA_VERIFY_URL __author__ = 'peter' User = get_user_model() @patch('accounts.authentication.requests.post') class AuthenticateTest(TestCase): def setUp(self): self.backend = PersonaAuthenticationBackend() user = User(email='[email protected]') user.username = 'otheruser' user.save() def test_sends_assertion_to_mozilla_with_domain(self, mock_post): self.backend.authenticate('an assertion') mock_post.assert_called_once_with( PERSONA_VERIFY_URL, data={'assertion': 'an assertion', 'audience': settings.DOMAIN} ) def test_returns_none_if_response_errors(self, mock_post): mock_post.return_value.ok = False mock_post.return_value.json.return_value = {} user = self.backend.authenticate('an assertion') self.assertIsNone(user) def test_returns_none_if_status_not_okay(self, mock_post): mock_post.return_value.json.return_value = {'status': 'not okay!'} user = self.backend.authenticate('an assertion') self.assertIsNone(user) def test_finds_existing_user_with_email(self, mock_post): mock_post.return_value.json.return_value = {'status': 'okay', 'email': '[email protected]'} actual_user = User.objects.create(email='[email protected]') found_user = self.backend.authenticate('an assertion') self.assertEqual(found_user, actual_user) def test_creates_new_user_if_necessary_for_valid_assertion(self, mock_post): mock_post.return_value.json.return_value = {'status': 'okay', 'email': '[email protected]'} found_user = self.backend.authenticate('an assertion') new_user = User.objects.get(email='[email protected]')<|fim▁hole|> def test_logs_non_okay_responses_from_persona(self, mock_post): response_json = { 'status': 'not okay', 'reason': 'eg, audience mismatch' } mock_post.return_value.ok = True mock_post.return_value.json.return_value = response_json logger = logging.getLogger('accounts.authentication') with patch.object(logger, 'warning') as mock_log_warning: self.backend.authenticate('an assertion') mock_log_warning.assert_called_once_with( 'Persona says no. Json was: {}'.format(response_json) ) class GetUserTest(TestCase): def test_gets_user_by_email(self): backend = PersonaAuthenticationBackend() other_user = User(email='[email protected]') other_user.username = 'otheruser' other_user.save() desired_user = User.objects.create(email='[email protected]') found_user = backend.get_user('[email protected]') self.assertEqual(found_user, desired_user) def test_returns_none_if_no_user_with_that_email(self): backend = PersonaAuthenticationBackend() self.assertIsNone(backend.get_user('[email protected]'))<|fim▁end|>
self.assertEqual(found_user, new_user)
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>extern crate dirs; use regex::Regex; use std::fs::File; use std::io::prelude::*; use std::path::Path;<|fim▁hole|>use {Creds, Result}; pub fn get_credentials(conf: String) -> Result<Creds> { let mut path = dirs::home_dir().ok_or("Can't get home dir")?; // Build path to config file path.push(conf); let content = read_config_file(path.as_path())?; let user = extract_info(r"set imap_user=(\w*)", &content)?; let pass = extract_info(r"set imap_pass=(\w*)", &content)?; let host = extract_info(r"set folder=imaps?://(.+):\d+", &content)?; let port = extract_info(r"set folder=imaps?://.+:(\d+)", &content)?; let port = port.parse()?; Ok(Creds { user: user, pass: pass, host: host, port: port, }) } pub fn extract_info(pattern: &str, text: &str) -> Result<String> { let re = Regex::new(pattern)?; let cap = re.captures(text).ok_or("Couldn't match")?; let xtr = cap.get(1).ok_or("No captures")?; Ok(xtr.as_str().to_string()) } fn read_config_file(path: &Path) -> Result<String> { let mut content = String::new(); let mut file = File::open(&path)?; file.read_to_string(&mut content)?; Ok(content) } pub fn get_db_path() -> Result<String> { let mut path = dirs::home_dir().ok_or("Can't get home dir")?; path.push(::DB); let path_str = path.to_str() .ok_or("Can't convert path into string")?; Ok(path_str.to_string()) }<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>"""redblue_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """<|fim▁hole|>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^red/', include('apps.red_app.urls', namespace='red_namespace')), url(r'^blue/', include('apps.blue_app.urls', namespace='blue_namespace')), url(r'^admin/', admin.site.urls), ]<|fim▁end|>
<|file_name|>asset_holder.rs<|end_file_name|><|fim▁begin|>use piston_window::PistonWindow; pub trait AssetHolder<Asset>: Default {<|fim▁hole|><|fim▁end|>
fn load(&mut self, asset_name: &'static str, window: &PistonWindow); fn get(&self, asset_name: &str) -> &Asset; fn get_mut(&mut self, asset_name: &str) -> &mut Asset; }
<|file_name|>venue.rs<|end_file_name|><|fim▁begin|>extern crate wd40; use wd40::venue::HeartbeatRes; use wd40::venue::VenueRes; fn main() { let venue_heartbeat: HeartbeatRes = wd40::venue::heartbeat("TESTEX") .unwrap() .unwrap_or_else(|why| { panic!("deserialization error: {}", why); }); <|fim▁hole|> .unwrap() .unwrap_or_else(|why| { panic!("deserialization error: {}", why); }); println!("venue stocks res: {:?}", venue_stocks); }<|fim▁end|>
println!("venue heartbeat res: {:?}", venue_heartbeat); let venue_stocks: VenueRes = wd40::venue::stocks("TESTEX")
<|file_name|>webglshaderprecisionformat.rs<|end_file_name|><|fim▁begin|>/* 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/. */ #![allow(dead_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding; use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding::WebGLShaderPrecisionFormatMethods; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct WebGLShaderPrecisionFormat { reflector_: Reflector, range_min: i32, range_max: i32, precision: i32, } impl WebGLShaderPrecisionFormat { fn new_inherited(range_min: i32, range_max: i32, precision: i32) -> WebGLShaderPrecisionFormat { WebGLShaderPrecisionFormat { reflector_: Reflector::new(), range_min: range_min, range_max: range_max, precision: precision, } } pub fn new(window: &Window, range_min: i32, range_max: i32, precision: i32) -> DomRoot<WebGLShaderPrecisionFormat> { reflect_dom_object( Box::new(WebGLShaderPrecisionFormat::new_inherited(range_min, range_max, precision)), window, WebGLShaderPrecisionFormatBinding::Wrap) } } impl WebGLShaderPrecisionFormatMethods for WebGLShaderPrecisionFormat { // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1 fn RangeMin(&self) -> i32 { self.range_min } // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1 fn RangeMax(&self) -> i32 {<|fim▁hole|> fn Precision(&self) -> i32 { self.precision } }<|fim▁end|>
self.range_max } // https://www.khronos.org/registry/webgl/specs/1.0/#5.12.1
<|file_name|>desktopshell_pl.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.1"> <context> <name>main</name> <message> <source>System Preferences</source> <translation>Ustawienia systemu</translation> </message> <message> <source>Keywords</source><|fim▁hole|> </message> <message> <source>Personal</source> <translation type="unfinished"/> </message> <message> <source>Hardware</source> <translation type="unfinished"/> </message> <message> <source>System</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<translation type="unfinished"/>
<|file_name|>test_common.py<|end_file_name|><|fim▁begin|># Copyright 2010 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License.<|fim▁hole|> import mock from testtools import matchers import webob import webob.exc from cinder.api import common from cinder import test NS = "{http://docs.openstack.org/compute/api/v1.1}" ATOMNS = "{http://www.w3.org/2005/Atom}" class LimiterTest(test.TestCase): """Unit tests for the `cinder.api.common.limited` method. This method takes in a list of items and, depending on the 'offset' and 'limit' GET params, returns a subset or complete set of the given items. """ def setUp(self): """Run before each test.""" super(LimiterTest, self).setUp() self.tiny = range(1) self.small = range(10) self.medium = range(1000) self.large = range(10000) def test_limiter_offset_zero(self): """Test offset key works with 0.""" req = webob.Request.blank('/?offset=0') self.assertEqual(common.limited(self.tiny, req), self.tiny) self.assertEqual(common.limited(self.small, req), self.small) self.assertEqual(common.limited(self.medium, req), self.medium) self.assertEqual(common.limited(self.large, req), self.large[:1000]) def test_limiter_offset_medium(self): """Test offset key works with a medium sized number.""" req = webob.Request.blank('/?offset=10') self.assertEqual(common.limited(self.tiny, req), []) self.assertEqual(common.limited(self.small, req), self.small[10:]) self.assertEqual(common.limited(self.medium, req), self.medium[10:]) self.assertEqual(common.limited(self.large, req), self.large[10:1010]) def test_limiter_offset_over_max(self): """Test offset key works with a number over 1000 (max_limit).""" req = webob.Request.blank('/?offset=1001') self.assertEqual([], common.limited(self.tiny, req)) self.assertEqual([], common.limited(self.small, req)) self.assertEqual([], common.limited(self.medium, req)) self.assertEqual( common.limited(self.large, req), self.large[1001:2001]) def test_limiter_offset_blank(self): """Test offset key works with a blank offset.""" req = webob.Request.blank('/?offset=') self.assertRaises( webob.exc.HTTPBadRequest, common.limited, self.tiny, req) def test_limiter_offset_bad(self): """Test offset key works with a BAD offset.""" req = webob.Request.blank(u'/?offset=\u0020aa') self.assertRaises( webob.exc.HTTPBadRequest, common.limited, self.tiny, req) def test_limiter_nothing(self): """Test request with no offset or limit.""" req = webob.Request.blank('/') self.assertEqual(common.limited(self.tiny, req), self.tiny) self.assertEqual(common.limited(self.small, req), self.small) self.assertEqual(common.limited(self.medium, req), self.medium) self.assertEqual(common.limited(self.large, req), self.large[:1000]) def test_limiter_limit_zero(self): """Test limit of zero.""" req = webob.Request.blank('/?limit=0') self.assertEqual(common.limited(self.tiny, req), self.tiny) self.assertEqual(common.limited(self.small, req), self.small) self.assertEqual(common.limited(self.medium, req), self.medium) self.assertEqual(common.limited(self.large, req), self.large[:1000]) def test_limiter_limit_bad(self): """Test with a bad limit.""" req = webob.Request.blank(u'/?limit=hello') self.assertRaises( webob.exc.HTTPBadRequest, common.limited, self.tiny, req) def test_limiter_limit_medium(self): """Test limit of 10.""" req = webob.Request.blank('/?limit=10') self.assertEqual(common.limited(self.tiny, req), self.tiny) self.assertEqual(common.limited(self.small, req), self.small) self.assertEqual(common.limited(self.medium, req), self.medium[:10]) self.assertEqual(common.limited(self.large, req), self.large[:10]) def test_limiter_limit_over_max(self): """Test limit of 3000.""" req = webob.Request.blank('/?limit=3000') self.assertEqual(common.limited(self.tiny, req), self.tiny) self.assertEqual(common.limited(self.small, req), self.small) self.assertEqual(common.limited(self.medium, req), self.medium) self.assertEqual(common.limited(self.large, req), self.large[:1000]) def test_limiter_limit_and_offset(self): """Test request with both limit and offset.""" items = range(2000) req = webob.Request.blank('/?offset=1&limit=3') self.assertEqual(common.limited(items, req), items[1:4]) req = webob.Request.blank('/?offset=3&limit=0') self.assertEqual(common.limited(items, req), items[3:1003]) req = webob.Request.blank('/?offset=3&limit=1500') self.assertEqual(common.limited(items, req), items[3:1003]) req = webob.Request.blank('/?offset=3000&limit=10') self.assertEqual(common.limited(items, req), []) def test_limiter_custom_max_limit(self): """Test a max_limit other than 1000.""" items = range(2000) req = webob.Request.blank('/?offset=1&limit=3') self.assertEqual( common.limited(items, req, max_limit=2000), items[1:4]) req = webob.Request.blank('/?offset=3&limit=0') self.assertEqual( common.limited(items, req, max_limit=2000), items[3:]) req = webob.Request.blank('/?offset=3&limit=2500') self.assertEqual( common.limited(items, req, max_limit=2000), items[3:]) req = webob.Request.blank('/?offset=3000&limit=10') self.assertEqual(common.limited(items, req, max_limit=2000), []) def test_limiter_negative_limit(self): """Test a negative limit.""" req = webob.Request.blank('/?limit=-3000') self.assertRaises( webob.exc.HTTPBadRequest, common.limited, self.tiny, req) def test_limiter_negative_offset(self): """Test a negative offset.""" req = webob.Request.blank('/?offset=-30') self.assertRaises( webob.exc.HTTPBadRequest, common.limited, self.tiny, req) class PaginationParamsTest(test.TestCase): """Unit tests for `cinder.api.common.get_pagination_params` method. This method takes in a request object and returns 'marker' and 'limit' GET params. """ def test_nonnumerical_limit(self): """Test nonnumerical limit param.""" req = webob.Request.blank('/?limit=hello') self.assertRaises( webob.exc.HTTPBadRequest, common.get_pagination_params, req) def test_no_params(self): """Test no params.""" req = webob.Request.blank('/') self.assertEqual({}, common.get_pagination_params(req)) def test_valid_marker(self): """Test valid marker param.""" req = webob.Request.blank( '/?marker=263abb28-1de6-412f-b00b-f0ee0c4333c2') self.assertEqual({'marker': '263abb28-1de6-412f-b00b-f0ee0c4333c2'}, common.get_pagination_params(req)) def test_valid_limit(self): """Test valid limit param.""" req = webob.Request.blank('/?limit=10') self.assertEqual({'limit': 10}, common.get_pagination_params(req)) def test_invalid_limit(self): """Test invalid limit param.""" req = webob.Request.blank('/?limit=-2') self.assertRaises( webob.exc.HTTPBadRequest, common.get_pagination_params, req) def test_valid_limit_and_marker(self): """Test valid limit and marker parameters.""" marker = '263abb28-1de6-412f-b00b-f0ee0c4333c2' req = webob.Request.blank('/?limit=20&marker=%s' % marker) self.assertEqual({'marker': marker, 'limit': 20}, common.get_pagination_params(req)) class SortParamUtilsTest(test.TestCase): def test_get_sort_params_defaults(self): """Verifies the default sort key and direction.""" sort_keys, sort_dirs = common.get_sort_params({}) self.assertEqual(['created_at'], sort_keys) self.assertEqual(['desc'], sort_dirs) def test_get_sort_params_override_defaults(self): """Verifies that the defaults can be overriden.""" sort_keys, sort_dirs = common.get_sort_params({}, default_key='key1', default_dir='dir1') self.assertEqual(['key1'], sort_keys) self.assertEqual(['dir1'], sort_dirs) def test_get_sort_params_single_value_sort_param(self): """Verifies a single sort key and direction.""" params = {'sort': 'key1:dir1'} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1'], sort_keys) self.assertEqual(['dir1'], sort_dirs) def test_get_sort_params_single_value_old_params(self): """Verifies a single sort key and direction.""" params = {'sort_key': 'key1', 'sort_dir': 'dir1'} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1'], sort_keys) self.assertEqual(['dir1'], sort_dirs) def test_get_sort_params_single_with_default_sort_param(self): """Verifies a single sort value with a default direction.""" params = {'sort': 'key1'} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1'], sort_keys) # Direction should be defaulted self.assertEqual(['desc'], sort_dirs) def test_get_sort_params_single_with_default_old_params(self): """Verifies a single sort value with a default direction.""" params = {'sort_key': 'key1'} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1'], sort_keys) # Direction should be defaulted self.assertEqual(['desc'], sort_dirs) def test_get_sort_params_multiple_values(self): """Verifies multiple sort parameter values.""" params = {'sort': 'key1:dir1,key2:dir2,key3:dir3'} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1', 'key2', 'key3'], sort_keys) self.assertEqual(['dir1', 'dir2', 'dir3'], sort_dirs) def test_get_sort_params_multiple_not_all_dirs(self): """Verifies multiple sort keys without all directions.""" params = {'sort': 'key1:dir1,key2,key3:dir3'} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1', 'key2', 'key3'], sort_keys) # Second key is missing the direction, should be defaulted self.assertEqual(['dir1', 'desc', 'dir3'], sort_dirs) def test_get_sort_params_multiple_override_default_dir(self): """Verifies multiple sort keys and overriding default direction.""" params = {'sort': 'key1:dir1,key2,key3'} sort_keys, sort_dirs = common.get_sort_params(params, default_dir='foo') self.assertEqual(['key1', 'key2', 'key3'], sort_keys) self.assertEqual(['dir1', 'foo', 'foo'], sort_dirs) def test_get_sort_params_params_modified(self): """Verifies that the input sort parameter are modified.""" params = {'sort': 'key1:dir1,key2:dir2,key3:dir3'} common.get_sort_params(params) self.assertEqual({}, params) params = {'sort_dir': 'key1', 'sort_dir': 'dir1'} common.get_sort_params(params) self.assertEqual({}, params) def test_get_sort_params_random_spaces(self): """Verifies that leading and trailing spaces are removed.""" params = {'sort': ' key1 : dir1,key2: dir2 , key3 '} sort_keys, sort_dirs = common.get_sort_params(params) self.assertEqual(['key1', 'key2', 'key3'], sort_keys) self.assertEqual(['dir1', 'dir2', 'desc'], sort_dirs) def test_get_params_mix_sort_and_old_params(self): """An exception is raised if both types of sorting params are given.""" for params in ({'sort': 'k1', 'sort_key': 'k1'}, {'sort': 'k1', 'sort_dir': 'd1'}, {'sort': 'k1', 'sort_key': 'k1', 'sort_dir': 'd2'}): self.assertRaises(webob.exc.HTTPBadRequest, common.get_sort_params, params) class MiscFunctionsTest(test.TestCase): def test_remove_major_version_from_href(self): fixture = 'http://www.testsite.com/v1/images' expected = 'http://www.testsite.com/images' actual = common.remove_version_from_href(fixture) self.assertEqual(expected, actual) def test_remove_version_from_href(self): fixture = 'http://www.testsite.com/v1.1/images' expected = 'http://www.testsite.com/images' actual = common.remove_version_from_href(fixture) self.assertEqual(expected, actual) def test_remove_version_from_href_2(self): fixture = 'http://www.testsite.com/v1.1/' expected = 'http://www.testsite.com/' actual = common.remove_version_from_href(fixture) self.assertEqual(expected, actual) def test_remove_version_from_href_3(self): fixture = 'http://www.testsite.com/v10.10' expected = 'http://www.testsite.com' actual = common.remove_version_from_href(fixture) self.assertEqual(expected, actual) def test_remove_version_from_href_4(self): fixture = 'http://www.testsite.com/v1.1/images/v10.5' expected = 'http://www.testsite.com/images/v10.5' actual = common.remove_version_from_href(fixture) self.assertEqual(expected, actual) def test_remove_version_from_href_bad_request(self): fixture = 'http://www.testsite.com/1.1/images' self.assertRaises(ValueError, common.remove_version_from_href, fixture) def test_remove_version_from_href_bad_request_2(self): fixture = 'http://www.testsite.com/v/images' self.assertRaises(ValueError, common.remove_version_from_href, fixture) def test_remove_version_from_href_bad_request_3(self): fixture = 'http://www.testsite.com/v1.1images' self.assertRaises(ValueError, common.remove_version_from_href, fixture) class TestCollectionLinks(test.TestCase): """Tests the _get_collection_links method.""" def _validate_next_link(self, href_link_mock, item_count, osapi_max_limit, limit, should_link_exist): req = mock.MagicMock() href_link_mock.return_value = [{"rel": "next", "href": "fake_link"}] self.flags(osapi_max_limit=osapi_max_limit) if limit is None: params = mock.PropertyMock(return_value=dict()) limited_list_size = min(item_count, osapi_max_limit) else: params = mock.PropertyMock(return_value=dict(limit=limit)) limited_list_size = min(item_count, osapi_max_limit, limit) limited_list = [{"uuid": str(i)} for i in range(limited_list_size)] type(req).params = params builder = common.ViewBuilder() results = builder._get_collection_links(req, limited_list, mock.sentinel.coll_key, item_count, "uuid") if should_link_exist: href_link_mock.assert_called_once_with(limited_list, "uuid", req, mock.sentinel.coll_key) self.assertThat(results, matchers.HasLength(1)) else: self.assertFalse(href_link_mock.called) self.assertThat(results, matchers.HasLength(0)) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_equals_osapi_max_no_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 5 limit = None should_link_exist = False self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_equals_osapi_max_greater_than_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 5 limit = 4 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_equals_osapi_max_equals_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 5 limit = 5 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_equals_osapi_max_less_than_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 5 limit = 6 should_link_exist = False self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_less_than_osapi_max_no_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 7 limit = None should_link_exist = False self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_limit_less_than_items_less_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 7 limit = 4 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_limit_equals_items_less_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 7 limit = 5 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_less_than_limit_less_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 7 limit = 6 should_link_exist = False self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_less_than_osapi_max_equals_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 7 limit = 7 should_link_exist = False self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_less_than_osapi_max_less_than_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 7 limit = 8 should_link_exist = False self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_greater_than_osapi_max_no_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 3 limit = None should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_limit_less_than_items_greater_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 3 limit = 2 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_greater_than_osapi_max_equals_limit(self, href_link_mock): item_count = 5 osapi_max_limit = 3 limit = 3 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_greater_than_limit_greater_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 3 limit = 4 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_items_equals_limit_greater_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 3 limit = 5 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) @mock.patch('cinder.api.common.ViewBuilder._generate_next_link') def test_limit_greater_than_items_greater_than_osapi_max(self, href_link_mock): item_count = 5 osapi_max_limit = 3 limit = 6 should_link_exist = True self._validate_next_link(href_link_mock, item_count, osapi_max_limit, limit, should_link_exist) class LinkPrefixTest(test.TestCase): def test_update_link_prefix(self): vb = common.ViewBuilder() result = vb._update_link_prefix("http://192.168.0.243:24/", "http://127.0.0.1/volume") self.assertEqual("http://127.0.0.1/volume", result) result = vb._update_link_prefix("http://foo.x.com/v1", "http://new.prefix.com") self.assertEqual("http://new.prefix.com/v1", result) result = vb._update_link_prefix( "http://foo.x.com/v1", "http://new.prefix.com:20455/new_extra_prefix") self.assertEqual("http://new.prefix.com:20455/new_extra_prefix/v1", result)<|fim▁end|>
""" Test suites for 'common' code used throughout the OpenStack HTTP API. """
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from rest_framework import generics from .models import Proj from .serializers import ProjSerializer # Create your views here. class ProjList(generics.ListCreateAPIView): """be report project list""" queryset = Proj.objects.all() serializer_class = ProjSerializer class ProjDetail(generics.RetrieveUpdateDestroyAPIView): """be report project detail"""<|fim▁hole|> queryset = Proj.objects.all() serializer_class = ProjSerializer<|fim▁end|>
<|file_name|>saveModule.py<|end_file_name|><|fim▁begin|>#pylint: disable=invalid-name from __future__ import (absolute_import, division, print_function) from PyQt4 import QtCore from mantid.simpleapi import * import numpy as n try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s def saveCustom(idx,fname,sep = ' ',logs = [],title = False,error = False): fname+='.dat' print("FILENAME: ", fname) a1=mtd[str(idx.text())] titl='#'+a1.getTitle()+'\n' x1=a1.readX(0) X1=n.zeros((len(x1)-1)) for i in range(0,len(x1)-1): X1[i]=(x1[i]+x1[i+1])/2.0 y1=a1.readY(0) e1=a1.readE(0) f=open(fname,'w') if title: f.write(titl) samp = a1.getRun() for log in logs: prop = samp.getLogData(str(log.text())) headerLine='#'+log.text() + ': ' + str(prop.value) + '\n' print(headerLine) f.write(headerLine) qres=(X1[1]-X1[0])/X1[1] print("Constant dq/q from file: ",qres) for i in range(len(X1)): if error: dq=X1[i]*qres s="%e" % X1[i] +sep+"%e" % y1[i] +sep + "%e" % e1[i] + sep + "%e" % dq +"\n" else: s="%e" % X1[i] +sep+"%e" % y1[i] +sep + "%e" % e1[i]+ "\n" f.write(s) f.close() def saveANSTO(idx,fname): fname+='.txt' print("FILENAME: ", fname) a1=mtd[str(idx.text())] x1=a1.readX(0) X1=n.zeros((len(x1)-1)) for i in range(0,len(x1)-1): X1[i]=(x1[i]+x1[i+1])/2.0 y1=a1.readY(0) e1=a1.readE(0) sep='\t' f=open(fname,'w') qres=(X1[1]-X1[0])/X1[1] print("Constant dq/q from file: ",qres) for i in range(len(X1)): dq=X1[i]*qres s="%e" % X1[i] +sep+"%e" % y1[i] +sep + "%e" % e1[i] + sep + "%e" % dq +"\n" f.write(s) f.close()<|fim▁hole|> fname+='.mft' print("FILENAME: ", fname) a1=mtd[str(idx.text())] x1=a1.readX(0) X1=n.zeros((len(x1)-1)) for i in range(0,len(x1)-1): X1[i]=(x1[i]+x1[i+1])/2.0 y1=a1.readY(0) e1=a1.readE(0) sep='\t' f=open(fname,'w') f.write('MFT\n') f.write('Instrument: '+a1.getInstrument().getName()+'\n') f.write('User-local contact: \n') f.write('Title: \n') samp = a1.getRun() s = 'Subtitle: '+samp.getLogData('run_title').value+'\n' f.write(s) s = 'Start date + time: '+samp.getLogData('run_start').value+'\n' f.write(s) s = 'End date + time: '+samp.getLogData('run_end').value+'\n' f.write(s) for log in logs: prop = samp.getLogData(str(log.text())) headerLine=log.text() + ': ' + str(prop.value) + '\n' print(headerLine) f.write(headerLine) f.write('Number of file format: 2\n') s = 'Number of data points:\t' + str(len(X1))+'\n' f.write(s) f.write('\n') f.write('\tq\trefl\trefl_err\tq_res\n') qres=(X1[1]-X1[0])/X1[1] print("Constant dq/q from file: ",qres) for i in range(len(X1)): dq=X1[i]*qres s="\t%e" % X1[i] +sep+"%e" % y1[i] +sep + "%e" % e1[i] + sep + "%e" % dq +"\n" f.write(s) f.close()<|fim▁end|>
def saveMFT(idx,fname,logs):
<|file_name|>lpi_runescape.cc<|end_file_name|><|fim▁begin|>/* * * Copyright (c) 2011-2016 The University of Waikato, Hamilton, New Zealand. * All rights reserved. * * This file is part of libprotoident. * * This code has been developed by the University of Waikato WAND * research group. For further information please see http://www.wand.net.nz/ * * libprotoident is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * libprotoident is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ #include <string.h> #include "libprotoident.h" #include "proto_manager.h" #include "proto_common.h" /* Protocol is not documented and goes through all sorts of revisions * (mainly to stop hax0rs, no doubt) - so this is mostly based on * observations of traffic to Jagex servers and messing around with the * game myself */ static inline bool match_runescape_req(uint32_t payload, uint32_t len) { if (len == 1 || len == 105) { if (MATCH(payload, 0x00, 0x00, 0x00, 0x00)) return true; } return false; } static inline bool match_runescape_resp(uint32_t payload, uint32_t len) { /* Don't allow empty responses, as the request rule is rather * non-specific */ /* First byte appears to be a packet type * Second bytes is the packet length - 2 * * It appears many types have a fixed size anyway, so no need to * get fancy :) */ if (MATCH(payload, 0x0f, 0x29, 0x00, 0x00)) { if (len == 43) return true; } if (MATCH(payload, 0x0f, 0x2a, 0x00, 0x00)) { if (len == 44) return true; } if (MATCH(payload, 0x0e, 0x00, 0x00, 0x00)) { if (len == 1) return true; } if (MATCH(payload, 0x0f, 0x00, 0x00, 0x00)) { if (len == 1) return true; } return false; <|fim▁hole|> if (match_runescape_req(data->payload[0], data->payload_len[0])) { if (match_runescape_resp(data->payload[1], data->payload_len[1])) { return true; } } if (match_runescape_req(data->payload[1], data->payload_len[1])) { if (match_runescape_resp(data->payload[0], data->payload_len[0])) { return true; } } return false; } static lpi_module_t lpi_runescape = { LPI_PROTO_RUNESCAPE, LPI_CATEGORY_GAMING, "Runescape", 9, match_runescape }; void register_runescape(LPIModuleMap *mod_map) { register_protocol(&lpi_runescape, mod_map); }<|fim▁end|>
} static inline bool match_runescape(lpi_data_t *data, lpi_module_t *mod UNUSED) {
<|file_name|>karma.conf.js<|end_file_name|><|fim▁begin|>/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const argv = require('minimist')(process.argv.slice(2)); const browserifyPersistFs = require('browserify-persist-fs'); const crypto = require('crypto'); const fs = require('fs'); const globby = require('globby'); const {isCiBuild} = require('../common/ci'); const TEST_SERVER_PORT = 8081; const COMMON_CHROME_FLAGS = [ // Dramatically speeds up iframe creation time. '--disable-extensions', // Allows simulating user actions (e.g unmute) which otherwise will be denied. '--autoplay-policy=no-user-gesture-required', ]; if (argv.debug) { COMMON_CHROME_FLAGS.push('--auto-open-devtools-for-tabs'); } // Used by persistent browserify caching to further salt hashes with our // environment state. Eg, when updating a babel-plugin, the environment hash // must change somehow so that the cache busts and the file is retransformed. const createHash = (input) => crypto.createHash('sha1').update(input).digest('hex'); const persistentCache = browserifyPersistFs( '.karma-cache', { deps: createHash(fs.readFileSync('./package-lock.json')), build: globby .sync([ 'build-system/**/*.js', '!build-system/eslint-rules', '!**/test/**', ]) .map((f) => { return createHash(fs.readFileSync(f)); }), }, () => { process.stdout.write('.'); } ); persistentCache.gc( { maxAge: 1000 * 60 * 60 * 24 * 7, }, () => { // swallow errors } ); /** * @param {!Object} config */ module.exports = { frameworks: [ 'fixture', 'browserify', 'mocha', 'sinon-chai', 'chai', 'source-map-support', ], preprocessors: { // `test-bin` is the output directory of the postHTML transformation. './test-bin/test/fixtures/*.html': ['html2js'], './test/**/*.js': ['browserify'], './ads/**/test/test-*.js': ['browserify'], './extensions/**/test/**/*.js': ['browserify'], './testing/**/*.js': ['browserify'], }, html2JsPreprocessor: { // Strip the test-bin/ prefix for the transformer destination so that the // change is transparent for users of the path. stripPrefix: 'test-bin/', }, hostname: 'localhost', browserify: { watch: true, debug: true, fast: true, basedir: __dirname + '/../../', transform: [['babelify', {caller: {name: 'test'}, global: true}]], // Prevent "cannot find module" errors during CI. See #14166. bundleDelay: isCiBuild() ? 5000 : 1200, persistentCache, }, reporters: ['super-dots', 'karmaSimpleReporter'], superDotsReporter: { nbDotsPerLine: 100000, color: { success: 'green', failure: 'red', ignore: 'yellow', }, icon: { success: '●', failure: '●', ignore: '○', }, }, specReporter: { suppressPassed: true, suppressSkipped: true, suppressFailed: false, suppressErrorSummary: true, maxLogLines: 20, }, mochaReporter: { output: 'full', colors: { success: 'green', error: 'red', info: 'yellow', }, symbols: { success: '●', error: '●', info: '○', }, }, port: 9876, colors: true, proxies: { '/ads/': '/base/ads/', '/dist/': '/base/dist/', '/dist.3p/': '/base/dist.3p/', '/examples/': '/base/examples/', '/extensions/': '/base/extensions/', '/src/': '/base/src/', '/test/': '/base/test/', }, // Can't import the Karma constant config.LOG_ERROR, so we hard code it here. // Hopefully it'll never change. logLevel: 'ERROR', autoWatch: true, customLaunchers: { /* eslint "google-camelcase/google-camelcase": 0*/<|fim▁hole|> flags: ['--no-sandbox'].concat(COMMON_CHROME_FLAGS), }, Chrome_no_extensions: { base: 'Chrome', flags: COMMON_CHROME_FLAGS, }, Chrome_no_extensions_headless: { base: 'ChromeHeadless', flags: [ // https://developers.google.com/web/updates/2017/04/headless-chrome#frontend '--no-sandbox', '--remote-debugging-port=9222', // https://github.com/karma-runner/karma-chrome-launcher/issues/175 "--proxy-server='direct://'", '--proxy-bypass-list=*', ].concat(COMMON_CHROME_FLAGS), }, }, client: { mocha: { reporter: 'html', // Longer timeout during CI; fail quickly during local runs. timeout: isCiBuild() ? 10000 : 2000, // Run tests up to 3 times before failing them during CI. retries: isCiBuild() ? 2 : 0, }, captureConsole: false, verboseLogging: false, testServerPort: TEST_SERVER_PORT, }, singleRun: true, captureTimeout: 4 * 60 * 1000, failOnEmptyTestSuite: false, // Give a disconnected browser 2 minutes to reconnect with Karma. // This allows a browser to retry 2 times per `browserDisconnectTolerance` // during CI before stalling out after 10 minutes. browserDisconnectTimeout: 2 * 60 * 1000, // If there's no message from the browser, make Karma wait 2 minutes // until it disconnects. browserNoActivityTimeout: 2 * 60 * 1000, // IF YOU CHANGE THIS, DEBUGGING WILL RANDOMLY KILL THE BROWSER browserDisconnectTolerance: isCiBuild() ? 2 : 0, // Import our gulp webserver as a Karma server middleware // So we instantly have all the custom server endpoints available beforeMiddleware: ['custom'], plugins: [ '@chiragrupani/karma-chromium-edge-launcher', 'karma-browserify', 'karma-chai', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-fixture', 'karma-html2js-preprocessor', 'karma-ie-launcher', 'karma-structured-json-reporter', 'karma-mocha', 'karma-mocha-reporter', 'karma-safarinative-launcher', 'karma-simple-reporter', 'karma-sinon-chai', 'karma-source-map-support', 'karma-super-dots-reporter', { 'middleware:custom': [ 'factory', function () { return require(require.resolve('../server/app.js')); }, ], }, ], };<|fim▁end|>
Chrome_ci: { base: 'Chrome',
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>""" Test cases to cover Accounts-related behaviors of the User API application """ import datetime import hashlib import json from copy import deepcopy<|fim▁hole|>import ddt import pytz from django.conf import settings from django.test.testcases import TransactionTestCase from django.test.utils import override_settings from django.urls import reverse from edx_name_affirmation.api import create_verified_name from edx_name_affirmation.statuses import VerifiedNameStatus from rest_framework import status from rest_framework.test import APIClient, APITestCase from common.djangoapps.student.models import PendingEmailChange, UserProfile from common.djangoapps.student.tests.factories import TEST_PASSWORD, RegistrationFactory, UserFactory from openedx.core.djangoapps.oauth_dispatch.jwt import create_jwt_for_user from openedx.core.djangoapps.user_api.accounts import ACCOUNT_VISIBILITY_PREF_KEY from openedx.core.djangoapps.user_api.models import UserPreference from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms from .. import ALL_USERS_VISIBILITY, CUSTOM_VISIBILITY, PRIVATE_VISIBILITY TEST_PROFILE_IMAGE_UPLOADED_AT = datetime.datetime(2002, 1, 9, 15, 43, 1, tzinfo=pytz.UTC) # this is used in one test to check the behavior of profile image url # generation with a relative url in the config. TEST_PROFILE_IMAGE_BACKEND = deepcopy(settings.PROFILE_IMAGE_BACKEND) TEST_PROFILE_IMAGE_BACKEND['options']['base_url'] = '/profile-images/' TEST_BIO_VALUE = "Tired mother of twins" TEST_LANGUAGE_PROFICIENCY_CODE = "hi" class UserAPITestCase(APITestCase): """ The base class for all tests of the User API """ VERIFIED_NAME = "Verified User" def setUp(self): super().setUp() self.anonymous_client = APIClient() self.different_user = UserFactory.create(password=TEST_PASSWORD) self.different_client = APIClient() self.staff_user = UserFactory(is_staff=True, password=TEST_PASSWORD) self.staff_client = APIClient() self.user = UserFactory.create(password=TEST_PASSWORD) # will be assigned to self.client by default def login_client(self, api_client, user): """Helper method for getting the client and user and logging in. Returns client. """ client = getattr(self, api_client) user = getattr(self, user) client.login(username=user.username, password=TEST_PASSWORD) return client def send_post(self, client, json_data, content_type='application/json', expected_status=201): """ Helper method for sending a post to the server, defaulting to application/json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.post(self.url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response def send_patch(self, client, json_data, content_type="application/merge-patch+json", expected_status=200): """ Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.patch(self.url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response def post_search_api(self, client, json_data, content_type='application/json', expected_status=200): """ Helper method for sending a post to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.post(self.search_api_url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response def send_get(self, client, query_parameters=None, expected_status=200): """ Helper method for sending a GET to the server. Verifies the expected status and returns the response. """ url = self.url + '?' + query_parameters if query_parameters else self.url # pylint: disable=no-member response = client.get(url) assert expected_status == response.status_code return response # pylint: disable=no-member def send_put(self, client, json_data, content_type="application/json", expected_status=204): """ Helper method for sending a PUT to the server. Verifies the expected status and returns the response. """ response = client.put(self.url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response # pylint: disable=no-member def send_delete(self, client, expected_status=204): """ Helper method for sending a DELETE to the server. Verifies the expected status and returns the response. """ response = client.delete(self.url) assert expected_status == response.status_code return response def create_mock_profile(self, user): """ Helper method that creates a mock profile for the specified user :return: """ legacy_profile = UserProfile.objects.get(id=user.id) legacy_profile.country = "US" legacy_profile.state = "MA" legacy_profile.level_of_education = "m" legacy_profile.year_of_birth = 2000 legacy_profile.goals = "world peace" legacy_profile.mailing_address = "Park Ave" legacy_profile.gender = "f" legacy_profile.bio = TEST_BIO_VALUE legacy_profile.profile_image_uploaded_at = TEST_PROFILE_IMAGE_UPLOADED_AT legacy_profile.language_proficiencies.create(code=TEST_LANGUAGE_PROFICIENCY_CODE) legacy_profile.phone_number = "+18005555555" legacy_profile.save() def create_mock_verified_name(self, user): """ Helper method to create an approved VerifiedName entry in name affirmation. """ legacy_profile = UserProfile.objects.get(id=user.id) create_verified_name(user, self.VERIFIED_NAME, legacy_profile.name, status=VerifiedNameStatus.APPROVED) def create_user_registration(self, user): """ Helper method that creates a registration object for the specified user """ RegistrationFactory(user=user) def _verify_profile_image_data(self, data, has_profile_image): """ Verify the profile image data in a GET response for self.user corresponds to whether the user has or hasn't set a profile image. """ template = '{root}/{filename}_{{size}}.{extension}' if has_profile_image: url_root = 'http://example-storage.com/profile-images' filename = hashlib.md5(('secret' + self.user.username).encode('utf-8')).hexdigest() file_extension = 'jpg' template += '?v={}'.format(TEST_PROFILE_IMAGE_UPLOADED_AT.strftime("%s")) else: url_root = 'http://testserver/static' filename = 'default' file_extension = 'png' template = template.format(root=url_root, filename=filename, extension=file_extension) assert data['profile_image'] == {'has_image': has_profile_image, 'image_url_full': template.format(size=50), 'image_url_small': template.format(size=10)} @ddt.ddt @skip_unless_lms class TestOwnUsernameAPI(CacheIsolationTestCase, UserAPITestCase): """ Unit tests for the Accounts API. """ ENABLED_CACHES = ['default'] def setUp(self): super().setUp() self.url = reverse("own_username_api") def _verify_get_own_username(self, queries, expected_status=200): """ Internal helper to perform the actual assertion """ with self.assertNumQueries(queries): response = self.send_get(self.client, expected_status=expected_status) if expected_status == 200: data = response.data assert 1 == len(data) assert self.user.username == data['username'] def test_get_username(self): """ Test that a client (logged in) can get her own username. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self._verify_get_own_username(17) def test_get_username_inactive(self): """ Test that a logged-in client can get their username, even if inactive. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.user.is_active = False self.user.save() self._verify_get_own_username(17) def test_get_username_not_logged_in(self): """ Test that a client (not logged in) gets a 401 when trying to retrieve their username. """ # verify that the endpoint is inaccessible when not logged in self._verify_get_own_username(13, expected_status=401) @ddt.ddt @skip_unless_lms @mock.patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10]) @mock.patch.dict( 'django.conf.settings.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'small': 10}, clear=True ) class TestAccountsAPI(CacheIsolationTestCase, UserAPITestCase): """ Unit tests for the Accounts API. """ ENABLED_CACHES = ['default'] TOTAL_QUERY_COUNT = 27 FULL_RESPONSE_FIELD_COUNT = 30 def setUp(self): super().setUp() self.url = reverse("accounts_api", kwargs={'username': self.user.username}) self.search_api_url = reverse("accounts_search_emails_api") def _set_user_age_to_10_years(self, user): """ Sets the given user's age to 10. Returns the calculated year of birth. """ legacy_profile = UserProfile.objects.get(id=user.id) current_year = datetime.datetime.now().year year_of_birth = current_year - 10 legacy_profile.year_of_birth = year_of_birth legacy_profile.save() return year_of_birth def _verify_full_shareable_account_response(self, response, account_privacy=None, badges_enabled=False): """ Verify that the shareable fields from the account are returned """ data = response.data assert 12 == len(data) # public fields (3) assert account_privacy == data['account_privacy'] self._verify_profile_image_data(data, True) assert self.user.username == data['username'] # additional shareable fields (8) assert TEST_BIO_VALUE == data['bio'] assert 'US' == data['country'] assert data['date_joined'] is not None assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies'] assert 'm' == data['level_of_education'] assert data['social_links'] is not None assert data['time_zone'] is None assert badges_enabled == data['accomplishments_shared'] def _verify_private_account_response(self, response, requires_parental_consent=False): """ Verify that only the public fields are returned if a user does not want to share account fields """ data = response.data assert 3 == len(data) assert PRIVATE_VISIBILITY == data['account_privacy'] self._verify_profile_image_data(data, not requires_parental_consent) assert self.user.username == data['username'] def _verify_full_account_response(self, response, requires_parental_consent=False, year_of_birth=2000): """ Verify that all account fields are returned (even those that are not shareable). """ data = response.data assert self.FULL_RESPONSE_FIELD_COUNT == len(data) # public fields (3) expected_account_privacy = ( PRIVATE_VISIBILITY if requires_parental_consent else UserPreference.get_value(self.user, 'account_privacy') ) assert expected_account_privacy == data['account_privacy'] self._verify_profile_image_data(data, not requires_parental_consent) assert self.user.username == data['username'] # additional shareable fields (8) assert TEST_BIO_VALUE == data['bio'] assert 'US' == data['country'] assert data['date_joined'] is not None assert data['last_login'] is not None assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies'] assert 'm' == data['level_of_education'] assert data['social_links'] is not None assert UserPreference.get_value(self.user, 'time_zone') == data['time_zone'] assert data['accomplishments_shared'] is not None assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] # additional admin fields (13) assert self.user.email == data['email'] assert self.user.id == data['id'] assert self.VERIFIED_NAME == data['verified_name'] assert data['extended_profile'] is not None assert 'MA' == data['state'] assert 'f' == data['gender'] assert 'world peace' == data['goals'] assert data['is_active'] assert 'Park Ave' == data['mailing_address'] assert requires_parental_consent == data['requires_parental_consent'] assert data['secondary_email'] is None assert data['secondary_email_enabled'] is None assert year_of_birth == data['year_of_birth'] def test_anonymous_access(self): """ Test that an anonymous client (not logged in) cannot call GET or PATCH. """ self.send_get(self.anonymous_client, expected_status=401) self.send_patch(self.anonymous_client, {}, expected_status=401) def test_unsupported_methods(self): """ Test that DELETE, POST, and PUT are not supported. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) assert 405 == self.client.put(self.url).status_code assert 405 == self.client.post(self.url).status_code assert 405 == self.client.delete(self.url).status_code @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_get_account_unknown_user(self, api_client, user): """ Test that requesting a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"})) assert 404 == response.status_code @ddt.data( ("client", "user"), ) @ddt.unpack def test_regsitration_activation_key(self, api_client, user): """ Test that registration activation key has a value. UserFactory does not auto-generate registration object for the test users. It is created only for users that signup via email/API. Therefore, activation key has to be tested manually. """ self.create_user_registration(self.user) client = self.login_client(api_client, user) response = self.send_get(client) assert response.data["activation_key"] is not None def test_successful_get_account_by_email(self): """ Test that request using email by a staff user successfully retrieves Account Info. """ api_client = "staff_client" user = "staff_user" client = self.login_client(api_client, user) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = self.send_get(client, query_parameters=f'email={self.user.email}') self._verify_full_account_response(response) def test_unsuccessful_get_account_by_email(self): """ Test that request using email by a normal user fails to retrieve Account Info. """ api_client = "client" user = "user" client = self.login_client(api_client, user) self.create_mock_profile(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = self.send_get( client, query_parameters=f'email={self.user.email}', expected_status=status.HTTP_403_FORBIDDEN ) assert response.data.get('detail') == 'You do not have permission to perform this action.' def test_successful_get_account_by_user_id(self): """ Test that request using lms user id by a staff user successfully retrieves Account Info. """ api_client = "staff_client" user = "staff_user" url = reverse("accounts_detail_api") client = self.login_client(api_client, user) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = client.get(url + f'?lms_user_id={self.user.id}') assert response.status_code == status.HTTP_200_OK response.data = response.data[0] self._verify_full_account_response(response) def test_unsuccessful_get_account_by_user_id(self): """ Test that requesting using lms user id by a normal user fails to retrieve Account Info. """ api_client = "client" user = "user" url = reverse("accounts_detail_api") client = self.login_client(api_client, user) self.create_mock_profile(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = client.get(url + f'?lms_user_id={self.user.id}') assert response.status_code == status.HTTP_403_FORBIDDEN assert response.data.get('detail') == 'You do not have permission to perform this action.' @ddt.data('abc', '2f', '1.0', "2/8") def test_get_account_by_user_id_non_integer(self, non_integer_id): """ Test that request using a non-integer lms user id by a staff user fails to retrieve Account Info. """ api_client = "staff_client" user = "staff_user" url = reverse("accounts_detail_api") client = self.login_client(api_client, user) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = client.get(url + f'?lms_user_id={non_integer_id}') assert response.status_code == status.HTTP_400_BAD_REQUEST def test_search_emails(self): client = self.login_client('staff_client', 'staff_user') json_data = {'emails': [self.user.email]} response = self.post_search_api(client, json_data=json_data) assert response.data == [{'email': self.user.email, 'id': self.user.id, 'username': self.user.username}] def test_search_emails_with_non_staff_user(self): client = self.login_client('client', 'user') json_data = {'emails': [self.user.email]} response = self.post_search_api(client, json_data=json_data, expected_status=404) assert response.data == { 'developer_message': "not_found", 'user_message': "Not Found" } def test_search_emails_with_non_existing_email(self): client = self.login_client('staff_client', 'staff_user') json_data = {"emails": ['[email protected]']} response = self.post_search_api(client, json_data=json_data) assert response.data == [] def test_search_emails_with_invalid_param(self): client = self.login_client('staff_client', 'staff_user') json_data = {'invalid_key': [self.user.email]} response = self.post_search_api(client, json_data=json_data, expected_status=400) assert response.data == { 'developer_message': "'emails' field is required", 'user_message': "'emails' field is required" } # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @mock.patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "all_users"}) def test_get_account_different_user_visible(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "all_users". """ self.different_client.login(username=self.different_user.username, password=TEST_PASSWORD) self.create_mock_profile(self.user) with self.assertNumQueries(self.TOTAL_QUERY_COUNT): response = self.send_get(self.different_client) self._verify_full_shareable_account_response(response, account_privacy=ALL_USERS_VISIBILITY) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @mock.patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "private"}) def test_get_account_different_user_private(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "private". """ self.different_client.login(username=self.different_user.username, password=TEST_PASSWORD) self.create_mock_profile(self.user) with self.assertNumQueries(self.TOTAL_QUERY_COUNT): response = self.send_get(self.different_client) self._verify_private_account_response(response) @mock.patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True}) @ddt.data( ("client", "user", PRIVATE_VISIBILITY), ("different_client", "different_user", PRIVATE_VISIBILITY), ("staff_client", "staff_user", PRIVATE_VISIBILITY), ("client", "user", ALL_USERS_VISIBILITY), ("different_client", "different_user", ALL_USERS_VISIBILITY), ("staff_client", "staff_user", ALL_USERS_VISIBILITY), ) @ddt.unpack def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility): """ Test the return from GET based on user visibility setting. """ def verify_fields_visible_to_all_users(response): """ Confirms that private fields are private, and public/shareable fields are public/shareable """ if preference_visibility == PRIVATE_VISIBILITY: self._verify_private_account_response(response) else: self._verify_full_shareable_account_response(response, ALL_USERS_VISIBILITY, badges_enabled=True) client = self.login_client(api_client, requesting_username) # Update user account visibility setting. set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) response = self.send_get(client) if requesting_username == "different_user": verify_fields_visible_to_all_users(response) else: self._verify_full_account_response(response) # Verify how the view parameter changes the fields that are returned. response = self.send_get(client, query_parameters='view=shared') verify_fields_visible_to_all_users(response) response = self.send_get(client, query_parameters=f'view=shared&username={self.user.username}') verify_fields_visible_to_all_users(response) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ("different_client", "different_user"), ) @ddt.unpack def test_custom_visibility_over_age(self, api_client, requesting_username): self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) # set user's custom visibility preferences set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, CUSTOM_VISIBILITY) shared_fields = ("bio", "language_proficiencies", "name") for field_name in shared_fields: set_user_preference(self.user, f"visibility.{field_name}", ALL_USERS_VISIBILITY) # make API request client = self.login_client(api_client, requesting_username) response = self.send_get(client) # verify response if requesting_username == "different_user": data = response.data assert 6 == len(data) # public fields assert self.user.username == data['username'] assert UserPreference.get_value(self.user, 'account_privacy') == data['account_privacy'] self._verify_profile_image_data(data, has_profile_image=True) # custom shared fields assert TEST_BIO_VALUE == data['bio'] assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies'] assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] else: self._verify_full_account_response(response) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ("different_client", "different_user"), ) @ddt.unpack def test_custom_visibility_under_age(self, api_client, requesting_username): self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) year_of_birth = self._set_user_age_to_10_years(self.user) # set user's custom visibility preferences set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, CUSTOM_VISIBILITY) shared_fields = ("bio", "language_proficiencies") for field_name in shared_fields: set_user_preference(self.user, f"visibility.{field_name}", ALL_USERS_VISIBILITY) # make API request client = self.login_client(api_client, requesting_username) response = self.send_get(client) # verify response if requesting_username == "different_user": self._verify_private_account_response(response, requires_parental_consent=True) else: self._verify_full_account_response( response, requires_parental_consent=True, year_of_birth=year_of_birth, ) def test_get_account_default(self): """ Test that a client (logged in) can get her own account information (using default legacy profile information, as created by the test UserFactory). """ def verify_get_own_information(queries): """ Internal helper to perform the actual assertions """ with self.assertNumQueries(queries): response = self.send_get(self.client) data = response.data assert self.FULL_RESPONSE_FIELD_COUNT == len(data) assert self.user.username == data['username'] assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"): assert data[empty_field] is None assert data['country'] is None assert data['state'] is None assert 'm' == data['gender'] assert 'Learn a lot' == data['goals'] assert self.user.email == data['email'] assert self.user.id == data['id'] assert data['date_joined'] is not None assert data['last_login'] is not None assert self.user.is_active == data['is_active'] self._verify_profile_image_data(data, False) assert data['requires_parental_consent'] assert [] == data['language_proficiencies'] assert PRIVATE_VISIBILITY == data['account_privacy'] assert data['time_zone'] is None # Badges aren't on by default, so should not be present. assert data['accomplishments_shared'] is False self.client.login(username=self.user.username, password=TEST_PASSWORD) verify_get_own_information(25) # Now make sure that the user can get the same information, even if not active self.user.is_active = False self.user.save() verify_get_own_information(17) def test_get_account_empty_string(self): """ Test the conversion of empty strings to None for certain fields. """ legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.country = "" legacy_profile.state = "" legacy_profile.level_of_education = "" legacy_profile.gender = "" legacy_profile.bio = "" legacy_profile.save() self.client.login(username=self.user.username, password=TEST_PASSWORD) with self.assertNumQueries(25): response = self.send_get(self.client) for empty_field in ("level_of_education", "gender", "country", "state", "bio",): assert response.data[empty_field] is None @ddt.data( ("different_client", "different_user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_disallowed_user(self, api_client, user): """ Test that a client cannot call PATCH on a different client's user account (even with is_staff access). """ client = self.login_client(api_client, user) self.send_patch(client, {}, expected_status=403) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_unknown_user(self, api_client, user): """ Test that trying to update a user who does not exist returns a 403. """ client = self.login_client(api_client, user) response = client.patch( reverse("accounts_api", kwargs={'username': "does_not_exist"}), data=json.dumps({}), content_type="application/merge-patch+json" ) assert 403 == response.status_code @ddt.data( ("gender", "f", "not a gender", '"not a gender" is not a valid choice.'), ("level_of_education", "none", "ȻħȺɍłɇs", '"ȻħȺɍłɇs" is not a valid choice.'), ("country", "GB", "XY", '"XY" is not a valid choice.'), ("state", "MA", "PY", '"PY" is not a valid choice.'), ("year_of_birth", 2009, "not_an_int", "A valid integer is required."), ("name", "bob", "z" * 256, "Ensure this field has no more than 255 characters."), ("name", "ȻħȺɍłɇs", " ", "The name field must be at least 1 character long."), ("goals", "Smell the roses"), ("mailing_address", "Sesame Street"), # Note that we store the raw data, so it is up to client to escape the HTML. ( "bio", "<html>Lacrosse-playing superhero 壓是進界推日不復女</html>", "z" * 301, "The about me field must be at most 300 characters long." ), ("account_privacy", ALL_USERS_VISIBILITY), ("account_privacy", PRIVATE_VISIBILITY), # Note that email is tested below, as it is not immediately updated. # Note that language_proficiencies is tested below as there are multiple error and success conditions. ) @ddt.unpack def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None): """ Test the behavior of patch, when using the correct content_type. """ client = self.login_client("client", "user") if field == 'account_privacy': # Ensure the user has birth year set, and is over 13, so # account_privacy behaves normally legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.year_of_birth = 2000 legacy_profile.save() response = self.send_patch(client, {field: value}) assert value == response.data[field] if fails_validation_value: error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400) expected_user_message = 'This value is invalid.' if field == 'bio': expected_user_message = "The about me field must be at most 300 characters long." assert expected_user_message == error_response.data['field_errors'][field]['user_message'] assert "Value '{value}' is not valid for field '{field}': {messages}".format( value=fails_validation_value, field=field, messages=[developer_validation_message] ) == error_response.data['field_errors'][field]['developer_message'] elif field != "account_privacy": # If there are no values that would fail validation, then empty string should be supported; # except for account_privacy, which cannot be an empty string. response = self.send_patch(client, {field: ""}) assert '' == response.data[field] def test_patch_inactive_user(self): """ Verify that a user can patch her own account, even if inactive. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.user.is_active = False self.user.save() response = self.send_patch(self.client, {"goals": "to not activate account"}) assert 'to not activate account' == response.data['goals'] @ddt.unpack def test_patch_account_noneditable(self): """ Tests the behavior of patch when a read-only field is attempted to be edited. """ client = self.login_client("client", "user") def verify_error_response(field_name, data): """ Internal helper to check the error messages returned """ assert 'This field is not editable via this API' == data['field_errors'][field_name]['developer_message'] assert "The '{}' field cannot be edited.".format( field_name ) == data['field_errors'][field_name]['user_message'] for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]: response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400) verify_error_response(field_name, response.data) # Make sure that gender did not change. response = self.send_get(client) assert 'm' == response.data['gender'] # Test error message with multiple read-only items response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400) assert 2 == len(response.data['field_errors']) verify_error_response("username", response.data) verify_error_response("date_joined", response.data) def test_patch_bad_content_type(self): """ Test the behavior of patch when an incorrect content_type is specified. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_patch(self.client, {}, content_type="application/json", expected_status=415) self.send_patch(self.client, {}, content_type="application/xml", expected_status=415) def test_patch_account_empty_string(self): """ Tests the behavior of patch when attempting to set fields with a select list of options to the empty string. Also verifies the behaviour when setting to None. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) for field_name in ["gender", "level_of_education", "country", "state"]: response = self.send_patch(self.client, {field_name: ""}) # Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer # is to convert to None, which also seems acceptable (and is difficult to override). assert response.data[field_name] is None # Verify that the behavior is the same for sending None. response = self.send_patch(self.client, {field_name: ""}) assert response.data[field_name] is None def test_patch_name_metadata(self): """ Test the metadata stored when changing the name field. """ def get_name_change_info(expected_entries): """ Internal method to encapsulate the retrieval of old names used """ legacy_profile = UserProfile.objects.get(id=self.user.id) name_change_info = legacy_profile.get_meta()["old_names"] assert expected_entries == len(name_change_info) return name_change_info def verify_change_info(change_info, old_name, requester, new_name): """ Internal method to validate name changes """ assert 3 == len(change_info) assert old_name == change_info[0] assert f'Name change requested through account API by {requester}' == change_info[1] assert change_info[2] is not None # Verify the new name was also stored. get_response = self.send_get(self.client) assert new_name == get_response.data['name'] self.client.login(username=self.user.username, password=TEST_PASSWORD) legacy_profile = UserProfile.objects.get(id=self.user.id) assert {} == legacy_profile.get_meta() old_name = legacy_profile.name # First change the name as the user and verify meta information. self.send_patch(self.client, {"name": "Mickey Mouse"}) name_change_info = get_name_change_info(1) verify_change_info(name_change_info[0], old_name, self.user.username, "Mickey Mouse") # Now change the name again and verify meta information. self.send_patch(self.client, {"name": "Donald Duck"}) name_change_info = get_name_change_info(2) verify_change_info(name_change_info[0], old_name, self.user.username, "Donald Duck", ) verify_change_info(name_change_info[1], "Mickey Mouse", self.user.username, "Donald Duck") @mock.patch.dict( 'django.conf.settings.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'medium': 30, 'small': 10}, clear=True ) def test_patch_email(self): """ Test that the user can request an email change through the accounts API. Full testing of the helper method used (do_email_change_request) exists in the package with the code. Here just do minimal smoke testing. """ client = self.login_client("client", "user") old_email = self.user.email new_email = "[email protected]" response = self.send_patch(client, {"email": new_email, "goals": "change my email"}) # Since request is multi-step, the email won't change on GET immediately (though goals will update). assert old_email == response.data['email'] assert 'change my email' == response.data['goals'] # Now call the method that will be invoked with the user clicks the activation key in the received email. # First we must get the activation key that was sent. pending_change = PendingEmailChange.objects.filter(user=self.user) assert 1 == len(pending_change) activation_key = pending_change[0].activation_key confirm_change_url = reverse( "confirm_email_change", kwargs={'key': activation_key} ) response = self.client.post(confirm_change_url) assert 200 == response.status_code get_response = self.send_get(client) assert new_email == get_response.data['email'] @ddt.data( ("not_an_email",), ("",), (None,), ) @ddt.unpack def test_patch_invalid_email(self, bad_email): """ Test a few error cases for email validation (full test coverage lives with do_email_change_request). """ client = self.login_client("client", "user") # Try changing to an invalid email to make sure error messages are appropriately returned. error_response = self.send_patch(client, {"email": bad_email}, expected_status=400) field_errors = error_response.data["field_errors"] assert "Error thrown from validate_new_email: 'Valid e-mail address required.'" == \ field_errors['email']['developer_message'] assert 'Valid e-mail address required.' == field_errors['email']['user_message'] @mock.patch('common.djangoapps.student.views.management.do_email_change_request') def test_patch_duplicate_email(self, do_email_change_request): """ Test that same success response will be sent to user even if the given email already used. """ existing_email = "[email protected]" UserFactory.create(email=existing_email) client = self.login_client("client", "user") # Try changing to an existing email to make sure no error messages returned. response = self.send_patch(client, {"email": existing_email}) assert 200 == response.status_code # Verify that no actual request made for email change assert not do_email_change_request.called def test_patch_language_proficiencies(self): """ Verify that patching the language_proficiencies field of the user profile completely overwrites the previous value. """ client = self.login_client("client", "user") # Patching language_proficiencies exercises the # `LanguageProficiencySerializer.get_identity` method, which compares # identifies language proficiencies based on their language code rather # than django model id. for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []): response = self.send_patch(client, {"language_proficiencies": proficiencies}) self.assertCountEqual(response.data["language_proficiencies"], proficiencies) @ddt.data( ( "not_a_list", {'non_field_errors': ['Expected a list of items but got type "unicode".']} ), ( ["not_a_JSON_object"], [{'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}] ), ( [{}], [{'code': ['This field is required.']}] ), ( [{"code": "invalid_language_code"}], [{'code': ['"invalid_language_code" is not a valid choice.']}] ), ( [{"code": "kw"}, {"code": "el"}, {"code": "kw"}], ['The language_proficiencies field must consist of unique languages.'] ), ) @ddt.unpack def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message): """ Verify we handle error cases when patching the language_proficiencies field. """ expected_error_message = str(expected_error_message).replace('unicode', 'str') client = self.login_client("client", "user") response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400) assert response.data['field_errors']['language_proficiencies']['developer_message'] == \ f"Value '{patch_value}' is not valid for field 'language_proficiencies': {expected_error_message}" @mock.patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save') def test_patch_serializer_save_fails(self, serializer_save): """ Test that AccountUpdateErrors are passed through to the response. """ serializer_save.side_effect = [Exception("bummer"), None] self.client.login(username=self.user.username, password=TEST_PASSWORD) error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400) assert "Error thrown when saving account updates: 'bummer'" == error_response.data['developer_message'] assert error_response.data['user_message'] is None @override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND) def test_convert_relative_profile_url(self): """ Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins with a '/', the API generates the full URL to profile images based on the URL of the request. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) response = self.send_get(self.client) assert response.data['profile_image'] == \ {'has_image': False, 'image_url_full': 'http://testserver/static/default_50.png', 'image_url_small': 'http://testserver/static/default_10.png'} @ddt.data( ("client", "user", True), ("different_client", "different_user", False), ("staff_client", "staff_user", True), ) @ddt.unpack def test_parental_consent(self, api_client, requesting_username, has_full_access): """ Verifies that under thirteens never return a public profile. """ client = self.login_client(api_client, requesting_username) year_of_birth = self._set_user_age_to_10_years(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY) # Verify that the default view is still private (except for clients with full access) response = self.send_get(client) if has_full_access: data = response.data assert self.FULL_RESPONSE_FIELD_COUNT == len(data) assert self.user.username == data['username'] assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] assert self.user.email == data['email'] assert self.user.id == data['id'] assert year_of_birth == data['year_of_birth'] for empty_field in ("country", "level_of_education", "mailing_address", "bio", "state",): assert data[empty_field] is None assert 'm' == data['gender'] assert 'Learn a lot' == data['goals'] assert data['is_active'] assert data['date_joined'] is not None assert data['last_login'] is not None self._verify_profile_image_data(data, False) assert data['requires_parental_consent'] assert PRIVATE_VISIBILITY == data['account_privacy'] else: self._verify_private_account_response(response, requires_parental_consent=True) # Verify that the shared view is still private response = self.send_get(client, query_parameters='view=shared') self._verify_private_account_response(response, requires_parental_consent=True) @skip_unless_lms class TestAccountAPITransactions(TransactionTestCase): """ Tests the transactional behavior of the account API """ def setUp(self): super().setUp() self.client = APIClient() self.user = UserFactory.create(password=TEST_PASSWORD) self.url = reverse("accounts_api", kwargs={'username': self.user.username}) @mock.patch('common.djangoapps.student.views.do_email_change_request') def test_update_account_settings_rollback(self, mock_email_change): """ Verify that updating account settings is transactional when a failure happens. """ # Send a PATCH request with updates to both profile information and email. # Throw an error from the method that is used to process the email change request # (this is the last thing done in the api method). Verify that the profile did not change. mock_email_change.side_effect = [ValueError, "mock value error thrown"] self.client.login(username=self.user.username, password=TEST_PASSWORD) old_email = self.user.email json_data = {"email": "[email protected]", "gender": "o"} response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json") assert 400 == response.status_code # Verify that GET returns the original preferences response = self.client.get(self.url) data = response.data assert old_email == data['email'] assert 'm' == data['gender'] @ddt.ddt class NameChangeViewTests(UserAPITestCase): """ NameChangeView tests """ def setUp(self): super().setUp() self.url = reverse('name_change') def test_request_succeeds(self): """ Test that a valid name change request succeeds. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post(self.client, {'name': 'New Name'}) def test_unauthenticated(self): """ Test that a name change request fails for an unauthenticated user. """ self.send_post(self.client, {'name': 'New Name'}, expected_status=401) def test_empty_request(self): """ Test that an empty request fails. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post(self.client, {}, expected_status=400) def test_blank_name(self): """ Test that a blank name string fails. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post(self.client, {'name': ''}, expected_status=400) @ddt.data('<html>invalid name</html>', 'https://invalid.com') def test_fails_validation(self, invalid_name): """ Test that an invalid name will return an error. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post( self.client, {'name': invalid_name}, expected_status=400 ) @ddt.ddt @mock.patch('django.conf.settings.USERNAME_REPLACEMENT_WORKER', 'test_replace_username_service_worker') class UsernameReplacementViewTests(APITestCase): """ Tests UsernameReplacementView """ SERVICE_USERNAME = 'test_replace_username_service_worker' def setUp(self): super().setUp() self.service_user = UserFactory(username=self.SERVICE_USERNAME) self.url = reverse("username_replacement") def build_jwt_headers(self, user): """ Helper function for creating headers for the JWT authentication. """ token = create_jwt_for_user(user) headers = {'HTTP_AUTHORIZATION': f'JWT {token}'} return headers def call_api(self, user, data): """ Helper function to call API with data """ data = json.dumps(data) headers = self.build_jwt_headers(user) return self.client.post(self.url, data, content_type='application/json', **headers) def test_auth(self): """ Verify the endpoint only works with the service worker """ data = { "username_mappings": [ {"test_username_1": "test_new_username_1"}, {"test_username_2": "test_new_username_2"} ] } # Test unauthenticated response = self.client.post(self.url) assert response.status_code == 401 # Test non-service worker random_user = UserFactory() response = self.call_api(random_user, data) assert response.status_code == 403 # Test service worker response = self.call_api(self.service_user, data) assert response.status_code == 200 @ddt.data( [{}, {}], {}, [{"test_key": "test_value", "test_key_2": "test_value_2"}] ) def test_bad_schema(self, mapping_data): """ Verify the endpoint rejects bad data schema """ data = { "username_mappings": mapping_data } response = self.call_api(self.service_user, data) assert response.status_code == 400 def test_existing_and_non_existing_users(self): """ Tests a mix of existing and non existing users """ random_users = [UserFactory() for _ in range(5)] fake_usernames = ["myname_" + str(x) for x in range(5)] existing_users = [{user.username: user.username + '_new'} for user in random_users] non_existing_users = [{username: username + '_new'} for username in fake_usernames] data = { "username_mappings": existing_users + non_existing_users } expected_response = { 'failed_replacements': [], 'successful_replacements': existing_users + non_existing_users } response = self.call_api(self.service_user, data) assert response.status_code == 200 assert response.data == expected_response<|fim▁end|>
from unittest import mock
<|file_name|>HTMLTreeBuilder.py<|end_file_name|><|fim▁begin|># # ElementTree # $Id: HTMLTreeBuilder.py 3265 2007-09-06 20:42:00Z fredrik $ # # a simple tree builder, for HTML input # # history: # 2002-04-06 fl created # 2002-04-07 fl ignore IMG and HR end tags # 2002-04-07 fl added support for 1.5.2 and later # 2003-04-13 fl added HTMLTreeBuilder alias # 2004-12-02 fl don't feed non-ASCII charrefs/entities as 8-bit strings # 2004-12-05 fl don't feed non-ASCII CDATA as 8-bit strings # # Copyright (c) 1999-2004 by Fredrik Lundh. All rights reserved. # # [email protected] # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2007 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-<|fim▁hole|># ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- ## # Tools to build element trees from HTML files. ## import htmlentitydefs import re, string, sys import mimetools, StringIO import ElementTree AUTOCLOSE = "p", "li", "tr", "th", "td", "head", "body" IGNOREEND = "img", "hr", "meta", "link", "br" if sys.version[:3] == "1.5": is_not_ascii = re.compile(r"[\x80-\xff]").search # 1.5.2 else: is_not_ascii = re.compile(eval(r'u"[\u0080-\uffff]"')).search try: from HTMLParser import HTMLParser except ImportError: from sgmllib import SGMLParser # hack to use sgmllib's SGMLParser to emulate 2.2's HTMLParser class HTMLParser(SGMLParser): # the following only works as long as this class doesn't # provide any do, start, or end handlers def unknown_starttag(self, tag, attrs): self.handle_starttag(tag, attrs) def unknown_endtag(self, tag): self.handle_endtag(tag) ## # ElementTree builder for HTML source code. This builder converts an # HTML document or fragment to an ElementTree. # <p> # The parser is relatively picky, and requires balanced tags for most # elements. However, elements belonging to the following group are # automatically closed: P, LI, TR, TH, and TD. In addition, the # parser automatically inserts end tags immediately after the start # tag, and ignores any end tags for the following group: IMG, HR, # META, and LINK. # # @keyparam builder Optional builder object. If omitted, the parser # uses the standard <b>elementtree</b> builder. # @keyparam encoding Optional character encoding, if known. If omitted, # the parser looks for META tags inside the document. If no tags # are found, the parser defaults to ISO-8859-1. Note that if your # document uses a non-ASCII compatible encoding, you must decode # the document before parsing. # # @see elementtree.ElementTree class HTMLTreeBuilder(HTMLParser): # FIXME: shouldn't this class be named Parser, not Builder? def __init__(self, builder=None, encoding=None): self.__stack = [] if builder is None: builder = ElementTree.TreeBuilder() self.__builder = builder self.encoding = encoding or "iso-8859-1" HTMLParser.__init__(self) ## # Flushes parser buffers, and return the root element. # # @return An Element instance. def close(self): HTMLParser.close(self) return self.__builder.close() ## # (Internal) Handles start tags. def handle_starttag(self, tag, attrs): if tag == "meta": # look for encoding directives http_equiv = content = None for k, v in attrs: if k == "http-equiv": http_equiv = string.lower(v) elif k == "content": content = v if http_equiv == "content-type" and content: # use mimetools to parse the http header header = mimetools.Message( StringIO.StringIO("%s: %s\n\n" % (http_equiv, content)) ) encoding = header.getparam("charset") if encoding: self.encoding = encoding if tag in AUTOCLOSE: if self.__stack and self.__stack[-1] == tag: self.handle_endtag(tag) self.__stack.append(tag) attrib = {} if attrs: for k, v in attrs: attrib[string.lower(k)] = v self.__builder.start(tag, attrib) if tag in IGNOREEND: self.__stack.pop() self.__builder.end(tag) ## # (Internal) Handles end tags. def handle_endtag(self, tag): if tag in IGNOREEND: return lasttag = self.__stack.pop() if tag != lasttag and lasttag in AUTOCLOSE: self.handle_endtag(lasttag) self.__builder.end(tag) ## # (Internal) Handles character references. def handle_charref(self, char): if char[:1] == "x": char = int(char[1:], 16) else: char = int(char) if 0 <= char < 128: self.__builder.data(chr(char)) else: self.__builder.data(unichr(char)) ## # (Internal) Handles entity references. def handle_entityref(self, name): entity = htmlentitydefs.entitydefs.get(name) if entity: if len(entity) == 1: entity = ord(entity) else: entity = int(entity[2:-1]) if 0 <= entity < 128: self.__builder.data(chr(entity)) else: self.__builder.data(unichr(entity)) else: self.unknown_entityref(name) ## # (Internal) Handles character data. def handle_data(self, data): if isinstance(data, type('')) and is_not_ascii(data): # convert to unicode, but only if necessary data = unicode(data, self.encoding, "ignore") self.__builder.data(data) ## # (Hook) Handles unknown entity references. The default action # is to ignore unknown entities. def unknown_entityref(self, name): pass # ignore by default; override if necessary ## # An alias for the <b>HTMLTreeBuilder</b> class. TreeBuilder = HTMLTreeBuilder ## # Parse an HTML document or document fragment. # # @param source A filename or file object containing HTML data. # @param encoding Optional character encoding, if known. If omitted, # the parser looks for META tags inside the document. If no tags # are found, the parser defaults to ISO-8859-1. # @return An ElementTree instance def parse(source, encoding=None): return ElementTree.parse(source, HTMLTreeBuilder(encoding=encoding)) if __name__ == "__main__": import sys ElementTree.dump(parse(open(sys.argv[1])))<|fim▁end|>
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, 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
<|file_name|>FileManagerSmallDatapoolTest.java<|end_file_name|><|fim▁begin|>/* * SPDX-License-Identifier: GPL-3.0 * * * (J)ava (M)iscellaneous (U)tilities (L)ibrary * * JMUL is a central repository for utilities which are used in my * other public and private repositories. * * Copyright (C) 2013 Kristian Kutin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * e-mail: [email protected] */ /* * This section contains meta informations. * * $Id$ */ package test.jmul.persistence; import jmul.misc.id.IDGenerator; import jmul.persistence.file.FileManager; import static jmul.string.Constants.FILE_SEPARATOR; import jmul.test.classification.ModuleTest; import org.junit.After; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * This class contains tests to check file mangaers with existing files. * * @author Kristian Kutin */ @ModuleTest public class FileManagerSmallDatapoolTest extends FileManagerTestBase { /** * A base directory for tests. */ private static final String BASEDIR = ROOT_DIRECTORY + "File-Manager3"; /** * The file where the generated IDs are persisted. */ private static final String ID_FILE = BASEDIR + FILE_SEPARATOR + "idtest"; /** * The number of files with which the file manager will be prepared before * running the actual test. */ private static final int FILES_THRESHOLD = 10000; /** * A file manager. */ private FileManager fileManager; /** * An ID generator.<|fim▁hole|> /** * Preparations before a test. */ @Before public void setUp() { initBaseDirectory(BASEDIR); fileManager = initFileManager(BASEDIR); generator = initIDGenerator(ID_FILE); createTestFiles(fileManager, generator, FILES_THRESHOLD); } /** * Cleanup after a test. */ @After public void tearDown() { fileManager.shutdown(); fileManager = null; generator = null; } /** * Tests searching for a file within an existing data pool. */ @Test public void testSmallDatapool() { String[] identifiers = { "#z72_", "Hello World!" }; boolean[] expectedResults = { true, false }; assertEquals("Testdata is incorrect!", identifiers.length, expectedResults.length); for (int a = 0; a < identifiers.length; a++) { String identifier = identifiers[a]; boolean expectedResult = expectedResults[a]; boolean result = fileManager.existsFile(identifier); checkExistence(identifier, expectedResult, result); } } }<|fim▁end|>
*/ private IDGenerator generator;
<|file_name|>solution_1_wrong.py<|end_file_name|><|fim▁begin|>def calc(): h, l = input().split(' ') mapa = [] for i_row in range(int(h)): mapa.append(input().split(' ')) maior_num = 0 for row in mapa: for col in row: n = int(col) if (n > maior_num): maior_num = n qtd = [0 for i in range(maior_num + 1)] for row in mapa: for col in row: n = int(col) qtd[n] = qtd[n] + 1 menor = 1 for i in range(1, len(qtd)): if (qtd[i] <= qtd[menor]): menor = i <|fim▁hole|> calc()<|fim▁end|>
print(menor)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from olpc import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) email = db.Column(db.String(120), unique=True) def __init__(self, name, email): self.name = name self.email = email<|fim▁hole|> def __repr__(self): return '<Name %r>' % self.name<|fim▁end|>
<|file_name|>views.py<|end_file_name|><|fim▁begin|>import os from tornado import gen import tornado.web class DocsHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): version = "{}://{}/docs/version/v1.yml".format( self.request.protocol, self.request.host) self.render("swagger/index.html", version=version) class HomeHandler(tornado.web.StaticFileHandler): @gen.coroutine def get(self, path, include_body=True): yield super().get('index.html', include_body) class CachingFrontendHandler(tornado.web.StaticFileHandler): """If a file exists in the root folder, serve it, otherwise serve index.html <|fim▁hole|> """ @gen.coroutine def get(self, path, include_body=True): absolute_path = self.get_absolute_path(self.root, path) is_file = os.path.isfile(absolute_path) if is_file: yield super().get(path, include_body) else: yield super().get('index.html', include_body)<|fim▁end|>
<|file_name|>test_long_path.py<|end_file_name|><|fim▁begin|># coding: utf-8 import os import sys from nxdrive.logging_config import get_logger from nxdrive.utils import safe_long_path from tests.common_unit_test import UnitTestCase if sys.platform == 'win32': import win32api log = get_logger(__name__) # Number of chars in path c://.../Nuxeo.. is approx 96 chars FOLDER_A = 'A' * 90 FOLDER_B = 'B' * 90 FOLDER_C = 'C' * 90 FOLDER_D = 'D' * 50 class TestLongPath(UnitTestCase): def setUp(self): UnitTestCase.setUp(self) self.local_1 = self.local_client_1 self.remote_1 = self.remote_document_client_1 log.info("Create a folder AAAA... (90 chars) in server") self.folder_a = self.remote_1.make_folder("/", FOLDER_A) self.folder_b = self.remote_1.make_folder(self.folder_a, FOLDER_B) self.folder_c = self.remote_1.make_folder(self.folder_b, FOLDER_C) self.remote_1.make_file(self.folder_c, "File1.txt", "Sample Content") def tearDown(self): log.info("Delete the folder AAA... in server") self.remote_1.delete(self.folder_a, use_trash=False) UnitTestCase.tearDown(self) def test_long_path(self): self.engine_1.start() self.wait_sync(wait_for_async=True) parent_path = os.path.join(self.local_1.abspath('/'), FOLDER_A, FOLDER_B, FOLDER_C, FOLDER_D) log.info("Creating folder with path: %s", parent_path) if sys.platform == 'win32' and not os.path.exists(parent_path): log.debug('Add \\\\?\\ prefix to path %r', parent_path) parent_path = safe_long_path(parent_path) os.makedirs(parent_path) if sys.platform == 'win32': log.info("Convert path of FOLDER_D\File2.txt to short path format") parent_path = win32api.GetShortPathName(parent_path) new_file = os.path.join(parent_path, "File2.txt") log.info("Creating file with path: %s", new_file) with open(new_file, "w") as f: f.write("Hello world")<|fim▁hole|> self.wait_sync(wait_for_async=True, timeout=45, fail_if_timeout=False) remote_children_of_c = self.remote_1.get_children_info(self.folder_c) children_names = [item.name for item in remote_children_of_c] log.warn("Verify if FOLDER_D is uploaded to server") self.assertIn(FOLDER_D, children_names) folder_d = [item.uid for item in remote_children_of_c if item.name == FOLDER_D][0] remote_children_of_d = self.remote_1.get_children_info(folder_d) children_names = [item.name for item in remote_children_of_d] log.warn("Verify if FOLDER_D\File2.txt is uploaded to server") self.assertIn('File2.txt', children_names) def test_setup_on_long_path(self): """ NXDRIVE 689: Fix error when adding a new account when installation path is greater than 245 characters. """ self.engine_1.stop() self.engine_1.reinit() # On Mac, avoid permission denied error self.engine_1.get_local_client().clean_xattr_root() test_folder_len = 245 - len(str(self.local_nxdrive_folder_1)) test_folder = 'A' * test_folder_len self.local_nxdrive_folder_1 = os.path.join(self.local_nxdrive_folder_1, test_folder) self.assertTrue(len(self.local_nxdrive_folder_1) > 245) self.manager_1.unbind_all() self.engine_1 = self.manager_1.bind_server( self.local_nxdrive_folder_1, self.nuxeo_url, self.user_2, self.password_2, start_engine=False) self.engine_1.start() self.engine_1.stop()<|fim▁end|>
<|file_name|>test_enroll_user_in_course.py<|end_file_name|><|fim▁begin|>""" Test the change_enrollment command line script.""" import ddt import unittest from uuid import uuid4 from django.conf import settings from django.core.management import call_command from django.core.management.base import CommandError from enrollment.api import get_enrollment from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory @ddt.ddt @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class EnrollManagementCommandTest(SharedModuleStoreTestCase): """ Test the enroll_user_in_course management command """ @classmethod def setUpClass(cls): super(EnrollManagementCommandTest, cls).setUpClass() cls.course = CourseFactory.create(org='fooX', number='007') def setUp(self): super(EnrollManagementCommandTest, self).setUp() self.course_id = unicode(self.course.id) self.username = 'ralph' + uuid4().hex self.user_email = self.username + '@example.com'<|fim▁hole|> UserFactory(username=self.username, email=self.user_email) def test_enroll_user(self): command_args = [ '--course', self.course_id, '--email', self.user_email, ] call_command( 'enroll_user_in_course', *command_args ) user_enroll = get_enrollment(self.username, self.course_id) self.assertTrue(user_enroll['is_active']) def test_enroll_user_twice(self): """ Ensures the command is idempotent. """ command_args = [ '--course', self.course_id, '--email', self.user_email, ] for _ in range(2): call_command( 'enroll_user_in_course', *command_args ) # Second run does not impact the first run (i.e., the # user is still enrolled, no exception was raised, etc) user_enroll = get_enrollment(self.username, self.course_id) self.assertTrue(user_enroll['is_active']) @ddt.data(['--email', 'foo'], ['--course', 'bar'], ['--bad-param', 'baz']) def test_not_enough_args(self, arg): """ When the command is missing certain arguments, it should raise an exception """ command_args = arg with self.assertRaises(CommandError): call_command( 'enroll_user_in_course', *command_args )<|fim▁end|>
<|file_name|>datatable.js<|end_file_name|><|fim▁begin|>/*** Wrapper/Helper Class for datagrid based on jQuery Datatable Plugin ***/ var Datatable = function () { var tableOptions; // main options var dataTable; // datatable object var table; // actual table jquery object var tableContainer; // actual table container object var tableWrapper; // actual table wrapper jquery object var tableInitialized = false; var ajaxParams = {}; // set filter mode var countSelectedRecords = function() { var selected = $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).size(); var text = tableOptions.dataTable.oLanguage.sGroupActions; if (selected > 0) { $('.table-group-actions > span', tableWrapper).text(text.replace("_TOTAL_", selected)); } else { $('.table-group-actions > span', tableWrapper).text(""); } } return { //main function to initiate the module init: function (options) { if (!$().dataTable) { return; } var the = this; // default settings options = $.extend(true, { src: "", // actual table filterApplyAction: "filter", filterCancelAction: "filter_cancel", resetGroupActionInputOnSuccess: true, dataTable: { "sDom" : "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r><'table-scrollable't><'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>r>>", // datatable layout "aLengthMenu": [ // set available records per page [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], "iDisplayLength": 10, // default records per page "oLanguage": { // language settings "sProcessing": '<img src="' + Metronic.getGlobalImgPath() + 'loading-spinner-grey.gif"/><span>&nbsp;&nbsp;Loading...</span>', "sLengthMenu": "<span class='seperator'>|</span>View _MENU_ records", "sInfo": "<span class='seperator'>|</span>Found total _TOTAL_ records", "sInfoEmpty": "No records found to show", "sGroupActions": "_TOTAL_ records selected: ", "sAjaxRequestGeneralError": "Could not complete request. Please check your internet connection", "sEmptyTable": "No data available in table", "sZeroRecords": "No matching records found", "oPaginate": { "sPrevious": "Prev", "sNext": "Next", "sPage": "Page", "sPageOf": "of" } }, "aoColumnDefs" : [{ // define columns sorting options(by default all columns are sortable extept the first checkbox column) 'bSortable' : false, 'aTargets' : [ 0 ] }], "bAutoWidth": false, // disable fixed width and enable fluid table "bSortCellsTop": true, // make sortable only the first row in thead "sPaginationType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended) "bProcessing": true, // enable/disable display message box on record load "bServerSide": true, // enable/disable server side ajax loading "sAjaxSource": "", // define ajax source URL "sServerMethod": "POST", // handle ajax request "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "dataType": 'json', "type": "POST", "url": sSource, "data": aoData, "success": function(res, textStatus, jqXHR) { if (res.sMessage) { Metronic.alert({type: (res.sStatus == 'OK' ? 'success' : 'danger'), icon: (res.sStatus == 'OK' ? 'check' : 'warning'), message: res.sMessage, container: tableWrapper, place: 'prepend'}); } if (res.sStatus) { if (tableOptions.resetGroupActionInputOnSuccess) { $('.table-group-action-input', tableWrapper).val(""); } } if ($('.group-checkable', table).size() === 1) { $('.group-checkable', table).attr("checked", false); $.uniform.update($('.group-checkable', table)); } if (tableOptions.onSuccess) { tableOptions.onSuccess.call(undefined, the); } fnCallback(res, textStatus, jqXHR); <|fim▁hole|> }, "error": function() { if (tableOptions.onError) { tableOptions.onError.call(undefined, the); } Metronic.alert({type: 'danger', icon: 'warning', message: tableOptions.dataTable.oLanguage.sAjaxRequestGeneralError, container: tableWrapper, place: 'prepend'}); $('.dataTables_processing', tableWrapper).remove(); } } ); }, // pass additional parameter "fnServerParams": function ( aoData ) { //here can be added an external ajax request parameters. $.each(ajaxParams, function( key, value ) { aoData.push({"name" : key, "value": value}); }); }, "fnDrawCallback": function( oSettings ) { // run some code on table redraw if (tableInitialized === false) { // check if table has been initialized tableInitialized = true; // set table initialized table.show(); // display table } Metronic.initUniform($('input[type="checkbox"]', table)); // reinitialize uniform checkboxes on each table reload countSelectedRecords(); // reset selected records indicator } } }, options); tableOptions = options; // create table's jquery object table = $(options.src); tableContainer = table.parents(".table-container"); // apply the special class that used to restyle the default datatable $.fn.dataTableExt.oStdClasses.sWrapper = $.fn.dataTableExt.oStdClasses.sWrapper + " dataTables_extended_wrapper"; // initialize a datatable dataTable = table.dataTable(options.dataTable); tableWrapper = table.parents('.dataTables_wrapper'); // modify table per page dropdown input by appliying some classes $('.dataTables_length select', tableWrapper).addClass("form-control input-xsmall input-sm"); // build table group actions panel if ($('.table-actions-wrapper', tableContainer).size() === 1) { $('.table-group-actions', tableWrapper).html($('.table-actions-wrapper', tableContainer).html()); // place the panel inside the wrapper $('.table-actions-wrapper', tableContainer).remove(); // remove the template container } // handle group checkboxes check/uncheck $('.group-checkable', table).change(function () { var set = $('tbody > tr > td:nth-child(1) input[type="checkbox"]', table); var checked = $(this).is(":checked"); $(set).each(function () { $(this).attr("checked", checked); }); $.uniform.update(set); countSelectedRecords(); }); // handle row's checkbox click table.on('change', 'tbody > tr > td:nth-child(1) input[type="checkbox"]', function(){ countSelectedRecords(); }); // handle filter submit button click table.on('click', '.filter-submit', function(e){ e.preventDefault(); the.setAjaxParam("sAction", tableOptions.filterApplyAction); // get all typeable inputs $('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])', table).each(function(){ the.setAjaxParam($(this).attr("name"), $(this).val()); }); // get all checkable inputs $('input.form-filter[type="checkbox"]:checked, input.form-filter[type="radio"]:checked', table).each(function(){ the.setAjaxParam($(this).attr("name"), $(this).val()); }); dataTable.fnDraw(); }); // handle filter cancel button click table.on('click', '.filter-cancel', function(e){ e.preventDefault(); $('textarea.form-filter, select.form-filter, input.form-filter', table).each(function(){ $(this).val(""); }); $('input.form-filter[type="checkbox"]', table).each(function(){ $(this).attr("checked", false); }); the.clearAjaxParams(); the.setAjaxParam("sAction", tableOptions.filterCancelAction); dataTable.fnDraw(); }); }, getSelectedRowsCount: function() { return $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).size(); }, getSelectedRows: function() { var rows = []; $('tbody > tr > td:nth-child(1) input[type="checkbox"]:checked', table).each(function(){ rows.push({name: $(this).attr("name"), value: $(this).val()}); }); return rows; }, addAjaxParam: function(name, value) { ajaxParams[name] = value; }, setAjaxParam: function(name, value) { ajaxParams[name] = value; }, clearAjaxParams: function(name, value) { ajaxParams = []; }, getDataTable: function() { return dataTable; }, getTableWrapper: function() { return tableWrapper; }, gettableContainer: function() { return tableContainer; }, getTable: function() { return table; } }; };<|fim▁end|>
<|file_name|>path_encrypt_test.go<|end_file_name|><|fim▁begin|>package transit import ( "context" "testing" "github.com/hashicorp/vault/logical" "github.com/mitchellh/mapstructure" ) // Case1: Ensure that batch encryption did not affect the normal flow of // encrypting the plaintext with a pre-existing key. func TestTransit_BatchEncryptionCase1(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) // Create the policy policyReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "keys/existing_key", Storage: s, } resp, err = b.HandleRequest(context.Background(), policyReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" // "the quick brown fox" encData := map[string]interface{}{ "plaintext": plaintext, } encReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "encrypt/existing_key", Storage: s, Data: encData, } resp, err = b.HandleRequest(context.Background(), encReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } ciphertext := resp.Data["ciphertext"] decData := map[string]interface{}{ "ciphertext": ciphertext, } decReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "decrypt/existing_key", Storage: s, Data: decData,<|fim▁hole|> if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } if resp.Data["plaintext"] != plaintext { t.Fatalf("bad: plaintext. Expected: %q, Actual: %q", plaintext, resp.Data["plaintext"]) } } // Case2: Ensure that batch encryption did not affect the normal flow of // encrypting the plaintext with the key upserted. func TestTransit_BatchEncryptionCase2(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) // Upsert the key and encrypt the data plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" encData := map[string]interface{}{ "plaintext": plaintext, } encReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: encData, } resp, err = b.HandleRequest(context.Background(), encReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } ciphertext := resp.Data["ciphertext"] decData := map[string]interface{}{ "ciphertext": ciphertext, } policyReq := &logical.Request{ Operation: logical.ReadOperation, Path: "keys/upserted_key", Storage: s, } resp, err = b.HandleRequest(context.Background(), policyReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } decReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "decrypt/upserted_key", Storage: s, Data: decData, } resp, err = b.HandleRequest(context.Background(), decReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } if resp.Data["plaintext"] != plaintext { t.Fatalf("bad: plaintext. Expected: %q, Actual: %q", plaintext, resp.Data["plaintext"]) } } // Case3: If batch encryption input is not base64 encoded, it should fail. func TestTransit_BatchEncryptionCase3(t *testing.T) { var err error b, s := createBackendWithStorage(t) batchInput := `[{"plaintext":"dGhlIHF1aWNrIGJyb3duIGZveA=="}]` batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } _, err = b.HandleRequest(context.Background(), batchReq) if err == nil { t.Fatal("expected an error") } } // Case4: Test batch encryption with an existing key func TestTransit_BatchEncryptionCase4(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) policyReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "keys/existing_key", Storage: s, } resp, err = b.HandleRequest(context.Background(), policyReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "encrypt/existing_key", Storage: s, Data: batchData, } resp, err = b.HandleRequest(context.Background(), batchReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchResponseItems := resp.Data["batch_results"].([]BatchResponseItem) decReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "decrypt/existing_key", Storage: s, } plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" for _, item := range batchResponseItems { decReq.Data = map[string]interface{}{ "ciphertext": item.Ciphertext, } resp, err = b.HandleRequest(context.Background(), decReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } if resp.Data["plaintext"] != plaintext { t.Fatalf("bad: plaintext. Expected: %q, Actual: %q", plaintext, resp.Data["plaintext"]) } } } // Case5: Test batch encryption with an existing derived key func TestTransit_BatchEncryptionCase5(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) policyData := map[string]interface{}{ "derived": true, } policyReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "keys/existing_key", Storage: s, Data: policyData, } resp, err = b.HandleRequest(context.Background(), policyReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "dmlzaGFsCg=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "dmlzaGFsCg=="}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "encrypt/existing_key", Storage: s, Data: batchData, } resp, err = b.HandleRequest(context.Background(), batchReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchResponseItems := resp.Data["batch_results"].([]BatchResponseItem) decReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "decrypt/existing_key", Storage: s, } plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" for _, item := range batchResponseItems { decReq.Data = map[string]interface{}{ "ciphertext": item.Ciphertext, "context": "dmlzaGFsCg==", } resp, err = b.HandleRequest(context.Background(), decReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } if resp.Data["plaintext"] != plaintext { t.Fatalf("bad: plaintext. Expected: %q, Actual: %q", plaintext, resp.Data["plaintext"]) } } } // Case6: Test batch encryption with an upserted non-derived key func TestTransit_BatchEncryptionCase6(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } resp, err = b.HandleRequest(context.Background(), batchReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchResponseItems := resp.Data["batch_results"].([]BatchResponseItem) decReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "decrypt/upserted_key", Storage: s, } plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" for _, responseItem := range batchResponseItems { var item BatchResponseItem if err := mapstructure.Decode(responseItem, &item); err != nil { t.Fatal(err) } decReq.Data = map[string]interface{}{ "ciphertext": item.Ciphertext, } resp, err = b.HandleRequest(context.Background(), decReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } if resp.Data["plaintext"] != plaintext { t.Fatalf("bad: plaintext. Expected: %q, Actual: %q", plaintext, resp.Data["plaintext"]) } } } // Case7: Test batch encryption with an upserted derived key func TestTransit_BatchEncryptionCase7(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "dmlzaGFsCg=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "dmlzaGFsCg=="}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } resp, err = b.HandleRequest(context.Background(), batchReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchResponseItems := resp.Data["batch_results"].([]BatchResponseItem) decReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "decrypt/upserted_key", Storage: s, } plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" for _, item := range batchResponseItems { decReq.Data = map[string]interface{}{ "ciphertext": item.Ciphertext, "context": "dmlzaGFsCg==", } resp, err = b.HandleRequest(context.Background(), decReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } if resp.Data["plaintext"] != plaintext { t.Fatalf("bad: plaintext. Expected: %q, Actual: %q", plaintext, resp.Data["plaintext"]) } } } // Case8: If plaintext is not base64 encoded, encryption should fail func TestTransit_BatchEncryptionCase8(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) // Create the policy policyReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "keys/existing_key", Storage: s, } resp, err = b.HandleRequest(context.Background(), policyReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } batchInput := []interface{}{ map[string]interface{}{"plaintext": "simple_plaintext"}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "encrypt/existing_key", Storage: s, Data: batchData, } resp, err = b.HandleRequest(context.Background(), batchReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } plaintext := "simple plaintext" encData := map[string]interface{}{ "plaintext": plaintext, } encReq := &logical.Request{ Operation: logical.UpdateOperation, Path: "encrypt/existing_key", Storage: s, Data: encData, } resp, err = b.HandleRequest(context.Background(), encReq) if err == nil { t.Fatal("expected an error") } } // Case9: If both plaintext and batch inputs are supplied, plaintext should be // ignored. func TestTransit_BatchEncryptionCase9(t *testing.T) { var resp *logical.Response var err error b, s := createBackendWithStorage(t) batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, } plaintext := "dGhlIHF1aWNrIGJyb3duIGZveA==" batchData := map[string]interface{}{ "batch_input": batchInput, "plaintext": plaintext, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } resp, err = b.HandleRequest(context.Background(), batchReq) if err != nil || (resp != nil && resp.IsError()) { t.Fatalf("err:%v resp:%#v", err, resp) } _, ok := resp.Data["ciphertext"] if ok { t.Fatal("ciphertext field should not be set") } } // Case10: Inconsistent presence of 'context' in batch input should be caught func TestTransit_BatchEncryptionCase10(t *testing.T) { var err error b, s := createBackendWithStorage(t) batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "dmlzaGFsCg=="}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } _, err = b.HandleRequest(context.Background(), batchReq) if err == nil { t.Fatalf("expected an error") } } // Case11: Incorrect inputs for context and nonce should not fail the operation func TestTransit_BatchEncryptionCase11(t *testing.T) { var err error b, s := createBackendWithStorage(t) batchInput := []interface{}{ map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "dmlzaGFsCg=="}, map[string]interface{}{"plaintext": "dGhlIHF1aWNrIGJyb3duIGZveA==", "context": "not-encoded"}, } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } _, err = b.HandleRequest(context.Background(), batchReq) if err != nil { t.Fatal(err) } } // Case12: Invalid batch input func TestTransit_BatchEncryptionCase12(t *testing.T) { var err error b, s := createBackendWithStorage(t) batchInput := []interface{}{ map[string]interface{}{}, "unexpected_interface", } batchData := map[string]interface{}{ "batch_input": batchInput, } batchReq := &logical.Request{ Operation: logical.CreateOperation, Path: "encrypt/upserted_key", Storage: s, Data: batchData, } _, err = b.HandleRequest(context.Background(), batchReq) if err == nil { t.Fatalf("expected an error") } }<|fim▁end|>
} resp, err = b.HandleRequest(context.Background(), decReq)
<|file_name|>feed_parse_extractNotoriousOnlineBlogspotCom.py<|end_file_name|><|fim▁begin|>def extractNotoriousOnlineBlogspotCom(item): ''' Parser for 'notorious-online.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)<|fim▁hole|><|fim▁end|>
return False
<|file_name|>leaflet.js<|end_file_name|><|fim▁begin|>/* @preserve * Leaflet 1.6.0+Detached: 0c81bdf904d864fd12a286e3d1979f47aba17991.0c81bdf, a JS library for interactive maps. http://leafletjs.com * (c) 2010-2019 Vladimir Agafonkin, (c) 2010-2011 CloudMade */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.L = {}))); }(this, (function (exports) { 'use strict'; var version = "1.6.0+HEAD.0c81bdf"; /* * @namespace Util * * Various utility functions, used by Leaflet internally. */ var freeze = Object.freeze; Object.freeze = function (obj) { return obj; }; // @function extend(dest: Object, src?: Object): Object // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut. function extend(dest) { var i, j, len, src; for (j = 1, len = arguments.length; j < len; j++) { src = arguments[j]; for (i in src) { dest[i] = src[i]; } } return dest; } // @function create(proto: Object, properties?: Object): Object // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create) var create = Object.create || (function () { function F() {} return function (proto) { F.prototype = proto; return new F(); }; })(); // @function bind(fn: Function, …): Function // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). // Has a `L.bind()` shortcut. function bind(fn, obj) { var slice = Array.prototype.slice; if (fn.bind) { return fn.bind.apply(fn, slice.call(arguments, 1)); } var args = slice.call(arguments, 2); return function () { return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments); }; } // @property lastId: Number // Last unique ID used by [`stamp()`](#util-stamp) var lastId = 0; // @function stamp(obj: Object): Number // Returns the unique ID of an object, assigning it one if it doesn't have it. function stamp(obj) { /*eslint-disable */ obj._leaflet_id = obj._leaflet_id || ++lastId; return obj._leaflet_id; /* eslint-enable */ } // @function throttle(fn: Function, time: Number, context: Object): Function // Returns a function which executes function `fn` with the given scope `context` // (so that the `this` keyword refers to `context` inside `fn`'s code). The function // `fn` will be called no more than one time per given amount of `time`. The arguments // received by the bound function will be any arguments passed when binding the // function, followed by any arguments passed when invoking the bound function. // Has an `L.throttle` shortcut. function throttle(fn, time, context) { var lock, args, wrapperFn, later; later = function () { // reset lock and call if queued lock = false; if (args) { wrapperFn.apply(context, args); args = false; } }; wrapperFn = function () { if (lock) { // called too soon, queue to call later args = arguments; } else { // call and lock until later fn.apply(context, arguments); setTimeout(later, time); lock = true; } }; return wrapperFn; } // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number // Returns the number `num` modulo `range` in such a way so it lies within // `range[0]` and `range[1]`. The returned value will be always smaller than // `range[1]` unless `includeMax` is set to `true`. function wrapNum(x, range, includeMax) { var max = range[1], min = range[0], d = max - min; return x === max && includeMax ? x : ((x - min) % d + d) % d + min; } // @function falseFn(): Function // Returns a function which always returns `false`. function falseFn() { return false; } // @function formatNum(num: Number, digits?: Number): Number // Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default. function formatNum(num, digits) { var pow = Math.pow(10, (digits === undefined ? 6 : digits)); return Math.round(num * pow) / pow; } // @function trim(str: String): String // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) function trim(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } // @function splitWords(str: String): String[] // Trims and splits the string on whitespace and returns the array of parts. function splitWords(str) { return trim(str).split(/\s+/); } // @function setOptions(obj: Object, options: Object): Object // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut. function setOptions(obj, options) { if (!obj.hasOwnProperty('options')) { obj.options = obj.options ? create(obj.options) : {}; } for (var i in options) { obj.options[i] = options[i]; } return obj.options; } // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}` // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will // be appended at the end. If `uppercase` is `true`, the parameter names will // be uppercased (e.g. `'?A=foo&B=bar'`) function getParamString(obj, existingUrl, uppercase) { var params = []; for (var i in obj) { params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i])); } return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&'); } var templateRe = /\{ *([\w_-]+) *\}/g; // @function template(str: String, data: Object): String // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'` // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string // `('Hello foo, bar')`. You can also specify functions instead of strings for // data values — they will be evaluated passing `data` as an argument. function template(str, data) { return str.replace(templateRe, function (str, key) { var value = data[key]; if (value === undefined) { throw new Error('No value provided for variable ' + str); } else if (typeof value === 'function') { value = value(data); } return value; }); } // @function isArray(obj): Boolean // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) var isArray = Array.isArray || function (obj) { return (Object.prototype.toString.call(obj) === '[object Array]'); }; // @function indexOf(array: Array, el: Object): Number // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) function indexOf(array, el) { for (var i = 0; i < array.length; i++) { if (array[i] === el) { return i; } } return -1; } // @property emptyImageUrl: String // Data URI string containing a base64-encoded empty GIF image. // Used as a hack to free memory from unused images on WebKit-powered // mobile devices (by setting image `src` to this string). var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/ function getPrefixed(name) { return window['webkit' + name] || window['moz' + name] || window['ms' + name]; } var lastTime = 0; // fallback for IE 7-8 function timeoutDefer(fn) { var time = +new Date(), timeToCall = Math.max(0, 16 - (time - lastTime)); lastTime = time + timeToCall; return window.setTimeout(fn, timeToCall); } var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer; var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') || getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); }; // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number // Schedules `fn` to be executed when the browser repaints. `fn` is bound to // `context` if given. When `immediate` is set, `fn` is called immediately if // the browser doesn't have native support for // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame), // otherwise it's delayed. Returns a request ID that can be used to cancel the request. function requestAnimFrame(fn, context, immediate) { if (immediate && requestFn === timeoutDefer) { fn.call(context); } else { return requestFn.call(window, bind(fn, context)); } } // @function cancelAnimFrame(id: Number): undefined // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame). function cancelAnimFrame(id) { if (id) { cancelFn.call(window, id); } } var Util = (Object.freeze || Object)({ freeze: freeze, extend: extend, create: create, bind: bind, lastId: lastId, stamp: stamp, throttle: throttle, wrapNum: wrapNum, falseFn: falseFn, formatNum: formatNum, trim: trim, splitWords: splitWords, setOptions: setOptions, getParamString: getParamString, template: template, isArray: isArray, indexOf: indexOf, emptyImageUrl: emptyImageUrl, requestFn: requestFn, cancelFn: cancelFn, requestAnimFrame: requestAnimFrame, cancelAnimFrame: cancelAnimFrame }); // @class Class // @aka L.Class // @section // @uninheritable // Thanks to John Resig and Dean Edwards for inspiration! function Class() {} Class.extend = function (props) { // @function extend(props: Object): Function // [Extends the current class](#class-inheritance) given the properties to be included. // Returns a Javascript function that is a class constructor (to be called with `new`). var NewClass = function () { // call the constructor if (this.initialize) { this.initialize.apply(this, arguments); } // call all constructor hooks this.callInitHooks(); }; var parentProto = NewClass.__super__ = this.prototype; var proto = create(parentProto); proto.constructor = NewClass; NewClass.prototype = proto; // inherit parent's statics for (var i in this) { if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') { NewClass[i] = this[i]; } } // mix static properties into the class if (props.statics) { extend(NewClass, props.statics); delete props.statics; } // mix includes into the prototype if (props.includes) { checkDeprecatedMixinEvents(props.includes); extend.apply(null, [proto].concat(props.includes)); delete props.includes; } // merge options if (proto.options) { props.options = extend(create(proto.options), props.options); } // mix given properties into the prototype extend(proto, props); proto._initHooks = []; // add method for calling all hooks proto.callInitHooks = function () { if (this._initHooksCalled) { return; } if (parentProto.callInitHooks) { parentProto.callInitHooks.call(this); } this._initHooksCalled = true; for (var i = 0, len = proto._initHooks.length; i < len; i++) { proto._initHooks[i].call(this); } }; return NewClass; }; // @function include(properties: Object): this // [Includes a mixin](#class-includes) into the current class. Class.include = function (props) { extend(this.prototype, props); return this; }; // @function mergeOptions(options: Object): this // [Merges `options`](#class-options) into the defaults of the class. Class.mergeOptions = function (options) { extend(this.prototype.options, options); return this; }; // @function addInitHook(fn: Function): this // Adds a [constructor hook](#class-constructor-hooks) to the class. Class.addInitHook = function (fn) { // (Function) || (String, args...) var args = Array.prototype.slice.call(arguments, 1); var init = typeof fn === 'function' ? fn : function () { this[fn].apply(this, args); }; this.prototype._initHooks = this.prototype._initHooks || []; this.prototype._initHooks.push(init); return this; }; function checkDeprecatedMixinEvents(includes) { if (typeof L === 'undefined' || !L || !L.Mixin) { return; } includes = isArray(includes) ? includes : [includes]; for (var i = 0; i < includes.length; i++) { if (includes[i] === L.Mixin.Events) { console.warn('Deprecated include of L.Mixin.Events: ' + 'this property will be removed in future releases, ' + 'please inherit from L.Evented instead.', new Error().stack); } } } /* * @class Evented * @aka L.Evented * @inherits Class * * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event). * * @example * * ```js * map.on('click', function(e) { * alert(e.latlng); * } ); * ``` * * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function: * * ```js * function onClick(e) { ... } * * map.on('click', onClick); * map.off('click', onClick); * ``` */ var Events = { /* @method on(type: String, fn: Function, context?: Object): this * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). * * @alternative * @method on(eventMap: Object): this * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` */ on: function (types, fn, context) { // types can be a map of types/handlers if (typeof types === 'object') { for (var type in types) { // we don't process space-separated events here for performance; // it's a hot path since Layer uses the on(obj) syntax this._on(type, types[type], fn); } } else { // types can be a string of space-separated words types = splitWords(types); for (var i = 0, len = types.length; i < len; i++) { this._on(types[i], fn, context); } } return this; }, /* @method off(type: String, fn?: Function, context?: Object): this * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. * * @alternative * @method off(eventMap: Object): this * Removes a set of type/listener pairs. * * @alternative * @method off: this * Removes all listeners to all events on the object. This includes implicitly attached events. */ off: function (types, fn, context) { if (!types) { // clear all listeners if called without arguments delete this._events; } else if (typeof types === 'object') { for (var type in types) { this._off(type, types[type], fn); } } else { types = splitWords(types); for (var i = 0, len = types.length; i < len; i++) { this._off(types[i], fn, context); } } return this; }, // attach listener (without syntactic sugar now) _on: function (type, fn, context) { this._events = this._events || {}; /* get/init listeners for type */ var typeListeners = this._events[type]; if (!typeListeners) { typeListeners = []; this._events[type] = typeListeners; } if (context === this) { // Less memory footprint. context = undefined; } var newListener = {fn: fn, ctx: context}, listeners = typeListeners; // check if fn already there for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i].fn === fn && listeners[i].ctx === context) { return; } } listeners.push(newListener); }, _off: function (type, fn, context) { var listeners, i, len; if (!this._events) { return; } listeners = this._events[type]; if (!listeners) { return; } if (!fn) { // Set all removed listeners to noop so they are not called if remove happens in fire for (i = 0, len = listeners.length; i < len; i++) { listeners[i].fn = falseFn; } // clear all listeners for a type if function isn't specified delete this._events[type]; return; } if (context === this) { context = undefined; } if (listeners) { // find fn and remove it for (i = 0, len = listeners.length; i < len; i++) { var l = listeners[i]; if (l.ctx !== context) { continue; } if (l.fn === fn) { // set the removed listener to noop so that's not called if remove happens in fire l.fn = falseFn; if (this._firingCount) { /* copy array in case events are being fired */ this._events[type] = listeners = listeners.slice(); } listeners.splice(i, 1); return; } } } }, // @method fire(type: String, data?: Object, propagate?: Boolean): this // Fires an event of the specified type. You can optionally provide an data // object — the first argument of the listener function will contain its // properties. The event can optionally be propagated to event parents. fire: function (type, data, propagate) { if (!this.listens(type, propagate)) { return this; } var event = extend({}, data, { type: type, target: this, sourceTarget: data && data.sourceTarget || this }); if (this._events) { var listeners = this._events[type]; if (listeners) { this._firingCount = (this._firingCount + 1) || 1; for (var i = 0, len = listeners.length; i < len; i++) { var l = listeners[i]; l.fn.call(l.ctx || this, event); } this._firingCount--; } } if (propagate) { // propagate the event to parents (set with addEventParent) this._propagateEvent(event); } return this; }, // @method listens(type: String): Boolean // Returns `true` if a particular event type has any listeners attached to it. listens: function (type, propagate) { var listeners = this._events && this._events[type]; if (listeners && listeners.length) { return true; } if (propagate) { // also check parents for listeners if event propagates for (var id in this._eventParents) { if (this._eventParents[id].listens(type, propagate)) { return true; } } } return false; }, // @method once(…): this // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. once: function (types, fn, context) { if (typeof types === 'object') { for (var type in types) { this.once(type, types[type], fn); } return this; } var handler = bind(function () { this .off(types, fn, context) .off(types, handler, context); }, this); // add a listener that's executed once and removed after that return this .on(types, fn, context) .on(types, handler, context); }, // @method addEventParent(obj: Evented): this // Adds an event parent - an `Evented` that will receive propagated events addEventParent: function (obj) { this._eventParents = this._eventParents || {}; this._eventParents[stamp(obj)] = obj; return this; }, // @method removeEventParent(obj: Evented): this // Removes an event parent, so it will stop receiving propagated events removeEventParent: function (obj) { if (this._eventParents) { delete this._eventParents[stamp(obj)]; } return this; }, _propagateEvent: function (e) { for (var id in this._eventParents) { this._eventParents[id].fire(e.type, extend({ layer: e.target, propagatedFrom: e.target }, e), true); } } }; // aliases; we should ditch those eventually // @method addEventListener(…): this // Alias to [`on(…)`](#evented-on) Events.addEventListener = Events.on; // @method removeEventListener(…): this // Alias to [`off(…)`](#evented-off) // @method clearAllEventListeners(…): this // Alias to [`off()`](#evented-off) Events.removeEventListener = Events.clearAllEventListeners = Events.off; // @method addOneTimeEventListener(…): this // Alias to [`once(…)`](#evented-once) Events.addOneTimeEventListener = Events.once; // @method fireEvent(…): this // Alias to [`fire(…)`](#evented-fire) Events.fireEvent = Events.fire; // @method hasEventListeners(…): Boolean // Alias to [`listens(…)`](#evented-listens) Events.hasEventListeners = Events.listens; var Evented = Class.extend(Events); /* * @class Point * @aka L.Point * * Represents a point with `x` and `y` coordinates in pixels. * * @example * * ```js * var point = L.point(200, 300); * ``` * * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent: * * ```js * map.panBy([200, 300]); * map.panBy(L.point(200, 300)); * ``` * * Note that `Point` does not inherit from Leafet's `Class` object, * which means new classes can't inherit from it, and new methods * can't be added to it with the `include` function. */ function Point(x, y, round) { // @property x: Number; The `x` coordinate of the point this.x = (round ? Math.round(x) : x); // @property y: Number; The `y` coordinate of the point this.y = (round ? Math.round(y) : y); } var trunc = Math.trunc || function (v) { return v > 0 ? Math.floor(v) : Math.ceil(v); }; Point.prototype = { // @method clone(): Point // Returns a copy of the current point. clone: function () { return new Point(this.x, this.y); }, // @method add(otherPoint: Point): Point // Returns the result of addition of the current and the given points. add: function (point) { // non-destructive, returns a new point return this.clone()._add(toPoint(point)); }, _add: function (point) { // destructive, used directly for performance in situations where it's safe to modify existing point this.x += point.x; this.y += point.y; return this; }, // @method subtract(otherPoint: Point): Point // Returns the result of subtraction of the given point from the current. subtract: function (point) { return this.clone()._subtract(toPoint(point)); }, _subtract: function (point) { this.x -= point.x; this.y -= point.y; return this; }, // @method divideBy(num: Number): Point // Returns the result of division of the current point by the given number. divideBy: function (num) { return this.clone()._divideBy(num); }, _divideBy: function (num) { this.x /= num; this.y /= num; return this; }, // @method multiplyBy(num: Number): Point // Returns the result of multiplication of the current point by the given number. multiplyBy: function (num) { return this.clone()._multiplyBy(num); }, _multiplyBy: function (num) { this.x *= num; this.y *= num; return this; }, // @method scaleBy(scale: Point): Point // Multiply each coordinate of the current point by each coordinate of // `scale`. In linear algebra terms, multiply the point by the // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation) // defined by `scale`. scaleBy: function (point) { return new Point(this.x * point.x, this.y * point.y); }, // @method unscaleBy(scale: Point): Point // Inverse of `scaleBy`. Divide each coordinate of the current point by // each coordinate of `scale`. unscaleBy: function (point) { return new Point(this.x / point.x, this.y / point.y); }, // @method round(): Point // Returns a copy of the current point with rounded coordinates. round: function () { return this.clone()._round(); }, _round: function () { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; }, // @method floor(): Point // Returns a copy of the current point with floored coordinates (rounded down). floor: function () { return this.clone()._floor(); }, _floor: function () { this.x = Math.floor(this.x); this.y = Math.floor(this.y); return this; }, // @method ceil(): Point // Returns a copy of the current point with ceiled coordinates (rounded up). ceil: function () { return this.clone()._ceil(); }, _ceil: function () { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); return this; }, // @method trunc(): Point // Returns a copy of the current point with truncated coordinates (rounded towards zero). trunc: function () { return this.clone()._trunc(); }, _trunc: function () { this.x = trunc(this.x); this.y = trunc(this.y); return this; }, // @method distanceTo(otherPoint: Point): Number // Returns the cartesian distance between the current and the given points. distanceTo: function (point) { point = toPoint(point); var x = point.x - this.x, y = point.y - this.y; return Math.sqrt(x * x + y * y); }, // @method equals(otherPoint: Point): Boolean // Returns `true` if the given point has the same coordinates. equals: function (point) { point = toPoint(point); return point.x === this.x && point.y === this.y; }, // @method contains(otherPoint: Point): Boolean // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values). contains: function (point) { point = toPoint(point); return Math.abs(point.x) <= Math.abs(this.x) && Math.abs(point.y) <= Math.abs(this.y); }, // @method toString(): String // Returns a string representation of the point for debugging purposes. toString: function () { return 'Point(' + formatNum(this.x) + ', ' + formatNum(this.y) + ')'; } }; // @factory L.point(x: Number, y: Number, round?: Boolean) // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values. // @alternative // @factory L.point(coords: Number[]) // Expects an array of the form `[x, y]` instead. // @alternative // @factory L.point(coords: Object) // Expects a plain object of the form `{x: Number, y: Number}` instead. function toPoint(x, y, round) { if (x instanceof Point) { return x; } if (isArray(x)) { return new Point(x[0], x[1]); } if (x === undefined || x === null) { return x; } if (typeof x === 'object' && 'x' in x && 'y' in x) { return new Point(x.x, x.y); } return new Point(x, y, round); } /* * @class Bounds * @aka L.Bounds * * Represents a rectangular area in pixel coordinates. * * @example * * ```js * var p1 = L.point(10, 10), * p2 = L.point(40, 60), * bounds = L.bounds(p1, p2); * ``` * * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this: * * ```js * otherBounds.intersects([[10, 10], [40, 60]]); * ``` * * Note that `Bounds` does not inherit from Leafet's `Class` object, * which means new classes can't inherit from it, and new methods * can't be added to it with the `include` function. */ function Bounds(a, b) { if (!a) { return; } var points = b ? [a, b] : a; for (var i = 0, len = points.length; i < len; i++) { this.extend(points[i]); } } Bounds.prototype = { // @method extend(point: Point): this // Extends the bounds to contain the given point. extend: function (point) { // (Point) point = toPoint(point); // @property min: Point // The top left corner of the rectangle. // @property max: Point // The bottom right corner of the rectangle. if (!this.min && !this.max) { this.min = point.clone(); this.max = point.clone(); } else { this.min.x = Math.min(point.x, this.min.x); this.max.x = Math.max(point.x, this.max.x); this.min.y = Math.min(point.y, this.min.y); this.max.y = Math.max(point.y, this.max.y); } return this; }, // @method getCenter(round?: Boolean): Point // Returns the center point of the bounds. getCenter: function (round) { return new Point( (this.min.x + this.max.x) / 2, (this.min.y + this.max.y) / 2, round); }, // @method getBottomLeft(): Point // Returns the bottom-left point of the bounds. getBottomLeft: function () { return new Point(this.min.x, this.max.y); }, // @method getTopRight(): Point // Returns the top-right point of the bounds. getTopRight: function () { // -> Point return new Point(this.max.x, this.min.y); }, // @method getTopLeft(): Point // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)). getTopLeft: function () { return this.min; // left, top }, // @method getBottomRight(): Point // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)). getBottomRight: function () { return this.max; // right, bottom }, // @method getSize(): Point // Returns the size of the given bounds getSize: function () { return this.max.subtract(this.min); }, // @method contains(otherBounds: Bounds): Boolean // Returns `true` if the rectangle contains the given one. // @alternative // @method contains(point: Point): Boolean // Returns `true` if the rectangle contains the given point. contains: function (obj) { var min, max; if (typeof obj[0] === 'number' || obj instanceof Point) { obj = toPoint(obj); } else { obj = toBounds(obj); } if (obj instanceof Bounds) { min = obj.min; max = obj.max; } else { min = max = obj; } return (min.x >= this.min.x) && (max.x <= this.max.x) && (min.y >= this.min.y) && (max.y <= this.max.y); }, // @method intersects(otherBounds: Bounds): Boolean // Returns `true` if the rectangle intersects the given bounds. Two bounds // intersect if they have at least one point in common. intersects: function (bounds) { // (Bounds) -> Boolean bounds = toBounds(bounds); var min = this.min, max = this.max, min2 = bounds.min, max2 = bounds.max, xIntersects = (max2.x >= min.x) && (min2.x <= max.x), yIntersects = (max2.y >= min.y) && (min2.y <= max.y); return xIntersects && yIntersects; }, // @method overlaps(otherBounds: Bounds): Boolean // Returns `true` if the rectangle overlaps the given bounds. Two bounds // overlap if their intersection is an area. overlaps: function (bounds) { // (Bounds) -> Boolean bounds = toBounds(bounds); var min = this.min, max = this.max, min2 = bounds.min, max2 = bounds.max, xOverlaps = (max2.x > min.x) && (min2.x < max.x), yOverlaps = (max2.y > min.y) && (min2.y < max.y); return xOverlaps && yOverlaps; }, isValid: function () { return !!(this.min && this.max); } }; // @factory L.bounds(corner1: Point, corner2: Point) // Creates a Bounds object from two corners coordinate pairs. // @alternative // @factory L.bounds(points: Point[]) // Creates a Bounds object from the given array of points. function toBounds(a, b) { if (!a || a instanceof Bounds) { return a; } return new Bounds(a, b); } /* * @class LatLngBounds * @aka L.LatLngBounds * * Represents a rectangular geographical area on a map. * * @example * * ```js * var corner1 = L.latLng(40.712, -74.227), * corner2 = L.latLng(40.774, -74.125), * bounds = L.latLngBounds(corner1, corner2); * ``` * * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this: * * ```js * map.fitBounds([ * [40.712, -74.227], * [40.774, -74.125] * ]); * ``` * * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range. * * Note that `LatLngBounds` does not inherit from Leafet's `Class` object, * which means new classes can't inherit from it, and new methods * can't be added to it with the `include` function. */ function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[]) if (!corner1) { return; } var latlngs = corner2 ? [corner1, corner2] : corner1; for (var i = 0, len = latlngs.length; i < len; i++) { this.extend(latlngs[i]); } } LatLngBounds.prototype = { // @method extend(latlng: LatLng): this // Extend the bounds to contain the given point // @alternative // @method extend(otherBounds: LatLngBounds): this // Extend the bounds to contain the given bounds extend: function (obj) { var sw = this._southWest, ne = this._northEast, sw2, ne2; if (obj instanceof LatLng) { sw2 = obj; ne2 = obj; } else if (obj instanceof LatLngBounds) { sw2 = obj._southWest; ne2 = obj._northEast; if (!sw2 || !ne2) { return this; } } else { return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this; } if (!sw && !ne) { this._southWest = new LatLng(sw2.lat, sw2.lng); this._northEast = new LatLng(ne2.lat, ne2.lng); } else { sw.lat = Math.min(sw2.lat, sw.lat); sw.lng = Math.min(sw2.lng, sw.lng); ne.lat = Math.max(ne2.lat, ne.lat); ne.lng = Math.max(ne2.lng, ne.lng); } return this; }, // @method pad(bufferRatio: Number): LatLngBounds // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction. // For example, a ratio of 0.5 extends the bounds by 50% in each direction. // Negative values will retract the bounds. pad: function (bufferRatio) { var sw = this._southWest, ne = this._northEast, heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio; return new LatLngBounds( new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer), new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)); }, // @method getCenter(): LatLng // Returns the center point of the bounds. getCenter: function () { return new LatLng( (this._southWest.lat + this._northEast.lat) / 2, (this._southWest.lng + this._northEast.lng) / 2); }, // @method getSouthWest(): LatLng // Returns the south-west point of the bounds. getSouthWest: function () { return this._southWest; }, // @method getNorthEast(): LatLng // Returns the north-east point of the bounds. getNorthEast: function () { return this._northEast; }, // @method getNorthWest(): LatLng // Returns the north-west point of the bounds. getNorthWest: function () { return new LatLng(this.getNorth(), this.getWest()); }, // @method getSouthEast(): LatLng // Returns the south-east point of the bounds. getSouthEast: function () { return new LatLng(this.getSouth(), this.getEast()); }, // @method getWest(): Number // Returns the west longitude of the bounds getWest: function () { return this._southWest.lng; }, // @method getSouth(): Number // Returns the south latitude of the bounds getSouth: function () { return this._southWest.lat; }, // @method getEast(): Number // Returns the east longitude of the bounds getEast: function () { return this._northEast.lng; }, // @method getNorth(): Number // Returns the north latitude of the bounds getNorth: function () { return this._northEast.lat; }, // @method contains(otherBounds: LatLngBounds): Boolean // Returns `true` if the rectangle contains the given one. // @alternative // @method contains (latlng: LatLng): Boolean // Returns `true` if the rectangle contains the given point. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) { obj = toLatLng(obj); } else { obj = toLatLngBounds(obj); } var sw = this._southWest, ne = this._northEast, sw2, ne2; if (obj instanceof LatLngBounds) { sw2 = obj.getSouthWest(); ne2 = obj.getNorthEast(); } else { sw2 = ne2 = obj; } return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) && (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng); }, // @method intersects(otherBounds: LatLngBounds): Boolean // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common. intersects: function (bounds) { bounds = toLatLngBounds(bounds); var sw = this._southWest, ne = this._northEast, sw2 = bounds.getSouthWest(), ne2 = bounds.getNorthEast(), latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat), lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng); return latIntersects && lngIntersects; }, // @method overlaps(otherBounds: Bounds): Boolean // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area. overlaps: function (bounds) { bounds = toLatLngBounds(bounds); var sw = this._southWest, ne = this._northEast, sw2 = bounds.getSouthWest(), ne2 = bounds.getNorthEast(), latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat), lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng); return latOverlaps && lngOverlaps; }, // @method toBBoxString(): String // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data. toBBoxString: function () { return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(','); }, // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number. equals: function (bounds, maxMargin) { if (!bounds) { return false; } bounds = toLatLngBounds(bounds); return this._southWest.equals(bounds.getSouthWest(), maxMargin) && this._northEast.equals(bounds.getNorthEast(), maxMargin); }, // @method isValid(): Boolean // Returns `true` if the bounds are properly initialized. isValid: function () { return !!(this._southWest && this._northEast); } }; // TODO International date line? // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng) // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle. // @alternative // @factory L.latLngBounds(latlngs: LatLng[]) // Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds). function toLatLngBounds(a, b) { if (a instanceof LatLngBounds) { return a; } return new LatLngBounds(a, b); } /* @class LatLng * @aka L.LatLng * * Represents a geographical point with a certain latitude and longitude. * * @example * * ``` * var latlng = L.latLng(50.5, 30.5); * ``` * * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent: * * ``` * map.panTo([50, 30]); * map.panTo({lon: 30, lat: 50}); * map.panTo({lat: 50, lng: 30}); * map.panTo(L.latLng(50, 30)); * ``` * * Note that `LatLng` does not inherit from Leaflet's `Class` object, * which means new classes can't inherit from it, and new methods * can't be added to it with the `include` function. */ function LatLng(lat, lng, alt) { if (isNaN(lat) || isNaN(lng)) { throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')'); } // @property lat: Number // Latitude in degrees this.lat = +lat; // @property lng: Number // Longitude in degrees this.lng = +lng; // @property alt: Number // Altitude in meters (optional) if (alt !== undefined) { this.alt = +alt; } } LatLng.prototype = { // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number. equals: function (obj, maxMargin) { if (!obj) { return false; } obj = toLatLng(obj); var margin = Math.max( Math.abs(this.lat - obj.lat), Math.abs(this.lng - obj.lng)); return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin); }, // @method toString(): String // Returns a string representation of the point (for debugging purposes). toString: function (precision) { return 'LatLng(' + formatNum(this.lat, precision) + ', ' + formatNum(this.lng, precision) + ')'; }, // @method distanceTo(otherLatLng: LatLng): Number // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines). distanceTo: function (other) { return Earth.distance(this, toLatLng(other)); }, // @method wrap(): LatLng // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees. wrap: function () { return Earth.wrapLatLng(this); }, // @method toBounds(sizeInMeters: Number): LatLngBounds // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`. toBounds: function (sizeInMeters) { var latAccuracy = 180 * sizeInMeters / 40075017, lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat); return toLatLngBounds( [this.lat - latAccuracy, this.lng - lngAccuracy], [this.lat + latAccuracy, this.lng + lngAccuracy]); }, clone: function () { return new LatLng(this.lat, this.lng, this.alt); } }; // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude). // @alternative // @factory L.latLng(coords: Array): LatLng // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead. // @alternative // @factory L.latLng(coords: Object): LatLng // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead. function toLatLng(a, b, c) { if (a instanceof LatLng) { return a; } if (isArray(a) && typeof a[0] !== 'object') { if (a.length === 3) { return new LatLng(a[0], a[1], a[2]); } if (a.length === 2) { return new LatLng(a[0], a[1]); } return null; } if (a === undefined || a === null) { return a; } if (typeof a === 'object' && 'lat' in a) { return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt); } if (b === undefined) { return null; } return new LatLng(a, b, c); } /* * @namespace CRS * @crs L.CRS.Base * Object that defines coordinate reference systems for projecting * geographical points into pixel (screen) coordinates and back (and to * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system). * * Leaflet defines the most usual CRSs by default. If you want to use a * CRS not defined by default, take a look at the * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin. * * Note that the CRS instances do not inherit from Leafet's `Class` object, * and can't be instantiated. Also, new classes can't inherit from them, * and methods can't be added to them with the `include` function. */ var CRS = { // @method latLngToPoint(latlng: LatLng, zoom: Number): Point // Projects geographical coordinates into pixel coordinates for a given zoom. latLngToPoint: function (latlng, zoom) { var projectedPoint = this.projection.project(latlng), scale = this.scale(zoom); return this.transformation._transform(projectedPoint, scale); }, // @method pointToLatLng(point: Point, zoom: Number): LatLng // The inverse of `latLngToPoint`. Projects pixel coordinates on a given // zoom into geographical coordinates. pointToLatLng: function (point, zoom) { var scale = this.scale(zoom), untransformedPoint = this.transformation.untransform(point, scale); return this.projection.unproject(untransformedPoint); }, // @method project(latlng: LatLng): Point // Projects geographical coordinates into coordinates in units accepted for // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). project: function (latlng) { return this.projection.project(latlng); }, // @method unproject(point: Point): LatLng // Given a projected coordinate returns the corresponding LatLng. // The inverse of `project`. unproject: function (point) { return this.projection.unproject(point); }, // @method scale(zoom: Number): Number // Returns the scale used when transforming projected coordinates into // pixel coordinates for a particular zoom. For example, it returns // `256 * 2^zoom` for Mercator-based CRS. scale: function (zoom) { return 256 * Math.pow(2, zoom); }, // @method zoom(scale: Number): Number // Inverse of `scale()`, returns the zoom level corresponding to a scale // factor of `scale`. zoom: function (scale) { return Math.log(scale / 256) / Math.LN2; }, // @method getProjectedBounds(zoom: Number): Bounds // Returns the projection's bounds scaled and transformed for the provided `zoom`. getProjectedBounds: function (zoom) { if (this.infinite) { return null; } var b = this.projection.bounds, s = this.scale(zoom), min = this.transformation.transform(b.min, s), max = this.transformation.transform(b.max, s); return new Bounds(min, max); }, // @method distance(latlng1: LatLng, latlng2: LatLng): Number // Returns the distance between two geographical coordinates. // @property code: String // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`) // // @property wrapLng: Number[] // An array of two numbers defining whether the longitude (horizontal) coordinate // axis wraps around a given range and how. Defaults to `[-180, 180]` in most // geographical CRSs. If `undefined`, the longitude axis does not wrap around. // // @property wrapLat: Number[] // Like `wrapLng`, but for the latitude (vertical) axis. // wrapLng: [min, max], // wrapLat: [min, max], // @property infinite: Boolean // If true, the coordinate space will be unbounded (infinite in both axes) infinite: false, // @method wrapLatLng(latlng: LatLng): LatLng // Returns a `LatLng` where lat and lng has been wrapped according to the // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds. wrapLatLng: function (latlng) { var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng, lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat, alt = latlng.alt; return new LatLng(lat, lng, alt); }, // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds // Returns a `LatLngBounds` with the same size as the given one, ensuring // that its center is within the CRS's bounds. // Only accepts actual `L.LatLngBounds` instances, not arrays. wrapLatLngBounds: function (bounds) { var center = bounds.getCenter(), newCenter = this.wrapLatLng(center), latShift = center.lat - newCenter.lat, lngShift = center.lng - newCenter.lng; if (latShift === 0 && lngShift === 0) { return bounds; } var sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift), newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift); return new LatLngBounds(newSw, newNe); } }; /* * @namespace CRS * @crs L.CRS.Earth * * Serves as the base for CRS that are global such that they cover the earth. * Can only be used as the base for other CRS and cannot be used directly, * since it does not have a `code`, `projection` or `transformation`. `distance()` returns * meters. */ var Earth = extend({}, CRS, { wrapLng: [-180, 180], // Mean Earth Radius, as recommended for use by // the International Union of Geodesy and Geophysics, // see http://rosettacode.org/wiki/Haversine_formula R: 6371000, // distance between two geographical points using spherical law of cosines approximation distance: function (latlng1, latlng2) { var rad = Math.PI / 180, lat1 = latlng1.lat * rad, lat2 = latlng2.lat * rad, sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2), sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2), a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return this.R * c; } }); /* * @namespace Projection * @projection L.Projection.SphericalMercator * * Spherical Mercator projection — the most common projection for online maps, * used by almost all free and commercial tile providers. Assumes that Earth is * a sphere. Used by the `EPSG:3857` CRS. */ var earthRadius = 6378137; var SphericalMercator = { R: earthRadius, MAX_LATITUDE: 85.0511287798, project: function (latlng) { var d = Math.PI / 180, max = this.MAX_LATITUDE, lat = Math.max(Math.min(max, latlng.lat), -max), sin = Math.sin(lat * d); return new Point( this.R * latlng.lng * d, this.R * Math.log((1 + sin) / (1 - sin)) / 2); }, unproject: function (point) { var d = 180 / Math.PI; return new LatLng( (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d, point.x * d / this.R); }, bounds: (function () { var d = earthRadius * Math.PI; return new Bounds([-d, -d], [d, d]); })() }; /* * @class Transformation * @aka L.Transformation * * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d` * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing * the reverse. Used by Leaflet in its projections code. * * @example * * ```js * var transformation = L.transformation(2, 5, -1, 10), * p = L.point(1, 2), * p2 = transformation.transform(p), // L.point(7, 8) * p3 = transformation.untransform(p2); // L.point(1, 2) * ``` */ // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number) // Creates a `Transformation` object with the given coefficients. function Transformation(a, b, c, d) { if (isArray(a)) { // use array properties this._a = a[0]; this._b = a[1]; this._c = a[2]; this._d = a[3]; return; } this._a = a; this._b = b; this._c = c; this._d = d; } Transformation.prototype = { // @method transform(point: Point, scale?: Number): Point // Returns a transformed point, optionally multiplied by the given scale. // Only accepts actual `L.Point` instances, not arrays. transform: function (point, scale) { // (Point, Number) -> Point return this._transform(point.clone(), scale); }, // destructive transform (faster) _transform: function (point, scale) { scale = scale || 1; point.x = scale * (this._a * point.x + this._b); point.y = scale * (this._c * point.y + this._d); return point; }, // @method untransform(point: Point, scale?: Number): Point // Returns the reverse transformation of the given point, optionally divided // by the given scale. Only accepts actual `L.Point` instances, not arrays. untransform: function (point, scale) { scale = scale || 1; return new Point( (point.x / scale - this._b) / this._a, (point.y / scale - this._d) / this._c); } }; // factory L.transformation(a: Number, b: Number, c: Number, d: Number) // @factory L.transformation(a: Number, b: Number, c: Number, d: Number) // Instantiates a Transformation object with the given coefficients. // @alternative // @factory L.transformation(coefficients: Array): Transformation // Expects an coefficients array of the form // `[a: Number, b: Number, c: Number, d: Number]`. function toTransformation(a, b, c, d) { return new Transformation(a, b, c, d); } /* * @namespace CRS * @crs L.CRS.EPSG3857 * * The most common CRS for online maps, used by almost all free and commercial * tile providers. Uses Spherical Mercator projection. Set in by default in * Map's `crs` option. */ var EPSG3857 = extend({}, Earth, { code: 'EPSG:3857', projection: SphericalMercator, transformation: (function () { var scale = 0.5 / (Math.PI * SphericalMercator.R); return toTransformation(scale, 0.5, -scale, 0.5); }()) }); var EPSG900913 = extend({}, EPSG3857, { code: 'EPSG:900913' }); // @namespace SVG; @section // There are several static functions which can be called without instantiating L.SVG: // @function create(name: String): SVGElement // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement), // corresponding to the class name passed. For example, using 'line' will return // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement). function svgCreate(name) { return document.createElementNS('http://www.w3.org/2000/svg', name); } // @function pointsToPath(rings: Point[], closed: Boolean): String // Generates a SVG path string for multiple rings, with each ring turning // into "M..L..L.." instructions function pointsToPath(rings, closed) { var str = '', i, j, len, len2, points, p; for (i = 0, len = rings.length; i < len; i++) { points = rings[i]; for (j = 0, len2 = points.length; j < len2; j++) { p = points[j]; str += (j ? 'L' : 'M') + p.x + ' ' + p.y; } // closes the ring for polygons; "x" is VML syntax str += closed ? (svg ? 'z' : 'x') : ''; } // SVG complains about empty path strings return str || 'M0 0'; } /* * @namespace Browser * @aka L.Browser * * A namespace with static properties for browser/feature detection used by Leaflet internally. * * @example * * ```js * if (L.Browser.ielt9) { * alert('Upgrade your browser, dude!'); * } * ``` */ var style$1 = document.documentElement.style; // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge). var ie = 'ActiveXObject' in window; // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9. var ielt9 = ie && !document.addEventListener; // @property edge: Boolean; `true` for the Edge web browser. var edge = 'msLaunchUri' in navigator && !('documentMode' in document); // @property webkit: Boolean; // `true` for webkit-based browsers like Chrome and Safari (including mobile versions). var webkit = userAgentContains('webkit'); // @property android: Boolean // `true` for any browser running on an Android platform. var android = userAgentContains('android'); // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3. var android23 = userAgentContains('android 2') || userAgentContains('android 3'); /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */ var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit // @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome) var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window); // @property opera: Boolean; `true` for the Opera browser var opera = !!window.opera; // @property chrome: Boolean; `true` for the Chrome browser. var chrome = userAgentContains('chrome'); // @property gecko: Boolean; `true` for gecko-based browsers like Firefox. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie; // @property safari: Boolean; `true` for the Safari browser. var safari = !chrome && userAgentContains('safari'); var phantom = userAgentContains('phantom'); // @property opera12: Boolean // `true` for the Opera browser supporting CSS transforms (version 12 or later). var opera12 = 'OTransition' in style$1; // @property win: Boolean; `true` when the browser is running in a Windows platform var win = navigator.platform.indexOf('Win') === 0; // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms. var ie3d = ie && ('transition' in style$1); // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23; // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms. var gecko3d = 'MozPerspective' in style$1; // @property any3d: Boolean // `true` for all browsers supporting CSS transforms. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom; // @property mobile: Boolean; `true` for all browsers running in a mobile device. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile'); // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device. var mobileWebkit = mobile && webkit; // @property mobileWebkit3d: Boolean // `true` for all webkit-based browsers in a mobile device supporting CSS transforms. var mobileWebkit3d = mobile && webkit3d; // @property msPointer: Boolean // `true` for browsers implementing the Microsoft touch events model (notably IE10). var msPointer = !window.PointerEvent && window.MSPointerEvent; // @property pointer: Boolean // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx). var pointer = !webkit && !!(window.PointerEvent || msPointer); // @property touch: Boolean // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events). // This does not necessarily mean that the browser is running in a computer with // a touchscreen, it only means that the browser is capable of understanding // touch events. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch)); // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device. var mobileOpera = mobile && opera; // @property mobileGecko: Boolean // `true` for gecko-based browsers running in a mobile device. var mobileGecko = mobile && gecko; // @property retina: Boolean // `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1; // @property passiveEvents: Boolean // `true` for browsers that support passive events. var passiveEvents = (function () { var supportsPassiveOption = false; try { var opts = Object.defineProperty({}, 'passive', { get: function () { supportsPassiveOption = true; } }); window.addEventListener('testPassiveEventSupport', falseFn, opts); window.removeEventListener('testPassiveEventSupport', falseFn, opts); } catch (e) { // Errors can safely be ignored since this is only a browser support test. } return supportsPassiveOption; }); // @property canvas: Boolean // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API). var canvas = (function () { return !!document.createElement('canvas').getContext; }()); // @property svg: Boolean // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG). var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect); // @property vml: Boolean // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language). var vml = !svg && (function () { try { var div = document.createElement('div'); div.innerHTML = '<v:shape adj="1"/>'; var shape = div.firstChild; shape.style.behavior = 'url(#default#VML)'; return shape && (typeof shape.adj === 'object'); } catch (e) { return false; } }()); function userAgentContains(str) { return navigator.userAgent.toLowerCase().indexOf(str) >= 0; } var Browser = (Object.freeze || Object)({ ie: ie, ielt9: ielt9, edge: edge, webkit: webkit, android: android, android23: android23, androidStock: androidStock, opera: opera, chrome: chrome, gecko: gecko, safari: safari, phantom: phantom, opera12: opera12, win: win, ie3d: ie3d, webkit3d: webkit3d, gecko3d: gecko3d, any3d: any3d, mobile: mobile, mobileWebkit: mobileWebkit, mobileWebkit3d: mobileWebkit3d, msPointer: msPointer, pointer: pointer, touch: touch, mobileOpera: mobileOpera, mobileGecko: mobileGecko, retina: retina, passiveEvents: passiveEvents, canvas: canvas, svg: svg, vml: vml }); /* * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices. */ var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown'; var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove'; var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup'; var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel'; var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION']; var _pointers = {}; var _pointerDocListener = false; // DomEvent.DoubleTap needs to know about this var _pointersCount = 0; // Provides a touch events wrapper for (ms)pointer events. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890 function addPointerListener(obj, type, handler, id) { if (type === 'touchstart') { _addPointerStart(obj, handler, id); } else if (type === 'touchmove') { _addPointerMove(obj, handler, id); } else if (type === 'touchend') { _addPointerEnd(obj, handler, id); } return this; } function removePointerListener(obj, type, id) { var handler = obj['_leaflet_' + type + id]; if (type === 'touchstart') { obj.removeEventListener(POINTER_DOWN, handler, false); } else if (type === 'touchmove') { obj.removeEventListener(POINTER_MOVE, handler, false); } else if (type === 'touchend') { obj.removeEventListener(POINTER_UP, handler, false); obj.removeEventListener(POINTER_CANCEL, handler, false); } return this; } function _addPointerStart(obj, handler, id) { var onDown = bind(function (e) { if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) { // In IE11, some touch events needs to fire for form controls, or // the controls will stop working. We keep a whitelist of tag names that // need these events. For other target tags, we prevent default on the event. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) { preventDefault(e); } else { return; } } _handlePointer(e, handler); }); obj['_leaflet_touchstart' + id] = onDown; obj.addEventListener(POINTER_DOWN, onDown, false); // need to keep track of what pointers and how many are active to provide e.touches emulation if (!_pointerDocListener) { // we listen documentElement as any drags that end by moving the touch off the screen get fired there document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true); document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true); document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true); document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true); _pointerDocListener = true; } } function _globalPointerDown(e) { _pointers[e.pointerId] = e; _pointersCount++; } function _globalPointerMove(e) { if (_pointers[e.pointerId]) { _pointers[e.pointerId] = e; } } function _globalPointerUp(e) { delete _pointers[e.pointerId]; _pointersCount--; } function _handlePointer(e, handler) { e.touches = []; for (var i in _pointers) { e.touches.push(_pointers[i]); } e.changedTouches = [e]; handler(e); } function _addPointerMove(obj, handler, id) { var onMove = function (e) { // don't fire touch moves when mouse isn't down if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; } _handlePointer(e, handler); }; obj['_leaflet_touchmove' + id] = onMove; obj.addEventListener(POINTER_MOVE, onMove, false); } function _addPointerEnd(obj, handler, id) { var onUp = function (e) { _handlePointer(e, handler); }; obj['_leaflet_touchend' + id] = onUp; obj.addEventListener(POINTER_UP, onUp, false); obj.addEventListener(POINTER_CANCEL, onUp, false); } /* * Extends the event handling code with double tap support for mobile browsers. */ var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart'; var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend'; var _pre = '_leaflet_'; // inspired by Zepto touch code by Thomas Fuchs function addDoubleTapListener(obj, handler, id) { var last, touch$$1, doubleTap = false, delay = 250; function onTouchStart(e) { var count; if (pointer) { if ((!edge) || e.pointerType === 'mouse') { return; } count = _pointersCount; } else { count = e.touches.length; } if (count > 1) { return; } var now = Date.now(), delta = now - (last || now); touch$$1 = e.touches ? e.touches[0] : e; doubleTap = (delta > 0 && delta <= delay); last = now; } function onTouchEnd(e) { if (doubleTap && !touch$$1.cancelBubble) { if (pointer) { if ((!edge) || e.pointerType === 'mouse') { return; } // work around .type being readonly with MSPointer* events var newTouch = {}, prop, i; for (i in touch$$1) { prop = touch$$1[i]; newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop; } touch$$1 = newTouch; } touch$$1.type = 'dblclick'; touch$$1.button = 0; handler(touch$$1); last = null; } } obj[_pre + _touchstart + id] = onTouchStart; obj[_pre + _touchend + id] = onTouchEnd; obj[_pre + 'dblclick' + id] = handler; obj.addEventListener(_touchstart, onTouchStart, passiveEvents ? {passive: false} : false); obj.addEventListener(_touchend, onTouchEnd, passiveEvents ? {passive: false} : false); // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse), // the browser doesn't fire touchend/pointerup events but does fire // native dblclicks. See #4127. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180. obj.addEventListener('dblclick', handler, false); return this; } function removeDoubleTapListener(obj, id) { var touchstart = obj[_pre + _touchstart + id], touchend = obj[_pre + _touchend + id], dblclick = obj[_pre + 'dblclick' + id]; obj.removeEventListener(_touchstart, touchstart, passiveEvents ? {passive: false} : false); obj.removeEventListener(_touchend, touchend, passiveEvents ? {passive: false} : false); if (!edge) { obj.removeEventListener('dblclick', dblclick, false); } return this; } /* * @namespace DomUtil * * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model) * tree, used by Leaflet internally. * * Most functions expecting or returning a `HTMLElement` also work for * SVG elements. The only difference is that classes refer to CSS classes * in HTML and SVG classes in SVG. */ // @property TRANSFORM: String // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit). var TRANSFORM = testProp( ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']); // webkitTransition comes first because some browser versions that drop vendor prefix don't do // the same for the transitionend event, in particular the Android 4.1 stock browser // @property TRANSITION: String // Vendor-prefixed transition style name. var TRANSITION = testProp( ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']); // @property TRANSITION_END: String // Vendor-prefixed transitionend event name. var TRANSITION_END = TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend'; // @function get(id: String|HTMLElement): HTMLElement // Returns an element given its DOM id, or returns the element itself // if it was passed directly. function get(id) { return typeof id === 'string' ? document.getElementById(id) : id; } // @function getStyle(el: HTMLElement, styleAttrib: String): String // Returns the value for a certain style attribute on an element, // including computed values or values set through CSS. function getStyle(el, style) { var value = el.style[style] || (el.currentStyle && el.currentStyle[style]); if ((!value || value === 'auto') && document.defaultView) { var css = document.defaultView.getComputedStyle(el, null); value = css ? css[style] : null; } return value === 'auto' ? null : value; } // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element. function create$1(tagName, className, container) { var el = document.createElement(tagName); el.className = className || ''; if (container) { container.appendChild(el); } return el; } // @function remove(el: HTMLElement) // Removes `el` from its parent element function remove(el) { var parent = el.parentNode; if (parent) { parent.removeChild(el); } } // @function empty(el: HTMLElement) // Removes all of `el`'s children elements from `el` function empty(el) { while (el.firstChild) { el.removeChild(el.firstChild); } } // @function toFront(el: HTMLElement) // Makes `el` the last child of its parent, so it renders in front of the other children. function toFront(el) { var parent = el.parentNode; if (parent && parent.lastChild !== el) { parent.appendChild(el); } } // @function toBack(el: HTMLElement) // Makes `el` the first child of its parent, so it renders behind the other children. function toBack(el) { var parent = el.parentNode; if (parent && parent.firstChild !== el) { parent.insertBefore(el, parent.firstChild); } } // @function hasClass(el: HTMLElement, name: String): Boolean // Returns `true` if the element's class attribute contains `name`. function hasClass(el, name) { if (el.classList !== undefined) { return el.classList.contains(name); } var className = getClass(el); return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className); } // @function addClass(el: HTMLElement, name: String) // Adds `name` to the element's class attribute. function addClass(el, name) { if (el.classList !== undefined) { var classes = splitWords(name); for (var i = 0, len = classes.length; i < len; i++) { el.classList.add(classes[i]); } } else if (!hasClass(el, name)) { var className = getClass(el); setClass(el, (className ? className + ' ' : '') + name); } } // @function removeClass(el: HTMLElement, name: String) // Removes `name` from the element's class attribute. function removeClass(el, name) { if (el.classList !== undefined) { el.classList.remove(name); } else { setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' '))); } } // @function setClass(el: HTMLElement, name: String) // Sets the element's class. function setClass(el, name) { if (el.className.baseVal === undefined) { el.className = name; } else { // in case of SVG element el.className.baseVal = name; } } // @function getClass(el: HTMLElement): String // Returns the element's class. function getClass(el) { // Check if the element is an SVGElementInstance and use the correspondingElement instead // (Required for linked SVG elements in IE11.) if (el.correspondingElement) { el = el.correspondingElement; } return el.className.baseVal === undefined ? el.className : el.className.baseVal; } // @function setOpacity(el: HTMLElement, opacity: Number) // Set the opacity of an element (including old IE support). // `opacity` must be a number from `0` to `1`. function setOpacity(el, value) { if ('opacity' in el.style) { el.style.opacity = value; } else if ('filter' in el.style) { _setOpacityIE(el, value); } } function _setOpacityIE(el, value) { var filter = false, filterName = 'DXImageTransform.Microsoft.Alpha'; // filters collection throws an error if we try to retrieve a filter that doesn't exist try { filter = el.filters.item(filterName); } catch (e) { // don't set opacity to 1 if we haven't already set an opacity, // it isn't needed and breaks transparent pngs. if (value === 1) { return; } } value = Math.round(value * 100); if (filter) { filter.Enabled = (value !== 100); filter.Opacity = value; } else { el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')'; } } // @function testProp(props: String[]): String|false // Goes through the array of style names and returns the first name // that is a valid style name for an element. If no such name is found, // it returns false. Useful for vendor-prefixed styles like `transform`. function testProp(props) { var style = document.documentElement.style; for (var i = 0; i < props.length; i++) { if (props[i] in style) { return props[i]; } } return false; } // @function setTransform(el: HTMLElement, offset: Point, scale?: Number) // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels // and optionally scaled by `scale`. Does not have an effect if the // browser doesn't support 3D CSS transforms. function setTransform(el, offset, scale) { var pos = offset || new Point(0, 0); el.style[TRANSFORM] = (ie3d ? 'translate(' + pos.x + 'px,' + pos.y + 'px)' : 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') + (scale ? ' scale(' + scale + ')' : ''); } // @function setPosition(el: HTMLElement, position: Point) // Sets the position of `el` to coordinates specified by `position`, // using CSS translate or top/left positioning depending on the browser // (used by Leaflet internally to position its layers). function setPosition(el, point) { /*eslint-disable */ el._leaflet_pos = point; /* eslint-enable */ if (any3d) { setTransform(el, point); } else { el.style.left = point.x + 'px'; el.style.top = point.y + 'px'; } } // @function getPosition(el: HTMLElement): Point // Returns the coordinates of an element previously positioned with setPosition. function getPosition(el) { // this method is only used for elements previously positioned using setPosition, // so it's safe to cache the position for performance return el._leaflet_pos || new Point(0, 0); } // @function disableTextSelection() // Prevents the user from generating `selectstart` DOM events, usually generated // when the user drags the mouse through a page with text. Used internally // by Leaflet to override the behaviour of any click-and-drag interaction on // the map. Affects drag interactions on the whole document. // @function enableTextSelection() // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection). var disableTextSelection; var enableTextSelection; var _userSelect; if ('onselectstart' in document) { disableTextSelection = function () { on(window, 'selectstart', preventDefault); }; enableTextSelection = function () { off(window, 'selectstart', preventDefault); }; } else { var userSelectProperty = testProp( ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']); disableTextSelection = function () { if (userSelectProperty) { var style = document.documentElement.style; _userSelect = style[userSelectProperty]; style[userSelectProperty] = 'none'; } }; enableTextSelection = function () { if (userSelectProperty) { document.documentElement.style[userSelectProperty] = _userSelect; _userSelect = undefined; } }; } // @function disableImageDrag() // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but // for `dragstart` DOM events, usually generated when the user drags an image. function disableImageDrag() { on(window, 'dragstart', preventDefault); } // @function enableImageDrag() // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection). function enableImageDrag() { off(window, 'dragstart', preventDefault); } var _outlineElement; var _outlineStyle; // @function preventOutline(el: HTMLElement) // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline) // of the element `el` invisible. Used internally by Leaflet to prevent // focusable elements from displaying an outline when the user performs a // drag interaction on them. function preventOutline(element) { while (element.tabIndex === -1) { element = element.parentNode; } if (!element.style) { return; } restoreOutline(); _outlineElement = element; _outlineStyle = element.style.outline; element.style.outline = 'none'; on(window, 'keydown', restoreOutline); } // @function restoreOutline() // Cancels the effects of a previous [`L.DomUtil.preventOutline`](). function restoreOutline() { if (!_outlineElement) { return; } _outlineElement.style.outline = _outlineStyle; _outlineElement = undefined; _outlineStyle = undefined; off(window, 'keydown', restoreOutline); } // @function getSizedParentNode(el: HTMLElement): HTMLElement // Finds the closest parent node which size (width and height) is not null. function getSizedParentNode(element) { do { element = element.parentNode; } while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body); return element; } // @function getScale(el: HTMLElement): Object // Computes the CSS scale currently applied on the element. // Returns an object with `x` and `y` members as horizontal and vertical scales respectively, // and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). function getScale(element) { var rect = element.getBoundingClientRect(); // Read-only in old browsers. return { x: rect.width / element.offsetWidth || 1, y: rect.height / element.offsetHeight || 1, boundingClientRect: rect }; } var DomUtil = (Object.freeze || Object)({ TRANSFORM: TRANSFORM, TRANSITION: TRANSITION, TRANSITION_END: TRANSITION_END, get: get, getStyle: getStyle, create: create$1, remove: remove, empty: empty, toFront: toFront, toBack: toBack, hasClass: hasClass, addClass: addClass, removeClass: removeClass, setClass: setClass, getClass: getClass, setOpacity: setOpacity, testProp: testProp, setTransform: setTransform, setPosition: setPosition, getPosition: getPosition, disableTextSelection: disableTextSelection, enableTextSelection: enableTextSelection, disableImageDrag: disableImageDrag, enableImageDrag: enableImageDrag, preventOutline: preventOutline, restoreOutline: restoreOutline, getSizedParentNode: getSizedParentNode, getScale: getScale }); /* * @namespace DomEvent * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally. */ // Inspired by John Resig, Dean Edwards and YUI addEvent implementations. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this // Adds a listener function (`fn`) to a particular DOM event type of the // element `el`. You can optionally specify the context of the listener // (object the `this` keyword will point to). You can also pass several // space-separated types (e.g. `'click dblclick'`). // @alternative // @function on(el: HTMLElement, eventMap: Object, context?: Object): this // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` function on(obj, types, fn, context) { if (typeof types === 'object') { for (var type in types) { addOne(obj, type, types[type], fn); } } else { types = splitWords(types); for (var i = 0, len = types.length; i < len; i++) { addOne(obj, types[i], fn, context); } } return this; } var eventsKey = '_leaflet_events'; // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this // Removes a previously added listener function. // Note that if you passed a custom context to on, you must pass the same // context to `off` in order to remove the listener. // @alternative // @function off(el: HTMLElement, eventMap: Object, context?: Object): this // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` function off(obj, types, fn, context) { if (typeof types === 'object') { for (var type in types) { removeOne(obj, type, types[type], fn); } } else if (types) { types = splitWords(types); for (var i = 0, len = types.length; i < len; i++) { removeOne(obj, types[i], fn, context); } } else { for (var j in obj[eventsKey]) { removeOne(obj, j, obj[eventsKey][j]); } delete obj[eventsKey]; } return this; } function addOne(obj, type, fn, context) { var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''); if (obj[eventsKey] && obj[eventsKey][id]) { return this; } var handler = function (e) { return fn.call(context || obj, e || window.event); }; var originalHandler = handler; if (pointer && type.indexOf('touch') === 0) { // Needs DomEvent.Pointer.js addPointerListener(obj, type, handler, id); } else if (touch && (type === 'dblclick') && addDoubleTapListener && !(pointer && chrome)) { // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener // See #5180 addDoubleTapListener(obj, handler, id); } else if ('addEventListener' in obj) { if (type === 'mousewheel') { obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false); } else if ((type === 'mouseenter') || (type === 'mouseleave')) { handler = function (e) { e = e || window.event; if (isExternalTarget(obj, e)) { originalHandler(e); } }; obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false); } else { if (type === 'click' && android) { handler = function (e) { filterClick(e, originalHandler); }; } obj.addEventListener(type, handler, false); } } else if ('attachEvent' in obj) { obj.attachEvent('on' + type, handler); } obj[eventsKey] = obj[eventsKey] || {}; obj[eventsKey][id] = handler; } function removeOne(obj, type, fn, context) { var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''), handler = obj[eventsKey] && obj[eventsKey][id]; if (!handler) { return this; } if (pointer && type.indexOf('touch') === 0) { removePointerListener(obj, type, id); } else if (touch && (type === 'dblclick') && removeDoubleTapListener && !(pointer && chrome)) { removeDoubleTapListener(obj, id); } else if ('removeEventListener' in obj) { if (type === 'mousewheel') { obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, passiveEvents ? {passive: false} : false); } else { obj.removeEventListener( type === 'mouseenter' ? 'mouseover' : type === 'mouseleave' ? 'mouseout' : type, handler, false); } } else if ('detachEvent' in obj) { obj.detachEvent('on' + type, handler); } obj[eventsKey][id] = null; } // @function stopPropagation(ev: DOMEvent): this // Stop the given event from propagation to parent elements. Used inside the listener functions: // ```js // L.DomEvent.on(div, 'click', function (ev) { // L.DomEvent.stopPropagation(ev); // }); // ``` function stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); } else if (e.originalEvent) { // In case of Leaflet event. e.originalEvent._stopped = true; } else { e.cancelBubble = true; } skipped(e); return this; } // @function disableScrollPropagation(el: HTMLElement): this // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants). function disableScrollPropagation(el) { addOne(el, 'mousewheel', stopPropagation); return this; } // @function disableClickPropagation(el: HTMLElement): this // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`, // `'mousedown'` and `'touchstart'` events (plus browser variants). function disableClickPropagation(el) { on(el, 'mousedown touchstart dblclick', stopPropagation); addOne(el, 'click', fakeStop); return this; } // @function preventDefault(ev: DOMEvent): this // Prevents the default action of the DOM Event `ev` from happening (such as // following a link in the href of the a element, or doing a POST request // with page reload when a `<form>` is submitted). // Use it inside listener functions. function preventDefault(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } return this; } // @function stop(ev: DOMEvent): this // Does `stopPropagation` and `preventDefault` at the same time. function stop(e) { preventDefault(e); stopPropagation(e); return this; } // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point // Gets normalized mouse position from a DOM event relative to the // `container` (border excluded) or to the whole page if not specified. function getMousePosition(e, container) { if (!container) { return new Point(e.clientX, e.clientY); } var scale = getScale(container), offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y) return new Point( // offset.left/top values are in page scale (like clientX/Y), // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies). (e.clientX - offset.left) / scale.x - container.clientLeft, (e.clientY - offset.top) / scale.y - container.clientTop ); } // Chrome on Win scrolls double the pixels as in other platforms (see #4538), // and Firefox scrolls device pixels, not CSS pixels var wheelPxFactor = (win && chrome) ? 2 * window.devicePixelRatio : gecko ? window.devicePixelRatio : 1; // @function getWheelDelta(ev: DOMEvent): Number // Gets normalized wheel delta from a mousewheel DOM event, in vertical // pixels scrolled (negative if scrolling down). // Events from pointing devices without precise scrolling are mapped to // a best guess of 60 pixels. function getWheelDelta(e) { return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages 0; } var skipEvents = {}; function fakeStop(e) { // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e) skipEvents[e.type] = true; } function skipped(e) { var events = skipEvents[e.type]; // reset when checking, as it's only used in map container and propagates outside of the map skipEvents[e.type] = false; return events; } // check if element really left/entered the event target (for mouseenter/mouseleave) function isExternalTarget(el, e) { var related = e.relatedTarget; if (!related) { return true; } try { while (related && (related !== el)) { related = related.parentNode; } } catch (err) { return false; } return (related !== el); } var lastClick; // this is a horrible workaround for a bug in Android where a single touch triggers two click events function filterClick(e, handler) { var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)), elapsed = lastClick && (timeStamp - lastClick); // are they closer together than 500ms yet more than 100ms? // Android typically triggers them ~300ms apart while multiple listeners // on the same event should be triggered far faster; // or check if click is simulated on the element, and if it is, reject any non-simulated events if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { stop(e); return; } lastClick = timeStamp; handler(e); } var DomEvent = (Object.freeze || Object)({ on: on, off: off, stopPropagation: stopPropagation, disableScrollPropagation: disableScrollPropagation, disableClickPropagation: disableClickPropagation, preventDefault: preventDefault, stop: stop, getMousePosition: getMousePosition, getWheelDelta: getWheelDelta, fakeStop: fakeStop, skipped: skipped, isExternalTarget: isExternalTarget, addListener: on, removeListener: off }); /* * @class PosAnimation * @aka L.PosAnimation * @inherits Evented * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9. * * @example * ```js * var fx = new L.PosAnimation(); * fx.run(el, [300, 500], 0.5); * ``` * * @constructor L.PosAnimation() * Creates a `PosAnimation` object. * */ var PosAnimation = Evented.extend({ // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number) // Run an animation of a given element to a new position, optionally setting // duration in seconds (`0.25` by default) and easing linearity factor (3rd // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1), // `0.5` by default). run: function (el, newPos, duration, easeLinearity) { this.stop(); this._el = el; this._inProgress = true; this._duration = duration || 0.25; this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2); this._startPos = getPosition(el); this._offset = newPos.subtract(this._startPos); this._startTime = +new Date(); // @event start: Event // Fired when the animation starts this.fire('start'); this._animate(); }, // @method stop() // Stops the animation (if currently running). stop: function () { if (!this._inProgress) { return; } this._step(true); this._complete(); }, _animate: function () { // animation loop this._animId = requestAnimFrame(this._animate, this); this._step(); }, _step: function (round) { var elapsed = (+new Date()) - this._startTime, duration = this._duration * 1000; if (elapsed < duration) { this._runFrame(this._easeOut(elapsed / duration), round); } else { this._runFrame(1); this._complete(); } }, _runFrame: function (progress, round) { var pos = this._startPos.add(this._offset.multiplyBy(progress)); if (round) { pos._round(); } setPosition(this._el, pos); // @event step: Event // Fired continuously during the animation. this.fire('step'); }, _complete: function () { cancelAnimFrame(this._animId); this._inProgress = false; // @event end: Event // Fired when the animation ends. this.fire('end'); }, _easeOut: function (t) { return 1 - Math.pow(1 - t, this._easeOutPower); } }); /* * @class Map * @aka L.Map * @inherits Evented * * The central class of the API — it is used to create a map on a page and manipulate it. * * @example * * ```js * // initialize the map on the "map" div with a given center and zoom * var map = L.map('map', { * center: [51.505, -0.09], * zoom: 13 * }); * ``` * */ var Map = Evented.extend({ options: { // @section Map State Options // @option crs: CRS = L.CRS.EPSG3857 // The [Coordinate Reference System](#crs) to use. Don't change this if you're not // sure what it means. crs: EPSG3857, // @option center: LatLng = undefined // Initial geographic center of the map center: undefined, // @option zoom: Number = undefined // Initial map zoom level zoom: undefined, // @option minZoom: Number = * // Minimum zoom level of the map. // If not specified and at least one `GridLayer` or `TileLayer` is in the map, // the lowest of their `minZoom` options will be used instead. minZoom: undefined, // @option maxZoom: Number = * // Maximum zoom level of the map. // If not specified and at least one `GridLayer` or `TileLayer` is in the map, // the highest of their `maxZoom` options will be used instead. maxZoom: undefined, // @option layers: Layer[] = [] // Array of layers that will be added to the map initially layers: [], // @option maxBounds: LatLngBounds = null // When this option is set, the map restricts the view to the given // geographical bounds, bouncing the user back if the user tries to pan // outside the view. To set the restriction dynamically, use // [`setMaxBounds`](#map-setmaxbounds) method. maxBounds: undefined, // @option renderer: Renderer = * // The default method for drawing vector layers on the map. `L.SVG` // or `L.Canvas` by default depending on browser support. renderer: undefined, // @section Animation Options // @option zoomAnimation: Boolean = true // Whether the map zoom animation is enabled. By default it's enabled // in all browsers that support CSS3 Transitions except Android. zoomAnimation: true, // @option zoomAnimationThreshold: Number = 4 // Won't animate zoom if the zoom difference exceeds this value. zoomAnimationThreshold: 4, // @option fadeAnimation: Boolean = true // Whether the tile fade animation is enabled. By default it's enabled // in all browsers that support CSS3 Transitions except Android. fadeAnimation: true, // @option markerZoomAnimation: Boolean = true // Whether markers animate their zoom with the zoom animation, if disabled // they will disappear for the length of the animation. By default it's // enabled in all browsers that support CSS3 Transitions except Android. markerZoomAnimation: true, // @option transform3DLimit: Number = 2^23 // Defines the maximum size of a CSS translation transform. The default // value should not be changed unless a web browser positions layers in // the wrong place after doing a large `panBy`. transform3DLimit: 8388608, // Precision limit of a 32-bit float // @section Interaction Options // @option zoomSnap: Number = 1 // Forces the map's zoom level to always be a multiple of this, particularly // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom. // By default, the zoom level snaps to the nearest integer; lower values // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0` // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom. zoomSnap: 1, // @option zoomDelta: Number = 1 // Controls how much the map's zoom level will change after a // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+` // or `-` on the keyboard, or using the [zoom controls](#control-zoom). // Values smaller than `1` (e.g. `0.5`) allow for greater granularity. zoomDelta: 1, // @option trackResize: Boolean = true // Whether the map automatically handles browser window resize to update itself. trackResize: true }, initialize: function (id, options) { // (HTMLElement or String, Object) options = setOptions(this, options); // Make sure to assign internal flags at the beginning, // to avoid inconsistent state in some edge cases. this._handlers = []; this._layers = {}; this._zoomBoundLayers = {}; this._sizeChanged = true; this._initContainer(id); this._initLayout(); // hack for https://github.com/Leaflet/Leaflet/issues/1980 this._onResize = bind(this._onResize, this); this._initEvents(); if (options.maxBounds) { this.setMaxBounds(options.maxBounds); } if (options.zoom !== undefined) { this._zoom = this._limitZoom(options.zoom); } if (options.center && options.zoom !== undefined) { this.setView(toLatLng(options.center), options.zoom, {reset: true}); } this.callInitHooks(); // don't animate on browsers without hardware-accelerated transitions or old Android/Opera this._zoomAnimated = TRANSITION && any3d && !mobileOpera && this.options.zoomAnimation; // zoom transitions run with the same duration for all layers, so if one of transitionend events // happens after starting zoom animation (propagating to the map pane), we know that it ended globally if (this._zoomAnimated) { this._createAnimProxy(); on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this); } this._addLayers(this.options.layers); }, // @section Methods for modifying map state // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this // Sets the view of the map (geographical center and zoom) with the given // animation options. setView: function (center, zoom, options) { zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom); center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds); options = options || {}; this._stop(); if (this._loaded && !options.reset && options !== true) { if (options.animate !== undefined) { options.zoom = extend({animate: options.animate}, options.zoom); options.pan = extend({animate: options.animate, duration: options.duration}, options.pan); } // try animating pan or zoom var moved = (this._zoom !== zoom) ? this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) : this._tryAnimatedPan(center, options.pan); if (moved) { // prevent resize handler call, the view will refresh after animation anyway clearTimeout(this._sizeTimer); return this; } } // animation didn't start, just reset the map view this._resetView(center, zoom); return this; }, // @method setZoom(zoom: Number, options?: Zoom/pan options): this // Sets the zoom of the map. setZoom: function (zoom, options) { if (!this._loaded) { this._zoom = zoom; return this; } return this.setView(this.getCenter(), zoom, {zoom: options}); }, // @method zoomIn(delta?: Number, options?: Zoom options): this // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). zoomIn: function (delta, options) { delta = delta || (any3d ? this.options.zoomDelta : 1); return this.setZoom(this._zoom + delta, options); }, // @method zoomOut(delta?: Number, options?: Zoom options): this // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). zoomOut: function (delta, options) { delta = delta || (any3d ? this.options.zoomDelta : 1); return this.setZoom(this._zoom - delta, options); }, // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this // Zooms the map while keeping a specified geographical point on the map // stationary (e.g. used internally for scroll zoom and double-click zoom). // @alternative // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary. setZoomAround: function (latlng, zoom, options) { var scale = this.getZoomScale(zoom), viewHalf = this.getSize().divideBy(2), containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng), centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale), newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset)); return this.setView(newCenter, zoom, {zoom: options}); }, _getBoundsCenterZoom: function (bounds, options) { options = options || {}; bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds); var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)); zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom; if (zoom === Infinity) { return { center: bounds.getCenter(), zoom: zoom }; } var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2), swPoint = this.project(bounds.getSouthWest(), zoom), nePoint = this.project(bounds.getNorthEast(), zoom), center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom); return { center: center, zoom: zoom }; }, // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this // Sets a map view that contains the given geographical bounds with the // maximum zoom level possible. fitBounds: function (bounds, options) { bounds = toLatLngBounds(bounds); if (!bounds.isValid()) { throw new Error('Bounds are not valid.'); } var target = this._getBoundsCenterZoom(bounds, options); return this.setView(target.center, target.zoom, options); }, // @method fitWorld(options?: fitBounds options): this // Sets a map view that mostly contains the whole world with the maximum // zoom level possible. fitWorld: function (options) { return this.fitBounds([[-90, -180], [90, 180]], options); }, // @method panTo(latlng: LatLng, options?: Pan options): this // Pans the map to a given center. panTo: function (center, options) { // (LatLng) return this.setView(center, this._zoom, {pan: options}); }, // @method panBy(offset: Point, options?: Pan options): this // Pans the map by a given number of pixels (animated). panBy: function (offset, options) { offset = toPoint(offset).round(); options = options || {}; if (!offset.x && !offset.y) { return this.fire('moveend'); } // If we pan too far, Chrome gets issues with tiles // and makes them disappear or appear in the wrong place (slightly offset) #2602 if (options.animate !== true && !this.getSize().contains(offset)) { this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom()); return this; } if (!this._panAnim) { this._panAnim = new PosAnimation(); this._panAnim.on({ 'step': this._onPanTransitionStep, 'end': this._onPanTransitionEnd }, this); } // don't fire movestart if animating inertia if (!options.noMoveStart) { this.fire('movestart'); } // animate pan unless animate: false specified if (options.animate !== false) { addClass(this._mapPane, 'leaflet-pan-anim'); var newPos = this._getMapPanePos().subtract(offset).round(); this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity); } else { this._rawPanBy(offset); this.fire('move').fire('moveend'); } return this; }, // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this // Sets the view of the map (geographical center and zoom) performing a smooth // pan-zoom animation. flyTo: function (targetCenter, targetZoom, options) { options = options || {}; if (options.animate === false || !any3d) { return this.setView(targetCenter, targetZoom, options); } this._stop(); var from = this.project(this.getCenter()), to = this.project(targetCenter), size = this.getSize(), startZoom = this._zoom; targetCenter = toLatLng(targetCenter); targetZoom = targetZoom === undefined ? startZoom : targetZoom; var w0 = Math.max(size.x, size.y), w1 = w0 * this.getZoomScale(startZoom, targetZoom), u1 = (to.distanceTo(from)) || 1, rho = 1.42, rho2 = rho * rho; function r(i) { var s1 = i ? -1 : 1, s2 = i ? w1 : w0, t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1, b1 = 2 * s2 * rho2 * u1, b = t1 / b1, sq = Math.sqrt(b * b + 1) - b; // workaround for floating point precision bug when sq = 0, log = -Infinite, // thus triggering an infinite loop in flyTo var log = sq < 0.000000001 ? -18 : Math.log(sq); return log; } function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } function tanh(n) { return sinh(n) / cosh(n); } var r0 = r(0); function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); } function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; } function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); } var start = Date.now(), S = (r(1) - r0) / rho, duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8; function frame() { var t = (Date.now() - start) / duration, s = easeOut(t) * S; if (t <= 1) { this._flyToFrame = requestAnimFrame(frame, this); this._move( this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom), this.getScaleZoom(w0 / w(s), startZoom), {flyTo: true}); } else { this ._move(targetCenter, targetZoom) ._moveEnd(true); } } this._moveStart(true, options.noMoveStart); frame.call(this); return this; }, // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto), // but takes a bounds parameter like [`fitBounds`](#map-fitbounds). flyToBounds: function (bounds, options) { var target = this._getBoundsCenterZoom(bounds, options); return this.flyTo(target.center, target.zoom, options); }, // @method setMaxBounds(bounds: Bounds): this // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option). setMaxBounds: function (bounds) { bounds = toLatLngBounds(bounds); if (!bounds.isValid()) { this.options.maxBounds = null; return this.off('moveend', this._panInsideMaxBounds); } else if (this.options.maxBounds) { this.off('moveend', this._panInsideMaxBounds); } this.options.maxBounds = bounds; if (this._loaded) { this._panInsideMaxBounds(); } return this.on('moveend', this._panInsideMaxBounds); }, // @method setMinZoom(zoom: Number): this // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option). setMinZoom: function (zoom) { var oldZoom = this.options.minZoom; this.options.minZoom = zoom; if (this._loaded && oldZoom !== zoom) { this.fire('zoomlevelschange'); if (this.getZoom() < this.options.minZoom) { return this.setZoom(zoom); } } return this; }, // @method setMaxZoom(zoom: Number): this // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option). setMaxZoom: function (zoom) { var oldZoom = this.options.maxZoom; this.options.maxZoom = zoom; if (this._loaded && oldZoom !== zoom) { this.fire('zoomlevelschange'); if (this.getZoom() > this.options.maxZoom) { return this.setZoom(zoom); } } return this; }, // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any. panInsideBounds: function (bounds, options) { this._enforcingBounds = true; var center = this.getCenter(), newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds)); if (!center.equals(newCenter)) { this.panTo(newCenter, options); } this._enforcingBounds = false; return this; }, // @method panInside(latlng: LatLng, options?: options): this // Pans the map the minimum amount to make the `latlng` visible. Use // `padding`, `paddingTopLeft` and `paddingTopRight` options to fit // the display to more restricted bounds, like [`fitBounds`](#map-fitbounds). // If `latlng` is already within the (optionally padded) display bounds, // the map will not be panned. panInside: function (latlng, options) { options = options || {}; var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]), paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]), center = this.getCenter(), pixelCenter = this.project(center), pixelPoint = this.project(latlng), pixelBounds = this.getPixelBounds(), halfPixelBounds = pixelBounds.getSize().divideBy(2), paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]); if (!paddedBounds.contains(pixelPoint)) { this._enforcingBounds = true; var diff = pixelCenter.subtract(pixelPoint), newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y); if (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) { newCenter.x = pixelCenter.x - diff.x; if (diff.x > 0) { newCenter.x += halfPixelBounds.x - paddingTL.x; } else { newCenter.x -= halfPixelBounds.x - paddingBR.x; } } if (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) { newCenter.y = pixelCenter.y - diff.y; if (diff.y > 0) { newCenter.y += halfPixelBounds.y - paddingTL.y; } else { newCenter.y -= halfPixelBounds.y - paddingBR.y; } } this.panTo(this.unproject(newCenter), options); this._enforcingBounds = false; } return this; }, // @method invalidateSize(options: Zoom/pan options): this // Checks if the map container size changed and updates the map if so — // call it after you've changed the map size dynamically, also animating // pan by default. If `options.pan` is `false`, panning will not occur. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so // that it doesn't happen often even if the method is called many // times in a row. // @alternative // @method invalidateSize(animate: Boolean): this // Checks if the map container size changed and updates the map if so — // call it after you've changed the map size dynamically, also animating // pan by default. invalidateSize: function (options) { if (!this._loaded) { return this; } options = extend({ animate: false, pan: true }, options === true ? {animate: true} : options); var oldSize = this.getSize(); this._sizeChanged = true; this._lastCenter = null; var newSize = this.getSize(), oldCenter = oldSize.divideBy(2).round(), newCenter = newSize.divideBy(2).round(), offset = oldCenter.subtract(newCenter); if (!offset.x && !offset.y) { return this; } if (options.animate && options.pan) { this.panBy(offset); } else { if (options.pan) { this._rawPanBy(offset); } this.fire('move'); if (options.debounceMoveend) { clearTimeout(this._sizeTimer); this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200); } else { this.fire('moveend'); } } // @section Map state change events // @event resize: ResizeEvent // Fired when the map is resized. return this.fire('resize', { oldSize: oldSize, newSize: newSize }); }, // @section Methods for modifying map state // @method stop(): this // Stops the currently running `panTo` or `flyTo` animation, if any. stop: function () { this.setZoom(this._limitZoom(this._zoom)); if (!this.options.zoomSnap) { this.fire('viewreset'); } return this._stop(); }, // @section Geolocation methods // @method locate(options?: Locate options): this // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound) // event with location data on success or a [`locationerror`](#map-locationerror) event on failure, // and optionally sets the map view to the user's location with respect to // detection accuracy (or to the world view if geolocation failed). // Note that, if your page doesn't use HTTPS, this method will fail in // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins)) // See `Locate options` for more details. locate: function (options) { options = this._locateOptions = extend({ timeout: 10000, watch: false // setView: false // maxZoom: <Number> // maximumAge: 0 // enableHighAccuracy: false }, options); if (!('geolocation' in navigator)) { this._handleGeolocationError({ code: 0, message: 'Geolocation not supported.' }); return this; } var onResponse = bind(this._handleGeolocationResponse, this), onError = bind(this._handleGeolocationError, this); if (options.watch) { this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options); } else { navigator.geolocation.getCurrentPosition(onResponse, onError, options); } return this; }, // @method stopLocate(): this // Stops watching location previously initiated by `map.locate({watch: true})` // and aborts resetting the map view if map.locate was called with // `{setView: true}`. stopLocate: function () { if (navigator.geolocation && navigator.geolocation.clearWatch) { navigator.geolocation.clearWatch(this._locationWatchId); } if (this._locateOptions) { this._locateOptions.setView = false; } return this; }, _handleGeolocationError: function (error) { var c = error.code, message = error.message || (c === 1 ? 'permission denied' : (c === 2 ? 'position unavailable' : 'timeout')); if (this._locateOptions.setView && !this._loaded) { this.fitWorld(); } // @section Location events // @event locationerror: ErrorEvent // Fired when geolocation (using the [`locate`](#map-locate) method) failed. this.fire('locationerror', { code: c, message: 'Geolocation error: ' + message + '.' }); }, _handleGeolocationResponse: function (pos) { var lat = pos.coords.latitude, lng = pos.coords.longitude, latlng = new LatLng(lat, lng), bounds = latlng.toBounds(pos.coords.accuracy * 2), options = this._locateOptions; if (options.setView) { var zoom = this.getBoundsZoom(bounds); this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom); } var data = { latlng: latlng, bounds: bounds, timestamp: pos.timestamp }; for (var i in pos.coords) { if (typeof pos.coords[i] === 'number') { data[i] = pos.coords[i]; } } // @event locationfound: LocationEvent // Fired when geolocation (using the [`locate`](#map-locate) method) // went successfully. this.fire('locationfound', data); }, // TODO Appropriate docs section? // @section Other Methods // @method addHandler(name: String, HandlerClass: Function): this // Adds a new `Handler` to the map, given its name and constructor function. addHandler: function (name, HandlerClass) { if (!HandlerClass) { return this; } var handler = this[name] = new HandlerClass(this); this._handlers.push(handler); if (this.options[name]) { handler.enable(); } return this; }, // @method remove(): this // Destroys the map and clears all related event listeners. remove: function () { this._initEvents(true); if (this._containerId !== this._container._leaflet_id) { throw new Error('Map container is being reused by another instance'); } try { // throws error in IE6-8 delete this._container._leaflet_id; delete this._containerId; } catch (e) { /*eslint-disable */ this._container._leaflet_id = undefined; /* eslint-enable */ this._containerId = undefined; } if (this._locationWatchId !== undefined) { this.stopLocate(); } this._stop(); remove(this._mapPane); if (this._clearControlPos) { this._clearControlPos(); } if (this._resizeRequest) { cancelAnimFrame(this._resizeRequest); this._resizeRequest = null; } this._clearHandlers(); if (this._loaded) { // @section Map state change events // @event unload: Event // Fired when the map is destroyed with [remove](#map-remove) method. this.fire('unload'); } var i; for (i in this._layers) { this._layers[i].remove(); } for (i in this._panes) { remove(this._panes[i]); } this._layers = []; this._panes = []; delete this._mapPane; delete this._renderer; return this; }, // @section Other Methods // @method createPane(name: String, container?: HTMLElement): HTMLElement // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already, // then returns it. The pane is created as a child of `container`, or // as a child of the main map pane if not set. createPane: function (name, container) { var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''), pane = create$1('div', className, container || this._mapPane); if (name) { this._panes[name] = pane; } return pane; }, // @section Methods for Getting Map State // @method getCenter(): LatLng // Returns the geographical center of the map view getCenter: function () { this._checkIfLoaded(); if (this._lastCenter && !this._moved()) { return this._lastCenter; } return this.layerPointToLatLng(this._getCenterLayerPoint()); }, // @method getZoom(): Number // Returns the current zoom level of the map view getZoom: function () { return this._zoom; }, // @method getBounds(): LatLngBounds // Returns the geographical bounds visible in the current map view getBounds: function () { var bounds = this.getPixelBounds(), sw = this.unproject(bounds.getBottomLeft()), ne = this.unproject(bounds.getTopRight()); return new LatLngBounds(sw, ne); }, // @method getMinZoom(): Number // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default. getMinZoom: function () { return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom; }, // @method getMaxZoom(): Number // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers). getMaxZoom: function () { return this.options.maxZoom === undefined ? (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) : this.options.maxZoom; }, // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number // Returns the maximum zoom level on which the given bounds fit to the map // view in its entirety. If `inside` (optional) is set to `true`, the method // instead returns the minimum zoom level on which the map view fits into // the given bounds in its entirety. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number bounds = toLatLngBounds(bounds); padding = toPoint(padding || [0, 0]); var zoom = this.getZoom() || 0, min = this.getMinZoom(), max = this.getMaxZoom(), nw = bounds.getNorthWest(), se = bounds.getSouthEast(), size = this.getSize().subtract(padding), boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(), snap = any3d ? this.options.zoomSnap : 1, scalex = size.x / boundsSize.x, scaley = size.y / boundsSize.y, scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley); zoom = this.getScaleZoom(scale, zoom); if (snap) { zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap; } return Math.max(min, Math.min(max, zoom)); }, // @method getSize(): Point // Returns the current size of the map container (in pixels). getSize: function () { if (!this._size || this._sizeChanged) { this._size = new Point( this._container.clientWidth || 0, this._container.clientHeight || 0); this._sizeChanged = false; } return this._size.clone(); }, // @method getPixelBounds(): Bounds // Returns the bounds of the current map view in projected pixel // coordinates (sometimes useful in layer and overlay implementations). getPixelBounds: function (center, zoom) { var topLeftPoint = this._getTopLeftPoint(center, zoom); return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize())); }, // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to // the map pane? "left point of the map layer" can be confusing, specially // since there can be negative offsets. // @method getPixelOrigin(): Point // Returns the projected pixel coordinates of the top left point of // the map layer (useful in custom layer and overlay implementations). getPixelOrigin: function () { this._checkIfLoaded(); return this._pixelOrigin; }, // @method getPixelWorldBounds(zoom?: Number): Bounds // Returns the world's bounds in pixel coordinates for zoom level `zoom`. // If `zoom` is omitted, the map's current zoom level is used. getPixelWorldBounds: function (zoom) { return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom); }, // @section Other Methods // @method getPane(pane: String|HTMLElement): HTMLElement // Returns a [map pane](#map-pane), given its name or its HTML element (its identity). getPane: function (pane) { return typeof pane === 'string' ? this._panes[pane] : pane; }, // @method getPanes(): Object // Returns a plain object containing the names of all [panes](#map-pane) as keys and // the panes as values. getPanes: function () { return this._panes; }, // @method getContainer: HTMLElement // Returns the HTML element that contains the map. getContainer: function () { return this._container; }, // @section Conversion Methods // @method getZoomScale(toZoom: Number, fromZoom: Number): Number // Returns the scale factor to be applied to a map transition from zoom level // `fromZoom` to `toZoom`. Used internally to help with zoom animations. getZoomScale: function (toZoom, fromZoom) { // TODO replace with universal implementation after refactoring projections var crs = this.options.crs; fromZoom = fromZoom === undefined ? this._zoom : fromZoom; return crs.scale(toZoom) / crs.scale(fromZoom); }, // @method getScaleZoom(scale: Number, fromZoom: Number): Number // Returns the zoom level that the map would end up at, if it is at `fromZoom` // level and everything is scaled by a factor of `scale`. Inverse of // [`getZoomScale`](#map-getZoomScale). getScaleZoom: function (scale, fromZoom) { var crs = this.options.crs; fromZoom = fromZoom === undefined ? this._zoom : fromZoom; var zoom = crs.zoom(scale * crs.scale(fromZoom)); return isNaN(zoom) ? Infinity : zoom; }, // @method project(latlng: LatLng, zoom: Number): Point // Projects a geographical coordinate `LatLng` according to the projection // of the map's CRS, then scales it according to `zoom` and the CRS's // `Transformation`. The result is pixel coordinate relative to // the CRS origin. project: function (latlng, zoom) { zoom = zoom === undefined ? this._zoom : zoom; return this.options.crs.latLngToPoint(toLatLng(latlng), zoom); }, // @method unproject(point: Point, zoom: Number): LatLng // Inverse of [`project`](#map-project). unproject: function (point, zoom) { zoom = zoom === undefined ? this._zoom : zoom; return this.options.crs.pointToLatLng(toPoint(point), zoom); }, // @method layerPointToLatLng(point: Point): LatLng // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), // returns the corresponding geographical coordinate (for the current zoom level). layerPointToLatLng: function (point) { var projectedPoint = toPoint(point).add(this.getPixelOrigin()); return this.unproject(projectedPoint); }, // @method latLngToLayerPoint(latlng: LatLng): Point // Given a geographical coordinate, returns the corresponding pixel coordinate // relative to the [origin pixel](#map-getpixelorigin). latLngToLayerPoint: function (latlng) { var projectedPoint = this.project(toLatLng(latlng))._round(); return projectedPoint._subtract(this.getPixelOrigin()); }, // @method wrapLatLng(latlng: LatLng): LatLng // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the // CRS's bounds. // By default this means longitude is wrapped around the dateline so its // value is between -180 and +180 degrees. wrapLatLng: function (latlng) { return this.options.crs.wrapLatLng(toLatLng(latlng)); }, // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds // Returns a `LatLngBounds` with the same size as the given one, ensuring that // its center is within the CRS's bounds. // By default this means the center longitude is wrapped around the dateline so its // value is between -180 and +180 degrees, and the majority of the bounds // overlaps the CRS's bounds. wrapLatLngBounds: function (latlng) { return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng)); }, // @method distance(latlng1: LatLng, latlng2: LatLng): Number // Returns the distance between two geographical coordinates according to // the map's CRS. By default this measures distance in meters. distance: function (latlng1, latlng2) { return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2)); }, // @method containerPointToLayerPoint(point: Point): Point // Given a pixel coordinate relative to the map container, returns the corresponding // pixel coordinate relative to the [origin pixel](#map-getpixelorigin). containerPointToLayerPoint: function (point) { // (Point) return toPoint(point).subtract(this._getMapPanePos()); }, // @method layerPointToContainerPoint(point: Point): Point // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), // returns the corresponding pixel coordinate relative to the map container. layerPointToContainerPoint: function (point) { // (Point) return toPoint(point).add(this._getMapPanePos()); }, // @method containerPointToLatLng(point: Point): LatLng // Given a pixel coordinate relative to the map container, returns // the corresponding geographical coordinate (for the current zoom level). containerPointToLatLng: function (point) { var layerPoint = this.containerPointToLayerPoint(toPoint(point)); return this.layerPointToLatLng(layerPoint); }, // @method latLngToContainerPoint(latlng: LatLng): Point // Given a geographical coordinate, returns the corresponding pixel coordinate // relative to the map container. latLngToContainerPoint: function (latlng) { return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng))); }, // @method mouseEventToContainerPoint(ev: MouseEvent): Point // Given a MouseEvent object, returns the pixel coordinate relative to the // map container where the event took place. mouseEventToContainerPoint: function (e) { return getMousePosition(e, this._container); }, // @method mouseEventToLayerPoint(ev: MouseEvent): Point // Given a MouseEvent object, returns the pixel coordinate relative to // the [origin pixel](#map-getpixelorigin) where the event took place. mouseEventToLayerPoint: function (e) { return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e)); }, // @method mouseEventToLatLng(ev: MouseEvent): LatLng // Given a MouseEvent object, returns geographical coordinate where the // event took place. mouseEventToLatLng: function (e) { // (MouseEvent) return this.layerPointToLatLng(this.mouseEventToLayerPoint(e)); }, // map initialization methods _initContainer: function (id) { var container = this._container = get(id); if (!container) { throw new Error('Map container not found.'); } else if (container._leaflet_id) { throw new Error('Map container is already initialized.'); } on(container, 'scroll', this._onScroll, this); this._containerId = stamp(container); }, _initLayout: function () { var container = this._container; this._fadeAnimated = this.options.fadeAnimation && any3d; addClass(container, 'leaflet-container' + (touch ? ' leaflet-touch' : '') + (retina ? ' leaflet-retina' : '') + (ielt9 ? ' leaflet-oldie' : '') + (safari ? ' leaflet-safari' : '') + (this._fadeAnimated ? ' leaflet-fade-anim' : '')); var position = getStyle(container, 'position'); if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') { container.style.position = 'relative'; } this._initPanes(); if (this._initControlPos) { this._initControlPos(); } }, _initPanes: function () { var panes = this._panes = {}; this._paneRenderers = {}; // @section // // Panes are DOM elements used to control the ordering of layers on the map. You // can access panes with [`map.getPane`](#map-getpane) or // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the // [`map.createPane`](#map-createpane) method. // // Every map has the following default panes that differ only in zIndex. // // @pane mapPane: HTMLElement = 'auto' // Pane that contains all other map panes this._mapPane = this.createPane('mapPane', this._container); setPosition(this._mapPane, new Point(0, 0)); // @pane tilePane: HTMLElement = 200 // Pane for `GridLayer`s and `TileLayer`s this.createPane('tilePane'); // @pane overlayPane: HTMLElement = 400 // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s this.createPane('shadowPane'); // @pane shadowPane: HTMLElement = 500 // Pane for overlay shadows (e.g. `Marker` shadows) this.createPane('overlayPane'); // @pane markerPane: HTMLElement = 600 // Pane for `Icon`s of `Marker`s this.createPane('markerPane'); // @pane tooltipPane: HTMLElement = 650 // Pane for `Tooltip`s. this.createPane('tooltipPane'); // @pane popupPane: HTMLElement = 700 // Pane for `Popup`s. this.createPane('popupPane'); if (!this.options.markerZoomAnimation) { addClass(panes.markerPane, 'leaflet-zoom-hide'); addClass(panes.shadowPane, 'leaflet-zoom-hide'); } }, // private methods that modify map state // @section Map state change events _resetView: function (center, zoom) { setPosition(this._mapPane, new Point(0, 0)); var loading = !this._loaded; this._loaded = true; zoom = this._limitZoom(zoom); this.fire('viewprereset'); var zoomChanged = this._zoom !== zoom; this ._moveStart(zoomChanged, false) ._move(center, zoom) ._moveEnd(zoomChanged); // @event viewreset: Event // Fired when the map needs to redraw its content (this usually happens // on map zoom or load). Very useful for creating custom overlays. this.fire('viewreset'); // @event load: Event // Fired when the map is initialized (when its center and zoom are set // for the first time). if (loading) { this.fire('load'); } }, _moveStart: function (zoomChanged, noMoveStart) { // @event zoomstart: Event // Fired when the map zoom is about to change (e.g. before zoom animation). // @event movestart: Event // Fired when the view of the map starts changing (e.g. user starts dragging the map). if (zoomChanged) { this.fire('zoomstart'); } if (!noMoveStart) { this.fire('movestart'); } return this; }, _move: function (center, zoom, data) { if (zoom === undefined) { zoom = this._zoom; } var zoomChanged = this._zoom !== zoom; this._zoom = zoom; this._lastCenter = center; this._pixelOrigin = this._getNewPixelOrigin(center); // @event zoom: Event // Fired repeatedly during any change in zoom level, including zoom // and fly animations. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530 this.fire('zoom', data); } // @event move: Event // Fired repeatedly during any movement of the map, including pan and // fly animations. return this.fire('move', data); }, _moveEnd: function (zoomChanged) { // @event zoomend: Event // Fired when the map has changed, after any animations. if (zoomChanged) { this.fire('zoomend'); } // @event moveend: Event // Fired when the center of the map stops changing (e.g. user stopped // dragging the map). return this.fire('moveend'); }, _stop: function () { cancelAnimFrame(this._flyToFrame); if (this._panAnim) { this._panAnim.stop(); } return this; }, _rawPanBy: function (offset) { setPosition(this._mapPane, this._getMapPanePos().subtract(offset)); }, _getZoomSpan: function () { return this.getMaxZoom() - this.getMinZoom(); }, _panInsideMaxBounds: function () { if (!this._enforcingBounds) { this.panInsideBounds(this.options.maxBounds); } }, _checkIfLoaded: function () { if (!this._loaded) { throw new Error('Set map center and zoom first.'); } }, // DOM event handling // @section Interaction events _initEvents: function (remove$$1) { this._targets = {}; this._targets[stamp(this._container)] = this; var onOff = remove$$1 ? off : on; // @event click: MouseEvent // Fired when the user clicks (or taps) the map. // @event dblclick: MouseEvent // Fired when the user double-clicks (or double-taps) the map. // @event mousedown: MouseEvent // Fired when the user pushes the mouse button on the map. // @event mouseup: MouseEvent // Fired when the user releases the mouse button on the map. // @event mouseover: MouseEvent // Fired when the mouse enters the map. // @event mouseout: MouseEvent // Fired when the mouse leaves the map. // @event mousemove: MouseEvent // Fired while the mouse moves over the map. // @event contextmenu: MouseEvent // Fired when the user pushes the right mouse button on the map, prevents // default browser context menu from showing if there are listeners on // this event. Also fired on mobile when the user holds a single touch // for a second (also called long press). // @event keypress: KeyboardEvent // Fired when the user presses a key from the keyboard that produces a character value while the map is focused. // @event keydown: KeyboardEvent // Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event, // the `keydown` event is fired for keys that produce a character value and for keys // that do not produce a character value. // @event keyup: KeyboardEvent // Fired when the user releases a key from the keyboard while the map is focused. onOff(this._container, 'click dblclick mousedown mouseup ' + 'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this); if (this.options.trackResize) { onOff(window, 'resize', this._onResize, this); } if (any3d && this.options.transform3DLimit) { (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd); } }, _onResize: function () { cancelAnimFrame(this._resizeRequest); this._resizeRequest = requestAnimFrame( function () { this.invalidateSize({debounceMoveend: true}); }, this); }, _onScroll: function () { this._container.scrollTop = 0; this._container.scrollLeft = 0; }, _onMoveEnd: function () { var pos = this._getMapPanePos(); if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) { // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/ this._resetView(this.getCenter(), this.getZoom()); } }, _findEventTargets: function (e, type) { var targets = [], target, isHover = type === 'mouseout' || type === 'mouseover', src = e.target || e.srcElement, dragging = false; while (src) { target = this._targets[stamp(src)]; if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) { // Prevent firing click after you just dragged an object. dragging = true; break; } if (target && target.listens(type, true)) { if (isHover && !isExternalTarget(src, e)) { break; } targets.push(target); if (isHover) { break; } } if (src === this._container) { break; } src = src.parentNode; } if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) { targets = [this]; } return targets; }, _handleDOMEvent: function (e) { if (!this._loaded || skipped(e)) { return; } var type = e.type; if (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') { // prevents outline when clicking on keyboard-focusable element preventOutline(e.target || e.srcElement); } this._fireDOMEvent(e, type); }, _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'], _fireDOMEvent: function (e, type, targets) { if (e.type === 'click') { // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups). // @event preclick: MouseEvent // Fired before mouse click on the map (sometimes useful when you // want something to happen on click before any existing click // handlers start running). var synth = extend({}, e); synth.type = 'preclick'; this._fireDOMEvent(synth, synth.type, targets); } if (e._stopped) { return; } // Find the layer the event is propagating from and its parents. targets = (targets || []).concat(this._findEventTargets(e, type)); if (!targets.length) { return; } var target = targets[0]; if (type === 'contextmenu' && target.listens(type, true)) { preventDefault(e); } var data = { originalEvent: e }; if (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') { var isMarker = target.getLatLng && (!target._radius || target._radius <= 10); data.containerPoint = isMarker ? this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e); data.layerPoint = this.containerPointToLayerPoint(data.containerPoint); data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint); } for (var i = 0; i < targets.length; i++) { targets[i].fire(type, data, true); if (data.originalEvent._stopped || (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; } } }, _draggableMoved: function (obj) { obj = obj.dragging && obj.dragging.enabled() ? obj : this; return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved()); }, _clearHandlers: function () { for (var i = 0, len = this._handlers.length; i < len; i++) { this._handlers[i].disable(); } }, // @section Other Methods // @method whenReady(fn: Function, context?: Object): this // Runs the given function `fn` when the map gets initialized with // a view (center and zoom) and at least one layer, or immediately // if it's already initialized, optionally passing a function context. whenReady: function (callback, context) { if (this._loaded) { callback.call(context || this, {target: this}); } else { this.on('load', callback, context); } return this; }, // private methods for getting map state _getMapPanePos: function () { return getPosition(this._mapPane) || new Point(0, 0); }, _moved: function () { var pos = this._getMapPanePos(); return pos && !pos.equals([0, 0]); }, _getTopLeftPoint: function (center, zoom) { var pixelOrigin = center && zoom !== undefined ? this._getNewPixelOrigin(center, zoom) : this.getPixelOrigin(); return pixelOrigin.subtract(this._getMapPanePos()); }, _getNewPixelOrigin: function (center, zoom) { var viewHalf = this.getSize()._divideBy(2); return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round(); }, _latLngToNewLayerPoint: function (latlng, zoom, center) { var topLeft = this._getNewPixelOrigin(center, zoom); return this.project(latlng, zoom)._subtract(topLeft); }, _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) { var topLeft = this._getNewPixelOrigin(center, zoom); return toBounds([ this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft), this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft), this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft), this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft) ]); }, // layer point of the current center _getCenterLayerPoint: function () { return this.containerPointToLayerPoint(this.getSize()._divideBy(2)); }, // offset of the specified place to the current center in pixels _getCenterOffset: function (latlng) { return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint()); }, // adjust center for view to get inside bounds _limitCenter: function (center, zoom, bounds) { if (!bounds) { return center; } var centerPoint = this.project(center, zoom), viewHalf = this.getSize().divideBy(2), viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), offset = this._getBoundsOffset(viewBounds, bounds, zoom); // If offset is less than a pixel, ignore. // This prevents unstable projections from getting into // an infinite loop of tiny offsets. if (offset.round().equals([0, 0])) { return center; } return this.unproject(centerPoint.add(offset), zoom); }, // adjust offset for view to get inside bounds _limitOffset: function (offset, bounds) { if (!bounds) { return offset; } var viewBounds = this.getPixelBounds(), newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset)); return offset.add(this._getBoundsOffset(newBounds, bounds)); }, // returns offset needed for pxBounds to get inside maxBounds at a specified zoom _getBoundsOffset: function (pxBounds, maxBounds, zoom) { var projectedMaxBounds = toBounds( this.project(maxBounds.getNorthEast(), zoom), this.project(maxBounds.getSouthWest(), zoom) ), minOffset = projectedMaxBounds.min.subtract(pxBounds.min), maxOffset = projectedMaxBounds.max.subtract(pxBounds.max), dx = this._rebound(minOffset.x, -maxOffset.x), dy = this._rebound(minOffset.y, -maxOffset.y); return new Point(dx, dy); }, _rebound: function (left, right) { return left + right > 0 ? Math.round(left - right) / 2 : Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right)); }, _limitZoom: function (zoom) { var min = this.getMinZoom(), max = this.getMaxZoom(), snap = any3d ? this.options.zoomSnap : 1; if (snap) { zoom = Math.round(zoom / snap) * snap; } return Math.max(min, Math.min(max, zoom)); }, _onPanTransitionStep: function () { this.fire('move'); }, _onPanTransitionEnd: function () { removeClass(this._mapPane, 'leaflet-pan-anim'); this.fire('moveend'); }, _tryAnimatedPan: function (center, options) { // difference between the new and current centers in pixels var offset = this._getCenterOffset(center)._trunc(); // don't animate too far unless animate: true specified in options if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; } this.panBy(offset, options); return true; }, _createAnimProxy: function () { var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated'); this._panes.mapPane.appendChild(proxy); this.on('zoomanim', function (e) { var prop = TRANSFORM, transform = this._proxy.style[prop]; setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1)); // workaround for case when transform is the same and so transitionend event is not fired if (transform === this._proxy.style[prop] && this._animatingZoom) { this._onZoomTransitionEnd(); } }, this); this.on('load moveend', this._animMoveEnd, this); this._on('unload', this._destroyAnimProxy, this); }, _destroyAnimProxy: function () { remove(this._proxy); this.off('load moveend', this._animMoveEnd, this); delete this._proxy; }, _animMoveEnd: function () { var c = this.getCenter(), z = this.getZoom(); setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1)); }, _catchTransitionEnd: function (e) { if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) { this._onZoomTransitionEnd(); } }, _nothingToAnimate: function () { return !this._container.getElementsByClassName('leaflet-zoom-animated').length; }, _tryAnimatedZoom: function (center, zoom, options) { if (this._animatingZoom) { return true; } options = options || {}; // don't animate if disabled, not supported or zoom difference is too large if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() || Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; } // offset is the pixel coords of the zoom origin relative to the current center var scale = this.getZoomScale(zoom), offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale); // don't animate if the zoom origin isn't within one screen from the current center, unless forced if (options.animate !== true && !this.getSize().contains(offset)) { return false; } requestAnimFrame(function () { this ._moveStart(true, false) ._animateZoom(center, zoom, true); }, this); return true; }, _animateZoom: function (center, zoom, startAnim, noUpdate) { if (!this._mapPane) { return; } if (startAnim) { this._animatingZoom = true; // remember what center/zoom to set after animation this._animateToCenter = center; this._animateToZoom = zoom; addClass(this._mapPane, 'leaflet-zoom-anim'); } // @section Other Events // @event zoomanim: ZoomAnimEvent // Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom. this.fire('zoomanim', { center: center, zoom: zoom, noUpdate: noUpdate }); // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693 setTimeout(bind(this._onZoomTransitionEnd, this), 250); }, _onZoomTransitionEnd: function () { if (!this._animatingZoom) { return; } if (this._mapPane) { removeClass(this._mapPane, 'leaflet-zoom-anim'); } this._animatingZoom = false; this._move(this._animateToCenter, this._animateToZoom); // This anim frame should prevent an obscure iOS webkit tile loading race condition. requestAnimFrame(function () { this._moveEnd(true); }, this); } }); // @section // @factory L.map(id: String, options?: Map options) // Instantiates a map object given the DOM ID of a `<div>` element // and optionally an object literal with `Map options`. // // @alternative // @factory L.map(el: HTMLElement, options?: Map options) // Instantiates a map object given an instance of a `<div>` HTML element // and optionally an object literal with `Map options`. function createMap(id, options) { return new Map(id, options); } /* * @class Control * @aka L.Control * @inherits Class * * L.Control is a base class for implementing map controls. Handles positioning. * All other controls extend from this class. */ var Control = Class.extend({ // @section // @aka Control options options: { // @option position: String = 'topright' // The position of the control (one of the map corners). Possible values are `'topleft'`, // `'topright'`, `'bottomleft'` or `'bottomright'` position: 'topright' }, initialize: function (options) { setOptions(this, options); }, /* @section * Classes extending L.Control will inherit the following methods: * * @method getPosition: string * Returns the position of the control. */ getPosition: function () { return this.options.position; }, // @method setPosition(position: string): this // Sets the position of the control. setPosition: function (position) { var map = this._map; if (map) { map.removeControl(this); } this.options.position = position; if (map) { map.addControl(this); } return this; }, // @method getContainer: HTMLElement // Returns the HTMLElement that contains the control. getContainer: function () { return this._container; }, // @method addTo(map: Map): this // Adds the control to the given map. addTo: function (map) { this.remove(); this._map = map; var container = this._container = this.onAdd(map), pos = this.getPosition(), corner = map._controlCorners[pos]; addClass(container, 'leaflet-control'); if (pos.indexOf('bottom') !== -1) { corner.insertBefore(container, corner.firstChild); } else { corner.appendChild(container); } this._map.on('unload', this.remove, this); return this; }, // @method remove: this // Removes the control from the map it is currently active on. remove: function () { if (!this._map) { return this; } remove(this._container); if (this.onRemove) { this.onRemove(this._map); } this._map.off('unload', this.remove, this); this._map = null; return this; }, _refocusOnMap: function (e) { // if map exists and event is not a keyboard event if (this._map && e && e.screenX > 0 && e.screenY > 0) { this._map.getContainer().focus(); } } }); var control = function (options) { return new Control(options); }; /* @section Extension methods * @uninheritable * * Every control should extend from `L.Control` and (re-)implement the following methods. * * @method onAdd(map: Map): HTMLElement * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo). * * @method onRemove(map: Map) * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove). */ /* @namespace Map * @section Methods for Layers and Controls */ Map.include({ // @method addControl(control: Control): this // Adds the given control to the map addControl: function (control) { control.addTo(this); return this; }, // @method removeControl(control: Control): this // Removes the given control from the map removeControl: function (control) { control.remove(); return this; }, _initControlPos: function () { var corners = this._controlCorners = {}, l = 'leaflet-', container = this._controlContainer = create$1('div', l + 'control-container', this._container); function createCorner(vSide, hSide) { var className = l + vSide + ' ' + l + hSide; corners[vSide + hSide] = create$1('div', className, container); } createCorner('top', 'left'); createCorner('top', 'right'); createCorner('bottom', 'left'); createCorner('bottom', 'right'); }, _clearControlPos: function () { for (var i in this._controlCorners) { remove(this._controlCorners[i]); } remove(this._controlContainer); delete this._controlCorners; delete this._controlContainer; } }); /* * @class Control.Layers * @aka L.Control.Layers * @inherits Control * * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`. * * @example * * ```js * var baseLayers = { * "Mapbox": mapbox, * "OpenStreetMap": osm * }; * * var overlays = { * "Marker": marker, * "Roads": roadsLayer * }; * * L.control.layers(baseLayers, overlays).addTo(map); * ``` * * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values: * * ```js * { * "<someName1>": layer1, * "<someName2>": layer2 * } * ``` * * The layer names can contain HTML, which allows you to add additional styling to the items: * * ```js * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer} * ``` */ var Layers = Control.extend({ // @section // @aka Control.Layers options options: { // @option collapsed: Boolean = true // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch. collapsed: true, position: 'topright', // @option autoZIndex: Boolean = true // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off. autoZIndex: true, // @option hideSingleBase: Boolean = false // If `true`, the base layers in the control will be hidden when there is only one. hideSingleBase: false, // @option sortLayers: Boolean = false // Whether to sort the layers. When `false`, layers will keep the order // in which they were added to the control. sortLayers: false, // @option sortFunction: Function = * // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) // that will be used for sorting the layers, when `sortLayers` is `true`. // The function receives both the `L.Layer` instances and their names, as in // `sortFunction(layerA, layerB, nameA, nameB)`. // By default, it sorts layers alphabetically by their name. sortFunction: function (layerA, layerB, nameA, nameB) { return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0); } }, initialize: function (baseLayers, overlays, options) { setOptions(this, options); this._layerControlInputs = []; this._layers = []; this._lastZIndex = 0; this._handlingClick = false; for (var i in baseLayers) { this._addLayer(baseLayers[i], i); } for (i in overlays) { this._addLayer(overlays[i], i, true); } }, onAdd: function (map) { this._initLayout(); this._update(); this._map = map; map.on('zoomend', this._checkDisabledLayers, this); for (var i = 0; i < this._layers.length; i++) { this._layers[i].layer.on('add remove', this._onLayerChange, this); } return this._container; }, addTo: function (map) { Control.prototype.addTo.call(this, map); // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height. return this._expandIfNotCollapsed(); }, onRemove: function () { this._map.off('zoomend', this._checkDisabledLayers, this); for (var i = 0; i < this._layers.length; i++) { this._layers[i].layer.off('add remove', this._onLayerChange, this); } }, // @method addBaseLayer(layer: Layer, name: String): this // Adds a base layer (radio button entry) with the given name to the control. addBaseLayer: function (layer, name) { this._addLayer(layer, name); return (this._map) ? this._update() : this; }, // @method addOverlay(layer: Layer, name: String): this // Adds an overlay (checkbox entry) with the given name to the control. addOverlay: function (layer, name) { this._addLayer(layer, name, true); return (this._map) ? this._update() : this; }, // @method removeLayer(layer: Layer): this // Remove the given layer from the control. removeLayer: function (layer) { layer.off('add remove', this._onLayerChange, this); var obj = this._getLayer(stamp(layer)); if (obj) { this._layers.splice(this._layers.indexOf(obj), 1); } return (this._map) ? this._update() : this; }, // @method expand(): this // Expand the control container if collapsed. expand: function () { addClass(this._container, 'leaflet-control-layers-expanded'); this._section.style.height = null; var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50); if (acceptableHeight < this._section.clientHeight) { addClass(this._section, 'leaflet-control-layers-scrollbar'); this._section.style.height = acceptableHeight + 'px'; } else { removeClass(this._section, 'leaflet-control-layers-scrollbar'); } this._checkDisabledLayers(); return this; }, // @method collapse(): this // Collapse the control container if expanded. collapse: function () { removeClass(this._container, 'leaflet-control-layers-expanded'); return this; }, _initLayout: function () { var className = 'leaflet-control-layers', container = this._container = create$1('div', className), collapsed = this.options.collapsed; // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released container.setAttribute('aria-haspopup', true); disableClickPropagation(container); disableScrollPropagation(container); var section = this._section = create$1('section', className + '-list'); if (collapsed) { this._map.on('click', this.collapse, this); if (!android) { on(container, { mouseenter: this.expand, mouseleave: this.collapse }, this); } } var link = this._layersLink = create$1('a', className + '-toggle', container); link.href = '#'; link.title = 'Layers'; if (touch) { on(link, 'click', stop); on(link, 'click', this.expand, this); } else { on(link, 'focus', this.expand, this); } if (!collapsed) { this.expand(); } this._baseLayersList = create$1('div', className + '-base', section); this._separator = create$1('div', className + '-separator', section); this._overlaysList = create$1('div', className + '-overlays', section); container.appendChild(section); }, _getLayer: function (id) { for (var i = 0; i < this._layers.length; i++) { if (this._layers[i] && stamp(this._layers[i].layer) === id) { return this._layers[i]; } } }, _addLayer: function (layer, name, overlay) { if (this._map) { layer.on('add remove', this._onLayerChange, this); } this._layers.push({ layer: layer, name: name, overlay: overlay }); if (this.options.sortLayers) { this._layers.sort(bind(function (a, b) { return this.options.sortFunction(a.layer, b.layer, a.name, b.name); }, this)); } if (this.options.autoZIndex && layer.setZIndex) { this._lastZIndex++; layer.setZIndex(this._lastZIndex); } this._expandIfNotCollapsed(); }, _update: function () { if (!this._container) { return this; } empty(this._baseLayersList); empty(this._overlaysList); this._layerControlInputs = []; var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0; for (i = 0; i < this._layers.length; i++) { obj = this._layers[i]; this._addItem(obj); overlaysPresent = overlaysPresent || obj.overlay; baseLayersPresent = baseLayersPresent || !obj.overlay; baseLayersCount += !obj.overlay ? 1 : 0; } // Hide base layers section if there's only one layer. if (this.options.hideSingleBase) { baseLayersPresent = baseLayersPresent && baseLayersCount > 1; this._baseLayersList.style.display = baseLayersPresent ? '' : 'none'; } this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none'; return this; }, _onLayerChange: function (e) { if (!this._handlingClick) { this._update(); } var obj = this._getLayer(stamp(e.target)); // @namespace Map // @section Layer events // @event baselayerchange: LayersControlEvent // Fired when the base layer is changed through the [layer control](#control-layers). // @event overlayadd: LayersControlEvent // Fired when an overlay is selected through the [layer control](#control-layers). // @event overlayremove: LayersControlEvent // Fired when an overlay is deselected through the [layer control](#control-layers). // @namespace Control.Layers var type = obj.overlay ? (e.type === 'add' ? 'overlayadd' : 'overlayremove') : (e.type === 'add' ? 'baselayerchange' : null); if (type) { this._map.fire(type, obj); } }, // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe) _createRadioElement: function (name, checked) { var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"' + (checked ? ' checked="checked"' : '') + '/>'; var radioFragment = document.createElement('div'); radioFragment.innerHTML = radioHtml; return radioFragment.firstChild; }, _addItem: function (obj) { var label = document.createElement('label'), checked = this._map.hasLayer(obj.layer), input; if (obj.overlay) { input = document.createElement('input'); input.type = 'checkbox'; input.className = 'leaflet-control-layers-selector'; input.defaultChecked = checked; } else { input = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked); } this._layerControlInputs.push(input); input.layerId = stamp(obj.layer); on(input, 'click', this._onInputClick, this); var name = document.createElement('span'); name.innerHTML = ' ' + obj.name; // Helps from preventing layer control flicker when checkboxes are disabled // https://github.com/Leaflet/Leaflet/issues/2771 var holder = document.createElement('div'); label.appendChild(holder); holder.appendChild(input); holder.appendChild(name); var container = obj.overlay ? this._overlaysList : this._baseLayersList; container.appendChild(label); this._checkDisabledLayers(); return label; }, _onInputClick: function () { var inputs = this._layerControlInputs, input, layer; var addedLayers = [], removedLayers = []; this._handlingClick = true; for (var i = inputs.length - 1; i >= 0; i--) { input = inputs[i]; layer = this._getLayer(input.layerId).layer; if (input.checked) { addedLayers.push(layer); } else if (!input.checked) { removedLayers.push(layer); } } // Bugfix issue 2318: Should remove all old layers before readding new ones for (i = 0; i < removedLayers.length; i++) { if (this._map.hasLayer(removedLayers[i])) { this._map.removeLayer(removedLayers[i]); } } for (i = 0; i < addedLayers.length; i++) { if (!this._map.hasLayer(addedLayers[i])) { this._map.addLayer(addedLayers[i]); } } this._handlingClick = false; this._refocusOnMap(); }, _checkDisabledLayers: function () { var inputs = this._layerControlInputs, input, layer, zoom = this._map.getZoom(); for (var i = inputs.length - 1; i >= 0; i--) { input = inputs[i]; layer = this._getLayer(input.layerId).layer; input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) || (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom); } }, _expandIfNotCollapsed: function () { if (this._map && !this.options.collapsed) { this.expand(); } return this; }, _expand: function () { // Backward compatibility, remove me in 1.1. return this.expand(); }, _collapse: function () { // Backward compatibility, remove me in 1.1. return this.collapse(); } }); // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options) // Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation. var layers = function (baseLayers, overlays, options) { return new Layers(baseLayers, overlays, options); }; /* * @class Control.Zoom * @aka L.Control.Zoom * @inherits Control * * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`. */ var Zoom = Control.extend({ // @section // @aka Control.Zoom options options: { position: 'topleft', // @option zoomInText: String = '+' // The text set on the 'zoom in' button. zoomInText: '+', // @option zoomInTitle: String = 'Zoom in' // The title set on the 'zoom in' button. zoomInTitle: 'Zoom in', // @option zoomOutText: String = '&#x2212;' // The text set on the 'zoom out' button. zoomOutText: '&#x2212;', // @option zoomOutTitle: String = 'Zoom out' // The title set on the 'zoom out' button. zoomOutTitle: 'Zoom out' }, onAdd: function (map) { var zoomName = 'leaflet-control-zoom', container = create$1('div', zoomName + ' leaflet-bar'), options = this.options; this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle, zoomName + '-in', container, this._zoomIn); this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle, zoomName + '-out', container, this._zoomOut); this._updateDisabled(); map.on('zoomend zoomlevelschange', this._updateDisabled, this); return container; }, onRemove: function (map) { map.off('zoomend zoomlevelschange', this._updateDisabled, this); }, disable: function () { this._disabled = true; this._updateDisabled(); return this; }, enable: function () { this._disabled = false; this._updateDisabled(); return this; }, _zoomIn: function (e) { if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) { this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1)); } }, _zoomOut: function (e) { if (!this._disabled && this._map._zoom > this._map.getMinZoom()) { this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1)); } }, _createButton: function (html, title, className, container, fn) { var link = create$1('a', className, container); link.innerHTML = html; link.href = '#'; link.title = title; /* * Will force screen readers like VoiceOver to read this as "Zoom in - button" */ link.setAttribute('role', 'button'); link.setAttribute('aria-label', title); disableClickPropagation(link); on(link, 'click', stop); on(link, 'click', fn, this); on(link, 'click', this._refocusOnMap, this); return link; }, _updateDisabled: function () { var map = this._map, className = 'leaflet-disabled'; removeClass(this._zoomInButton, className); removeClass(this._zoomOutButton, className); if (this._disabled || map._zoom === map.getMinZoom()) { addClass(this._zoomOutButton, className); } if (this._disabled || map._zoom === map.getMaxZoom()) { addClass(this._zoomInButton, className); } } }); // @namespace Map // @section Control options // @option zoomControl: Boolean = true // Whether a [zoom control](#control-zoom) is added to the map by default. Map.mergeOptions({ zoomControl: true }); Map.addInitHook(function () { if (this.options.zoomControl) { // @section Controls // @property zoomControl: Control.Zoom // The default zoom control (only available if the // [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map). this.zoomControl = new Zoom(); this.addControl(this.zoomControl); } }); // @namespace Control.Zoom // @factory L.control.zoom(options: Control.Zoom options) // Creates a zoom control var zoom = function (options) { return new Zoom(options); }; /* * @class Control.Scale * @aka L.Control.Scale * @inherits Control * * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`. * * @example * * ```js * L.control.scale().addTo(map); * ``` */ var Scale = Control.extend({ // @section // @aka Control.Scale options options: { position: 'bottomleft', // @option maxWidth: Number = 100 // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500). maxWidth: 100, // @option metric: Boolean = True // Whether to show the metric scale line (m/km). metric: true, // @option imperial: Boolean = True // Whether to show the imperial scale line (mi/ft). imperial: true // @option updateWhenIdle: Boolean = false // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)). }, onAdd: function (map) { var className = 'leaflet-control-scale', container = create$1('div', className), options = this.options; this._addScales(options, className + '-line', container); map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this); map.whenReady(this._update, this); return container; }, onRemove: function (map) { map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this); }, _addScales: function (options, className, container) { if (options.metric) { this._mScale = create$1('div', className, container); } if (options.imperial) { this._iScale = create$1('div', className, container); } }, _update: function () { var map = this._map, y = map.getSize().y / 2; var maxMeters = map.distance( map.containerPointToLatLng([0, y]), map.containerPointToLatLng([this.options.maxWidth, y])); this._updateScales(maxMeters); }, _updateScales: function (maxMeters) { if (this.options.metric && maxMeters) { this._updateMetric(maxMeters); } if (this.options.imperial && maxMeters) { this._updateImperial(maxMeters); } }, _updateMetric: function (maxMeters) { var meters = this._getRoundNum(maxMeters), label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km'; this._updateScale(this._mScale, label, meters / maxMeters); }, _updateImperial: function (maxMeters) { var maxFeet = maxMeters * 3.2808399, maxMiles, miles, feet; if (maxFeet > 5280) { maxMiles = maxFeet / 5280; miles = this._getRoundNum(maxMiles); this._updateScale(this._iScale, miles + ' mi', miles / maxMiles); } else { feet = this._getRoundNum(maxFeet); this._updateScale(this._iScale, feet + ' ft', feet / maxFeet); } }, _updateScale: function (scale, text, ratio) { scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px'; scale.innerHTML = text; }, _getRoundNum: function (num) { var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1), d = num / pow10; d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1; return pow10 * d; } }); // @factory L.control.scale(options?: Control.Scale options) // Creates an scale control with the given options. var scale = function (options) { return new Scale(options); }; /* * @class Control.Attribution * @aka L.Control.Attribution * @inherits Control * * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control. */ var Attribution = Control.extend({ // @section // @aka Control.Attribution options options: { position: 'bottomright', // @option prefix: String = 'Leaflet' // The HTML text shown before the attributions. Pass `false` to disable. prefix: '<a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>' }, initialize: function (options) { setOptions(this, options); this._attributions = {}; }, onAdd: function (map) { map.attributionControl = this; this._container = create$1('div', 'leaflet-control-attribution'); disableClickPropagation(this._container); // TODO ugly, refactor for (var i in map._layers) { if (map._layers[i].getAttribution) { this.addAttribution(map._layers[i].getAttribution()); } } this._update(); return this._container; }, // @method setPrefix(prefix: String): this // Sets the text before the attributions. setPrefix: function (prefix) { this.options.prefix = prefix; this._update(); return this; }, // @method addAttribution(text: String): this // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`). addAttribution: function (text) { if (!text) { return this; } if (!this._attributions[text]) { this._attributions[text] = 0; } this._attributions[text]++; this._update(); return this; }, // @method removeAttribution(text: String): this // Removes an attribution text. removeAttribution: function (text) { if (!text) { return this; } if (this._attributions[text]) { this._attributions[text]--; this._update(); } return this; }, _update: function () { if (!this._map) { return; } var attribs = []; for (var i in this._attributions) { if (this._attributions[i]) { attribs.push(i); } } var prefixAndAttribs = []; if (this.options.prefix) { prefixAndAttribs.push(this.options.prefix); } if (attribs.length) { prefixAndAttribs.push(attribs.join(', ')); } this._container.innerHTML = prefixAndAttribs.join(' | '); } }); // @namespace Map // @section Control options // @option attributionControl: Boolean = true // Whether a [attribution control](#control-attribution) is added to the map by default. Map.mergeOptions({ attributionControl: true }); Map.addInitHook(function () { if (this.options.attributionControl) { new Attribution().addTo(this); } }); // @namespace Control.Attribution // @factory L.control.attribution(options: Control.Attribution options) // Creates an attribution control. var attribution = function (options) { return new Attribution(options); }; Control.Layers = Layers; Control.Zoom = Zoom; Control.Scale = Scale; Control.Attribution = Attribution; control.layers = layers; control.zoom = zoom; control.scale = scale; control.attribution = attribution; /* L.Handler is a base class for handler classes that are used internally to inject interaction features like dragging to classes like Map and Marker. */ // @class Handler // @aka L.Handler // Abstract class for map interaction handlers var Handler = Class.extend({ initialize: function (map) { this._map = map; }, // @method enable(): this // Enables the handler enable: function () { if (this._enabled) { return this; } this._enabled = true; this.addHooks(); return this; }, // @method disable(): this // Disables the handler disable: function () { if (!this._enabled) { return this; } this._enabled = false; this.removeHooks(); return this; }, // @method enabled(): Boolean // Returns `true` if the handler is enabled enabled: function () { return !!this._enabled; } // @section Extension methods // Classes inheriting from `Handler` must implement the two following methods: // @method addHooks() // Called when the handler is enabled, should add event hooks. // @method removeHooks() // Called when the handler is disabled, should remove the event hooks added previously. }); // @section There is static function which can be called without instantiating L.Handler: // @function addTo(map: Map, name: String): this // Adds a new Handler to the given map with the given name. Handler.addTo = function (map, name) { map.addHandler(name, this); return this; }; var Mixin = {Events: Events}; /* * @class Draggable * @aka L.Draggable * @inherits Evented * * A class for making DOM elements draggable (including touch support). * Used internally for map and marker dragging. Only works for elements * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition). * * @example * ```js * var draggable = new L.Draggable(elementToDrag); * draggable.enable(); * ``` */ var START = touch ? 'touchstart mousedown' : 'mousedown'; var END = { mousedown: 'mouseup', touchstart: 'touchend', pointerdown: 'touchend', MSPointerDown: 'touchend' }; var MOVE = { mousedown: 'mousemove', touchstart: 'touchmove', pointerdown: 'touchmove', MSPointerDown: 'touchmove' }; var Draggable = Evented.extend({ options: { // @section // @aka Draggable options // @option clickTolerance: Number = 3 // The max number of pixels a user can shift the mouse pointer during a click // for it to be considered a valid click (as opposed to a mouse drag). clickTolerance: 3 }, // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options) // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default). initialize: function (element, dragStartTarget, preventOutline$$1, options) { setOptions(this, options); this._element = element; this._dragStartTarget = dragStartTarget || element; this._preventOutline = preventOutline$$1; }, // @method enable() // Enables the dragging ability enable: function () { if (this._enabled) { return; } on(this._dragStartTarget, START, this._onDown, this); this._enabled = true; }, // @method disable() // Disables the dragging ability disable: function () { if (!this._enabled) { return; } // If we're currently dragging this draggable, // disabling it counts as first ending the drag. if (Draggable._dragging === this) { this.finishDrag(); } off(this._dragStartTarget, START, this._onDown, this); this._enabled = false; this._moved = false; }, _onDown: function (e) { // Ignore simulated events, since we handle both touch and // mouse explicitly; otherwise we risk getting duplicates of // touch events, see #4315. // Also ignore the event if disabled; this happens in IE11 // under some circumstances, see #3666. if (e._simulated || !this._enabled) { return; } this._moved = false; if (hasClass(this._element, 'leaflet-zoom-anim')) { return; } if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; } Draggable._dragging = this; // Prevent dragging multiple objects at once. if (this._preventOutline) { preventOutline(this._element); } disableImageDrag(); disableTextSelection(); if (this._moving) { return; } // @event down: Event // Fired when a drag is about to start. this.fire('down'); var first = e.touches ? e.touches[0] : e, sizedParent = getSizedParentNode(this._element); this._startPoint = new Point(first.clientX, first.clientY); // Cache the scale, so that we can continuously compensate for it during drag (_onMove). this._parentScale = getScale(sizedParent); on(document, MOVE[e.type], this._onMove, this); on(document, END[e.type], this._onUp, this); }, _onMove: function (e) { // Ignore simulated events, since we handle both touch and // mouse explicitly; otherwise we risk getting duplicates of // touch events, see #4315. // Also ignore the event if disabled; this happens in IE11 // under some circumstances, see #3666. if (e._simulated || !this._enabled) { return; } if (e.touches && e.touches.length > 1) { this._moved = true; return; } var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e), offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint); if (!offset.x && !offset.y) { return; } if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; } // We assume that the parent container's position, border and scale do not change for the duration of the drag. // Therefore there is no need to account for the position and border (they are eliminated by the subtraction) // and we can use the cached value for the scale. offset.x /= this._parentScale.x; offset.y /= this._parentScale.y; preventDefault(e); if (!this._moved) { // @event dragstart: Event // Fired when a drag starts this.fire('dragstart'); this._moved = true; this._startPos = getPosition(this._element).subtract(offset); addClass(document.body, 'leaflet-dragging'); this._lastTarget = e.target || e.srcElement; // IE and Edge do not give the <use> element, so fetch it // if necessary if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) { this._lastTarget = this._lastTarget.correspondingUseElement; } addClass(this._lastTarget, 'leaflet-drag-target'); } this._newPos = this._startPos.add(offset); this._moving = true; cancelAnimFrame(this._animRequest); this._lastEvent = e; this._animRequest = requestAnimFrame(this._updatePosition, this, true); }, _updatePosition: function () { var e = {originalEvent: this._lastEvent}; // @event predrag: Event // Fired continuously during dragging *before* each corresponding // update of the element's position. this.fire('predrag', e); setPosition(this._element, this._newPos); // @event drag: Event // Fired continuously during dragging. this.fire('drag', e); }, _onUp: function (e) { // Ignore simulated events, since we handle both touch and // mouse explicitly; otherwise we risk getting duplicates of // touch events, see #4315. // Also ignore the event if disabled; this happens in IE11 // under some circumstances, see #3666. if (e._simulated || !this._enabled) { return; } this.finishDrag(); }, finishDrag: function () { removeClass(document.body, 'leaflet-dragging'); if (this._lastTarget) { removeClass(this._lastTarget, 'leaflet-drag-target'); this._lastTarget = null; } for (var i in MOVE) { off(document, MOVE[i], this._onMove, this); off(document, END[i], this._onUp, this); } enableImageDrag(); enableTextSelection(); if (this._moved && this._moving) { // ensure drag is not fired after dragend cancelAnimFrame(this._animRequest); // @event dragend: DragEndEvent // Fired when the drag ends. this.fire('dragend', { distance: this._newPos.distanceTo(this._startPos) }); } this._moving = false; Draggable._dragging = false; } }); /* * @namespace LineUtil * * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast. */ // Simplify polyline with vertex reduction and Douglas-Peucker simplification. // Improves rendering performance dramatically by lessening the number of points to draw. // @function simplify(points: Point[], tolerance: Number): Point[] // Dramatically reduces the number of points in a polyline while retaining // its shape and returns a new array of simplified points, using the // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm). // Used for a huge performance boost when processing/displaying Leaflet polylines for // each zoom level and also reducing visual noise. tolerance affects the amount of // simplification (lesser value means higher quality but slower and with more points). // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/). function simplify(points, tolerance) { if (!tolerance || !points.length) { return points.slice(); } var sqTolerance = tolerance * tolerance; // stage 1: vertex reduction points = _reducePoints(points, sqTolerance); // stage 2: Douglas-Peucker simplification points = _simplifyDP(points, sqTolerance); return points; } // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number // Returns the distance between point `p` and segment `p1` to `p2`. function pointToSegmentDistance(p, p1, p2) { return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true)); } // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number // Returns the closest point from a point `p` on a segment `p1` to `p2`. function closestPointOnSegment(p, p1, p2) { return _sqClosestPointOnSegment(p, p1, p2); } // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm function _simplifyDP(points, sqTolerance) { var len = points.length, ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array, markers = new ArrayConstructor(len); markers[0] = markers[len - 1] = 1; _simplifyDPStep(points, markers, sqTolerance, 0, len - 1); var i, newPoints = []; for (i = 0; i < len; i++) { if (markers[i]) { newPoints.push(points[i]); } } return newPoints; } function _simplifyDPStep(points, markers, sqTolerance, first, last) { var maxSqDist = 0, index, i, sqDist; for (i = first + 1; i <= last - 1; i++) { sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true); if (sqDist > maxSqDist) { index = i; maxSqDist = sqDist; } } if (maxSqDist > sqTolerance) { markers[index] = 1; _simplifyDPStep(points, markers, sqTolerance, first, index); _simplifyDPStep(points, markers, sqTolerance, index, last); } } // reduce points that are too close to each other to a single point function _reducePoints(points, sqTolerance) { var reducedPoints = [points[0]]; for (var i = 1, prev = 0, len = points.length; i < len; i++) { if (_sqDist(points[i], points[prev]) > sqTolerance) { reducedPoints.push(points[i]); prev = i; } } if (prev < len - 1) { reducedPoints.push(points[len - 1]); } return reducedPoints; } var _lastCode; // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean // Clips the segment a to b by rectangular bounds with the // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm) // (modifying the segment points directly!). Used by Leaflet to only show polyline // points that are on the screen or near, increasing performance. function clipSegment(a, b, bounds, useLastCode, round) { var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds), codeB = _getBitCode(b, bounds), codeOut, p, newCode; // save 2nd code to avoid calculating it on the next segment _lastCode = codeB; while (true) { // if a,b is inside the clip window (trivial accept) if (!(codeA | codeB)) { return [a, b]; } // if a,b is outside the clip window (trivial reject) if (codeA & codeB) { return false; } // other cases codeOut = codeA || codeB; p = _getEdgeIntersection(a, b, codeOut, bounds, round); newCode = _getBitCode(p, bounds); if (codeOut === codeA) { a = p; codeA = newCode; } else { b = p; codeB = newCode; } } } function _getEdgeIntersection(a, b, code, bounds, round) { var dx = b.x - a.x, dy = b.y - a.y, min = bounds.min, max = bounds.max, x, y; if (code & 8) { // top x = a.x + dx * (max.y - a.y) / dy; y = max.y; } else if (code & 4) { // bottom x = a.x + dx * (min.y - a.y) / dy; y = min.y; } else if (code & 2) { // right x = max.x; y = a.y + dy * (max.x - a.x) / dx; } else if (code & 1) { // left x = min.x; y = a.y + dy * (min.x - a.x) / dx; } return new Point(x, y, round); } function _getBitCode(p, bounds) { var code = 0; if (p.x < bounds.min.x) { // left code |= 1; } else if (p.x > bounds.max.x) { // right code |= 2; } if (p.y < bounds.min.y) { // bottom code |= 4; } else if (p.y > bounds.max.y) { // top code |= 8; } return code; } // square distance (to avoid unnecessary Math.sqrt calls) function _sqDist(p1, p2) { var dx = p2.x - p1.x, dy = p2.y - p1.y; return dx * dx + dy * dy; } // return closest point on segment or distance to that point function _sqClosestPointOnSegment(p, p1, p2, sqDist) { var x = p1.x, y = p1.y, dx = p2.x - x, dy = p2.y - y, dot = dx * dx + dy * dy, t; if (dot > 0) { t = ((p.x - x) * dx + (p.y - y) * dy) / dot; if (t > 1) { x = p2.x; y = p2.y; } else if (t > 0) { x += dx * t; y += dy * t; } } dx = p.x - x; dy = p.y - y; return sqDist ? dx * dx + dy * dy : new Point(x, y); } // @function isFlat(latlngs: LatLng[]): Boolean // Returns true if `latlngs` is a flat array, false is nested. function isFlat(latlngs) { return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined'); } function _flat(latlngs) { console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.'); return isFlat(latlngs); } var LineUtil = (Object.freeze || Object)({ simplify: simplify, pointToSegmentDistance: pointToSegmentDistance, closestPointOnSegment: closestPointOnSegment, clipSegment: clipSegment, _getEdgeIntersection: _getEdgeIntersection, _getBitCode: _getBitCode, _sqClosestPointOnSegment: _sqClosestPointOnSegment, isFlat: isFlat, _flat: _flat }); /* * @namespace PolyUtil * Various utility functions for polygon geometries. */ /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[] * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)). * Used by Leaflet to only show polygon points that are on the screen or near, increasing * performance. Note that polygon points needs different algorithm for clipping * than polyline, so there's a separate method for it. */ function clipPolygon(points, bounds, round) { var clippedPoints, edges = [1, 4, 2, 8], i, j, k, a, b, len, edge, p; for (i = 0, len = points.length; i < len; i++) { points[i]._code = _getBitCode(points[i], bounds); } // for each edge (left, bottom, right, top) for (k = 0; k < 4; k++) { edge = edges[k]; clippedPoints = []; for (i = 0, len = points.length, j = len - 1; i < len; j = i++) { a = points[i]; b = points[j]; // if a is inside the clip window if (!(a._code & edge)) { // if b is outside the clip window (a->b goes out of screen) if (b._code & edge) { p = _getEdgeIntersection(b, a, edge, bounds, round); p._code = _getBitCode(p, bounds); clippedPoints.push(p); } clippedPoints.push(a); // else if b is inside the clip window (a->b enters the screen) } else if (!(b._code & edge)) { p = _getEdgeIntersection(b, a, edge, bounds, round); p._code = _getBitCode(p, bounds); clippedPoints.push(p); } } points = clippedPoints; } return points; } var PolyUtil = (Object.freeze || Object)({ clipPolygon: clipPolygon }); /* * @namespace Projection * @section * Leaflet comes with a set of already defined Projections out of the box: * * @projection L.Projection.LonLat * * Equirectangular, or Plate Carree projection — the most simple projection, * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as * latitude. Also suitable for flat worlds, e.g. game maps. Used by the * `EPSG:4326` and `Simple` CRS. */ var LonLat = { project: function (latlng) { return new Point(latlng.lng, latlng.lat); }, unproject: function (point) { return new LatLng(point.y, point.x); }, bounds: new Bounds([-180, -90], [180, 90]) }; /* * @namespace Projection * @projection L.Projection.Mercator * * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS. */ var Mercator = { R: 6378137, R_MINOR: 6356752.314245179, bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]), project: function (latlng) { var d = Math.PI / 180, r = this.R, y = latlng.lat * d, tmp = this.R_MINOR / r, e = Math.sqrt(1 - tmp * tmp), con = e * Math.sin(y); var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2); y = -r * Math.log(Math.max(ts, 1E-10)); return new Point(latlng.lng * d * r, y); }, unproject: function (point) { var d = 180 / Math.PI, r = this.R, tmp = this.R_MINOR / r, e = Math.sqrt(1 - tmp * tmp), ts = Math.exp(-point.y / r), phi = Math.PI / 2 - 2 * Math.atan(ts); for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) { con = e * Math.sin(phi); con = Math.pow((1 - con) / (1 + con), e / 2); dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi; phi += dphi; } return new LatLng(phi * d, point.x * d / r); } }; /* * @class Projection * An object with methods for projecting geographical coordinates of the world onto * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection). * @property bounds: Bounds * The bounds (specified in CRS units) where the projection is valid * @method project(latlng: LatLng): Point * Projects geographical coordinates into a 2D point. * Only accepts actual `L.LatLng` instances, not arrays. * @method unproject(point: Point): LatLng * The inverse of `project`. Projects a 2D point into a geographical location. * Only accepts actual `L.Point` instances, not arrays. * Note that the projection instances do not inherit from Leafet's `Class` object, * and can't be instantiated. Also, new classes can't inherit from them, * and methods can't be added to them with the `include` function. */ var index = (Object.freeze || Object)({ LonLat: LonLat, Mercator: Mercator, SphericalMercator: SphericalMercator }); /* * @namespace CRS * @crs L.CRS.EPSG3395 * * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection. */ var EPSG3395 = extend({}, Earth, { code: 'EPSG:3395', projection: Mercator, transformation: (function () { var scale = 0.5 / (Math.PI * Mercator.R); return toTransformation(scale, 0.5, -scale, 0.5); }()) }); /* * @namespace CRS * @crs L.CRS.EPSG4326 * * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. * * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic), * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer` * with this CRS, ensure that there are two 256x256 pixel tiles covering the * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90), * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set. */ var EPSG4326 = extend({}, Earth, { code: 'EPSG:4326', projection: LonLat, transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5) }); /* * @namespace CRS * @crs L.CRS.Simple * * A simple CRS that maps longitude and latitude into `x` and `y` directly. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y` * axis should still be inverted (going from bottom to top). `distance()` returns * simple euclidean distance. */ var Simple = extend({}, CRS, { projection: LonLat, transformation: toTransformation(1, 0, -1, 0), scale: function (zoom) { return Math.pow(2, zoom); }, zoom: function (scale) { return Math.log(scale) / Math.LN2; }, distance: function (latlng1, latlng2) { var dx = latlng2.lng - latlng1.lng, dy = latlng2.lat - latlng1.lat; return Math.sqrt(dx * dx + dy * dy); }, infinite: true }); CRS.Earth = Earth; CRS.EPSG3395 = EPSG3395; CRS.EPSG3857 = EPSG3857; CRS.EPSG900913 = EPSG900913; CRS.EPSG4326 = EPSG4326; CRS.Simple = Simple; /* * @class Layer * @inherits Evented * @aka L.Layer * @aka ILayer * * A set of methods from the Layer base class that all Leaflet layers use. * Inherits all methods, options and events from `L.Evented`. * * @example * * ```js * var layer = L.marker(latlng).addTo(map); * layer.addTo(map); * layer.remove(); * ``` * * @event add: Event * Fired after the layer is added to a map * * @event remove: Event * Fired after the layer is removed from a map */ var Layer = Evented.extend({ // Classes extending `L.Layer` will inherit the following options: options: { // @option pane: String = 'overlayPane' // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. pane: 'overlayPane', // @option attribution: String = null // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. attribution: null, bubblingMouseEvents: true }, /* @section * Classes extending `L.Layer` will inherit the following methods: * * @method addTo(map: Map|LayerGroup): this * Adds the layer to the given map or layer group. */ addTo: function (map) { map.addLayer(this); return this; }, // @method remove: this // Removes the layer from the map it is currently active on. remove: function () { return this.removeFrom(this._map || this._mapToAdd); }, // @method removeFrom(map: Map): this // Removes the layer from the given map removeFrom: function (obj) { if (obj) { obj.removeLayer(this); } return this; }, // @method getPane(name? : String): HTMLElement // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. getPane: function (name) { return this._map.getPane(name ? (this.options[name] || name) : this.options.pane); }, addInteractiveTarget: function (targetEl) { this._map._targets[stamp(targetEl)] = this; return this; }, removeInteractiveTarget: function (targetEl) { delete this._map._targets[stamp(targetEl)]; return this; }, // @method getAttribution: String // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). getAttribution: function () { return this.options.attribution; }, _layerAdd: function (e) { var map = e.target; // check in case layer gets added and then removed before the map is ready if (!map.hasLayer(this)) { return; } this._map = map; this._zoomAnimated = map._zoomAnimated; if (this.getEvents) { var events = this.getEvents(); map.on(events, this); this.once('remove', function () { map.off(events, this); }, this); } this.onAdd(map); if (this.getAttribution && map.attributionControl) { map.attributionControl.addAttribution(this.getAttribution()); } this.fire('add'); map.fire('layeradd', {layer: this}); } }); /* @section Extension methods * @uninheritable * * Every layer should extend from `L.Layer` and (re-)implement the following methods. * * @method onAdd(map: Map): this * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer). * * @method onRemove(map: Map): this * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer). * * @method getEvents(): Object * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer. * * @method getAttribution(): String * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible. * * @method beforeAdd(map: Map): this * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only. */ /* @namespace Map * @section Layer events * * @event layeradd: LayerEvent * Fired when a new layer is added to the map. * * @event layerremove: LayerEvent * Fired when some layer is removed from the map * * @section Methods for Layers and Controls */ Map.include({ // @method addLayer(layer: Layer): this // Adds the given layer to the map addLayer: function (layer) { if (!layer._layerAdd) { throw new Error('The provided object is not a Layer.'); } var id = stamp(layer); if (this._layers[id]) { return this; } this._layers[id] = layer; layer._mapToAdd = this; if (layer.beforeAdd) { layer.beforeAdd(this); } this.whenReady(layer._layerAdd, layer); return this; }, // @method removeLayer(layer: Layer): this // Removes the given layer from the map. removeLayer: function (layer) { var id = stamp(layer); if (!this._layers[id]) { return this; } if (this._loaded) { layer.onRemove(this); } if (layer.getAttribution && this.attributionControl) { this.attributionControl.removeAttribution(layer.getAttribution()); } delete this._layers[id]; if (this._loaded) { this.fire('layerremove', {layer: layer}); layer.fire('remove'); } layer._map = layer._mapToAdd = null; return this; }, // @method hasLayer(layer: Layer): Boolean // Returns `true` if the given layer is currently added to the map hasLayer: function (layer) { return !!layer && (stamp(layer) in this._layers); }, /* @method eachLayer(fn: Function, context?: Object): this * Iterates over the layers of the map, optionally specifying context of the iterator function. * ``` * map.eachLayer(function(layer){ * layer.bindPopup('Hello'); * }); * ``` */ eachLayer: function (method, context) { for (var i in this._layers) { method.call(context, this._layers[i]); } return this; }, _addLayers: function (layers) { layers = layers ? (isArray(layers) ? layers : [layers]) : []; for (var i = 0, len = layers.length; i < len; i++) { this.addLayer(layers[i]); } }, _addZoomLimit: function (layer) { if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) { this._zoomBoundLayers[stamp(layer)] = layer; this._updateZoomLevels(); } }, _removeZoomLimit: function (layer) { var id = stamp(layer); if (this._zoomBoundLayers[id]) { delete this._zoomBoundLayers[id]; this._updateZoomLevels(); } }, _updateZoomLevels: function () { var minZoom = Infinity, maxZoom = -Infinity, oldZoomSpan = this._getZoomSpan(); for (var i in this._zoomBoundLayers) { var options = this._zoomBoundLayers[i].options; minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom); maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom); } this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom; this._layersMinZoom = minZoom === Infinity ? undefined : minZoom; // @section Map state change events // @event zoomlevelschange: Event // Fired when the number of zoomlevels on the map is changed due // to adding or removing a layer. if (oldZoomSpan !== this._getZoomSpan()) { this.fire('zoomlevelschange'); } if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) { this.setZoom(this._layersMaxZoom); } if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) { this.setZoom(this._layersMinZoom); } } }); /* * @class LayerGroup * @aka L.LayerGroup * @inherits Layer * * Used to group several layers and handle them as one. If you add it to the map, * any layers added or removed from the group will be added/removed on the map as * well. Extends `Layer`. * * @example * * ```js * L.layerGroup([marker1, marker2]) * .addLayer(polyline) * .addTo(map); * ``` */ var LayerGroup = Layer.extend({ initialize: function (layers, options) { setOptions(this, options); this._layers = {}; var i, len; if (layers) { for (i = 0, len = layers.length; i < len; i++) { this.addLayer(layers[i]); } } }, // @method addLayer(layer: Layer): this // Adds the given layer to the group. addLayer: function (layer) { var id = this.getLayerId(layer); this._layers[id] = layer; if (this._map) { this._map.addLayer(layer); } return this; }, // @method removeLayer(layer: Layer): this // Removes the given layer from the group. // @alternative // @method removeLayer(id: Number): this // Removes the layer with the given internal ID from the group. removeLayer: function (layer) { var id = layer in this._layers ? layer : this.getLayerId(layer); if (this._map && this._layers[id]) { this._map.removeLayer(this._layers[id]); } delete this._layers[id]; return this; }, // @method hasLayer(layer: Layer): Boolean // Returns `true` if the given layer is currently added to the group. // @alternative // @method hasLayer(id: Number): Boolean // Returns `true` if the given internal ID is currently added to the group. hasLayer: function (layer) { return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers); }, // @method clearLayers(): this // Removes all the layers from the group. clearLayers: function () { return this.eachLayer(this.removeLayer, this); }, // @method invoke(methodName: String, …): this // Calls `methodName` on every layer contained in this group, passing any // additional parameters. Has no effect if the layers contained do not // implement `methodName`. invoke: function (methodName) { var args = Array.prototype.slice.call(arguments, 1), i, layer; for (i in this._layers) { layer = this._layers[i]; if (layer[methodName]) { layer[methodName].apply(layer, args); } } return this; }, onAdd: function (map) { this.eachLayer(map.addLayer, map); }, onRemove: function (map) { this.eachLayer(map.removeLayer, map); }, // @method eachLayer(fn: Function, context?: Object): this // Iterates over the layers of the group, optionally specifying context of the iterator function. // ```js // group.eachLayer(function (layer) { // layer.bindPopup('Hello'); // }); // ``` eachLayer: function (method, context) { for (var i in this._layers) { method.call(context, this._layers[i]); } return this; }, // @method getLayer(id: Number): Layer // Returns the layer with the given internal ID. getLayer: function (id) { return this._layers[id]; }, // @method getLayers(): Layer[] // Returns an array of all the layers added to the group. getLayers: function () { var layers = []; this.eachLayer(layers.push, layers); return layers; }, // @method setZIndex(zIndex: Number): this // Calls `setZIndex` on every layer contained in this group, passing the z-index. setZIndex: function (zIndex) { return this.invoke('setZIndex', zIndex); }, // @method getLayerId(layer: Layer): Number // Returns the internal ID for a layer getLayerId: function (layer) { return stamp(layer); } }); // @factory L.layerGroup(layers?: Layer[], options?: Object) // Create a layer group, optionally given an initial set of layers and an `options` object. var layerGroup = function (layers, options) { return new LayerGroup(layers, options); }; /* * @class FeatureGroup * @aka L.FeatureGroup * @inherits LayerGroup * * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers: * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip)) * * Events are propagated to the `FeatureGroup`, so if the group has an event * handler, it will handle events from any of the layers. This includes mouse events * and custom events. * * Has `layeradd` and `layerremove` events * * @example * * ```js * L.featureGroup([marker1, marker2, polyline]) * .bindPopup('Hello world!') * .on('click', function() { alert('Clicked on a member of the group!'); }) * .addTo(map); * ``` */ var FeatureGroup = LayerGroup.extend({ addLayer: function (layer) { if (this.hasLayer(layer)) { return this; } layer.addEventParent(this); LayerGroup.prototype.addLayer.call(this, layer); // @event layeradd: LayerEvent // Fired when a layer is added to this `FeatureGroup` return this.fire('layeradd', {layer: layer}); }, removeLayer: function (layer) { if (!this.hasLayer(layer)) { return this; } if (layer in this._layers) { layer = this._layers[layer]; } layer.removeEventParent(this); LayerGroup.prototype.removeLayer.call(this, layer); // @event layerremove: LayerEvent // Fired when a layer is removed from this `FeatureGroup` return this.fire('layerremove', {layer: layer}); }, // @method setStyle(style: Path options): this // Sets the given path options to each layer of the group that has a `setStyle` method. setStyle: function (style) { return this.invoke('setStyle', style); }, // @method bringToFront(): this // Brings the layer group to the top of all other layers bringToFront: function () { return this.invoke('bringToFront'); }, // @method bringToBack(): this // Brings the layer group to the back of all other layers bringToBack: function () { return this.invoke('bringToBack'); }, // @method getBounds(): LatLngBounds // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children). getBounds: function () { var bounds = new LatLngBounds(); for (var id in this._layers) { var layer = this._layers[id]; bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng()); } return bounds; } }); // @factory L.featureGroup(layers: Layer[]) // Create a feature group, optionally given an initial set of layers. var featureGroup = function (layers) { return new FeatureGroup(layers); }; /* * @class Icon * @aka L.Icon * * Represents an icon to provide when creating a marker. * * @example * * ```js * var myIcon = L.icon({ * iconUrl: 'my-icon.png', * iconRetinaUrl: '[email protected]', * iconSize: [38, 95], * iconAnchor: [22, 94], * popupAnchor: [-3, -76], * shadowUrl: 'my-icon-shadow.png', * shadowRetinaUrl: '[email protected]', * shadowSize: [68, 95], * shadowAnchor: [22, 94] * }); * * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map); * ``` * * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default. * */ var Icon = Class.extend({ /* @section * @aka Icon options * * @option iconUrl: String = null * **(required)** The URL to the icon image (absolute or relative to your script path). * * @option iconRetinaUrl: String = null * The URL to a retina sized version of the icon image (absolute or relative to your * script path). Used for Retina screen devices. * * @option iconSize: Point = null * Size of the icon image in pixels. * * @option iconAnchor: Point = null * The coordinates of the "tip" of the icon (relative to its top left corner). The icon * will be aligned so that this point is at the marker's geographical location. Centered * by default if size is specified, also can be set in CSS with negative margins. * * @option popupAnchor: Point = [0, 0] * The coordinates of the point from which popups will "open", relative to the icon anchor. * * @option tooltipAnchor: Point = [0, 0] * The coordinates of the point from which tooltips will "open", relative to the icon anchor. * * @option shadowUrl: String = null * The URL to the icon shadow image. If not specified, no shadow image will be created. * * @option shadowRetinaUrl: String = null * * @option shadowSize: Point = null * Size of the shadow image in pixels. * * @option shadowAnchor: Point = null * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same * as iconAnchor if not specified). * * @option className: String = '' * A custom class name to assign to both icon and shadow images. Empty by default. */ options: { popupAnchor: [0, 0], tooltipAnchor: [0, 0] }, initialize: function (options) { setOptions(this, options); }, // @method createIcon(oldIcon?: HTMLElement): HTMLElement // Called internally when the icon has to be shown, returns a `<img>` HTML element // styled according to the options. createIcon: function (oldIcon) { return this._createIcon('icon', oldIcon); }, // @method createShadow(oldIcon?: HTMLElement): HTMLElement // As `createIcon`, but for the shadow beneath it. createShadow: function (oldIcon) { return this._createIcon('shadow', oldIcon); }, _createIcon: function (name, oldIcon) { var src = this._getIconUrl(name); if (!src) { if (name === 'icon') { throw new Error('iconUrl not set in Icon options (see the docs).'); } return null; } var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null); this._setIconStyles(img, name); return img; }, _setIconStyles: function (img, name) { var options = this.options; var sizeOption = options[name + 'Size']; if (typeof sizeOption === 'number') { sizeOption = [sizeOption, sizeOption]; } var size = toPoint(sizeOption), anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor || size && size.divideBy(2, true)); img.className = 'leaflet-marker-' + name + ' ' + (options.className || ''); if (anchor) { img.style.marginLeft = (-anchor.x) + 'px'; img.style.marginTop = (-anchor.y) + 'px'; } if (size) { img.style.width = size.x + 'px'; img.style.height = size.y + 'px'; } }, _createImg: function (src, el) { el = el || document.createElement('img'); el.src = src; return el; }, _getIconUrl: function (name) { return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url']; } }); // @factory L.icon(options: Icon options) // Creates an icon instance with the given options. function icon(options) { return new Icon(options); } /* * @miniclass Icon.Default (Icon) * @aka L.Icon.Default * @section * * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when * no icon is specified. Points to the blue marker image distributed with Leaflet * releases. * * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options` * (which is a set of `Icon options`). * * If you want to _completely_ replace the default icon, override the * `L.Marker.prototype.options.icon` with your own icon instead. */ var IconDefault = Icon.extend({ options: { iconUrl: 'marker-icon.png', iconRetinaUrl: 'marker-icon-2x.png', shadowUrl: 'marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], tooltipAnchor: [16, -28], shadowSize: [41, 41] }, _getIconUrl: function (name) { if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only IconDefault.imagePath = this._detectIconPath(); } // @option imagePath: String // `Icon.Default` will try to auto-detect the location of the // blue icon images. If you are placing these images in a non-standard // way, set this option to point to the right path. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name); }, _detectIconPath: function () { var el = create$1('div', 'leaflet-default-icon-path', document.body); var path = getStyle(el, 'background-image') || getStyle(el, 'backgroundImage'); // IE8 document.body.removeChild(el); if (path === null || path.indexOf('url') !== 0) { path = ''; } else { path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, ''); } return path; } }); /* * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable. */ /* @namespace Marker * @section Interaction handlers * * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example: * * ```js * marker.dragging.disable(); * ``` * * @property dragging: Handler * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)). */ var MarkerDrag = Handler.extend({ initialize: function (marker) { this._marker = marker; }, addHooks: function () { var icon = this._marker._icon; if (!this._draggable) { this._draggable = new Draggable(icon, icon, true); } this._draggable.on({ dragstart: this._onDragStart, predrag: this._onPreDrag, drag: this._onDrag, dragend: this._onDragEnd }, this).enable(); addClass(icon, 'leaflet-marker-draggable'); }, removeHooks: function () { this._draggable.off({ dragstart: this._onDragStart, predrag: this._onPreDrag, drag: this._onDrag, dragend: this._onDragEnd }, this).disable(); if (this._marker._icon) { removeClass(this._marker._icon, 'leaflet-marker-draggable'); } }, moved: function () { return this._draggable && this._draggable._moved; }, _adjustPan: function (e) { var marker = this._marker, map = marker._map, speed = this._marker.options.autoPanSpeed, padding = this._marker.options.autoPanPadding, iconPos = getPosition(marker._icon), bounds = map.getPixelBounds(), origin = map.getPixelOrigin(); var panBounds = toBounds( bounds.min._subtract(origin).add(padding), bounds.max._subtract(origin).subtract(padding) ); if (!panBounds.contains(iconPos)) { // Compute incremental movement var movement = toPoint( (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) - (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x), (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) - (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y) ).multiplyBy(speed); map.panBy(movement, {animate: false}); this._draggable._newPos._add(movement); this._draggable._startPos._add(movement); setPosition(marker._icon, this._draggable._newPos); this._onDrag(e); this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e)); } }, _onDragStart: function () { // @section Dragging events // @event dragstart: Event // Fired when the user starts dragging the marker. // @event movestart: Event // Fired when the marker starts moving (because of dragging). this._oldLatLng = this._marker.getLatLng(); this._marker .closePopup() .fire('movestart') .fire('dragstart'); }, _onPreDrag: function (e) { if (this._marker.options.autoPan) { cancelAnimFrame(this._panRequest); this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e)); } }, _onDrag: function (e) { var marker = this._marker, shadow = marker._shadow, iconPos = getPosition(marker._icon), latlng = marker._map.layerPointToLatLng(iconPos); // update shadow position if (shadow) { setPosition(shadow, iconPos); } marker._latlng = latlng; e.latlng = latlng; e.oldLatLng = this._oldLatLng; // @event drag: Event // Fired repeatedly while the user drags the marker. marker .fire('move', e) .fire('drag', e); }, _onDragEnd: function (e) { // @event dragend: DragEndEvent // Fired when the user stops dragging the marker. cancelAnimFrame(this._panRequest); // @event moveend: Event // Fired when the marker stops moving (because of dragging). delete this._oldLatLng; this._marker .fire('moveend') .fire('dragend', e); } }); /* * @class Marker * @inherits Interactive layer * @aka L.Marker * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`. * * @example * * ```js * L.marker([50.5, 30.5]).addTo(map); * ``` */ var Marker = Layer.extend({ // @section // @aka Marker options options: { // @option icon: Icon = * // Icon instance to use for rendering the marker. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon. // If not specified, a common instance of `L.Icon.Default` is used. icon: new IconDefault(), // Option inherited from "Interactive layer" abstract class interactive: true, // @option keyboard: Boolean = true // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. keyboard: true, // @option title: String = '' // Text for the browser tooltip that appear on marker hover (no tooltip by default). title: '', // @option alt: String = '' // Text for the `alt` attribute of the icon image (useful for accessibility). alt: '', // @option zIndexOffset: Number = 0 // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively). zIndexOffset: 0, // @option opacity: Number = 1.0 // The opacity of the marker. opacity: 1, // @option riseOnHover: Boolean = false // If `true`, the marker will get on top of others when you hover the mouse over it. riseOnHover: false, // @option riseOffset: Number = 250 // The z-index offset used for the `riseOnHover` feature. riseOffset: 250, // @option pane: String = 'markerPane' // `Map pane` where the markers icon will be added. pane: 'markerPane', // @option pane: String = 'shadowPane' // `Map pane` where the markers shadow will be added. shadowPane: 'shadowPane', // @option bubblingMouseEvents: Boolean = false // When `true`, a mouse event on this marker will trigger the same event on the map // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). bubblingMouseEvents: false, // @section Draggable marker options // @option draggable: Boolean = false // Whether the marker is draggable with mouse/touch or not. draggable: false, // @option autoPan: Boolean = false // Whether to pan the map when dragging this marker near its edge or not. autoPan: false, // @option autoPanPadding: Point = Point(50, 50) // Distance (in pixels to the left/right and to the top/bottom) of the // map edge to start panning the map. autoPanPadding: [50, 50], // @option autoPanSpeed: Number = 10 // Number of pixels the map should pan by. autoPanSpeed: 10 }, /* @section * * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods: */ initialize: function (latlng, options) { setOptions(this, options); this._latlng = toLatLng(latlng); }, onAdd: function (map) { this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation; if (this._zoomAnimated) { map.on('zoomanim', this._animateZoom, this); } this._initIcon(); this.update(); }, onRemove: function (map) { if (this.dragging && this.dragging.enabled()) { this.options.draggable = true; this.dragging.removeHooks(); } delete this.dragging; if (this._zoomAnimated) { map.off('zoomanim', this._animateZoom, this); } this._removeIcon(); this._removeShadow(); }, getEvents: function () { return { zoom: this.update, viewreset: this.update }; }, // @method getLatLng: LatLng // Returns the current geographical position of the marker. getLatLng: function () { return this._latlng; }, // @method setLatLng(latlng: LatLng): this // Changes the marker position to the given point. setLatLng: function (latlng) { var oldLatLng = this._latlng; this._latlng = toLatLng(latlng); this.update(); // @event move: Event // Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng}); }, // @method setZIndexOffset(offset: Number): this // Changes the [zIndex offset](#marker-zindexoffset) of the marker. setZIndexOffset: function (offset) { this.options.zIndexOffset = offset; return this.update(); }, // @method getIcon: Icon // Returns the current icon used by the marker getIcon: function () { return this.options.icon; }, // @method setIcon(icon: Icon): this // Changes the marker icon. setIcon: function (icon) { this.options.icon = icon; if (this._map) { this._initIcon(); this.update(); } if (this._popup) { this.bindPopup(this._popup, this._popup.options); } return this; }, getElement: function () { return this._icon; }, update: function () { if (this._icon && this._map) { var pos = this._map.latLngToLayerPoint(this._latlng).round(); this._setPos(pos); } return this; }, _initIcon: function () { var options = this.options, classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide'); var icon = options.icon.createIcon(this._icon), addIcon = false; // if we're not reusing the icon, remove the old one and init new one if (icon !== this._icon) { if (this._icon) { this._removeIcon(); } addIcon = true; if (options.title) { icon.title = options.title; } if (icon.tagName === 'IMG') { icon.alt = options.alt || ''; } } addClass(icon, classToAdd); if (options.keyboard) { icon.tabIndex = '0'; } this._icon = icon; if (options.riseOnHover) { this.on({ mouseover: this._bringToFront, mouseout: this._resetZIndex }); } var newShadow = options.icon.createShadow(this._shadow), addShadow = false; if (newShadow !== this._shadow) { this._removeShadow(); addShadow = true; } if (newShadow) { addClass(newShadow, classToAdd); newShadow.alt = ''; } this._shadow = newShadow; if (options.opacity < 1) { this._updateOpacity(); } if (addIcon) { this.getPane().appendChild(this._icon); } this._initInteraction(); if (newShadow && addShadow) { this.getPane(options.shadowPane).appendChild(this._shadow); } }, _removeIcon: function () { if (this.options.riseOnHover) { this.off({ mouseover: this._bringToFront, mouseout: this._resetZIndex }); } remove(this._icon); this.removeInteractiveTarget(this._icon); this._icon = null; }, _removeShadow: function () { if (this._shadow) { remove(this._shadow); } this._shadow = null; }, _setPos: function (pos) { if (this._icon) { setPosition(this._icon, pos); } if (this._shadow) { setPosition(this._shadow, pos); } this._zIndex = pos.y + this.options.zIndexOffset; this._resetZIndex(); }, _updateZIndex: function (offset) { if (this._icon) { this._icon.style.zIndex = this._zIndex + offset; } }, _animateZoom: function (opt) { var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round(); this._setPos(pos); }, _initInteraction: function () { if (!this.options.interactive) { return; } addClass(this._icon, 'leaflet-interactive'); this.addInteractiveTarget(this._icon); if (MarkerDrag) { var draggable = this.options.draggable; if (this.dragging) { draggable = this.dragging.enabled(); this.dragging.disable(); } this.dragging = new MarkerDrag(this); if (draggable) { this.dragging.enable(); } } }, // @method setOpacity(opacity: Number): this // Changes the opacity of the marker. setOpacity: function (opacity) { this.options.opacity = opacity; if (this._map) { this._updateOpacity(); } return this; }, _updateOpacity: function () { var opacity = this.options.opacity; if (this._icon) { setOpacity(this._icon, opacity); } if (this._shadow) { setOpacity(this._shadow, opacity); } }, _bringToFront: function () { this._updateZIndex(this.options.riseOffset); }, _resetZIndex: function () { this._updateZIndex(0); }, _getPopupAnchor: function () { return this.options.icon.options.popupAnchor; }, _getTooltipAnchor: function () { return this.options.icon.options.tooltipAnchor; } }); // factory L.marker(latlng: LatLng, options? : Marker options) // @factory L.marker(latlng: LatLng, options? : Marker options) // Instantiates a Marker object given a geographical point and optionally an options object. function marker(latlng, options) { return new Marker(latlng, options); } /* * @class Path * @aka L.Path * @inherits Interactive layer * * An abstract class that contains options and constants shared between vector * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`. */ var Path = Layer.extend({ // @section // @aka Path options options: { // @option stroke: Boolean = true // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. stroke: true, // @option color: String = '#3388ff' // Stroke color color: '#3388ff', // @option weight: Number = 3 // Stroke width in pixels weight: 3, // @option opacity: Number = 1.0 // Stroke opacity opacity: 1, // @option lineCap: String= 'round' // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. lineCap: 'round', // @option lineJoin: String = 'round' // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. lineJoin: 'round', // @option dashArray: String = null // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). dashArray: null, // @option dashOffset: String = null // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). dashOffset: null, // @option fill: Boolean = depends // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. fill: false, // @option fillColor: String = * // Fill color. Defaults to the value of the [`color`](#path-color) option fillColor: null, // @option fillOpacity: Number = 0.2 // Fill opacity. fillOpacity: 0.2, // @option fillRule: String = 'evenodd' // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. fillRule: 'evenodd', // className: '', // Option inherited from "Interactive layer" abstract class interactive: true, // @option bubblingMouseEvents: Boolean = true // When `true`, a mouse event on this path will trigger the same event on the map // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). bubblingMouseEvents: true }, beforeAdd: function (map) { // Renderer is set here because we need to call renderer.getEvents // before this.getEvents. this._renderer = map.getRenderer(this); }, onAdd: function () { this._renderer._initPath(this); this._reset(); this._renderer._addPath(this); }, onRemove: function () { this._renderer._removePath(this); }, // @method redraw(): this // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. redraw: function () { if (this._map) { this._renderer._updatePath(this); } return this; }, // @method setStyle(style: Path options): this // Changes the appearance of a Path based on the options in the `Path options` object. setStyle: function (style) { setOptions(this, style); if (this._renderer) { this._renderer._updateStyle(this); if (this.options.stroke && style && style.hasOwnProperty('weight')) { this._updateBounds(); } } return this; }, // @method bringToFront(): this // Brings the layer to the top of all path layers. bringToFront: function () { if (this._renderer) { this._renderer._bringToFront(this); } return this; }, // @method bringToBack(): this // Brings the layer to the bottom of all path layers. bringToBack: function () { if (this._renderer) { this._renderer._bringToBack(this); } return this; }, getElement: function () { return this._path; }, _reset: function () { // defined in child classes this._project(); this._update(); }, _clickTolerance: function () { // used when doing hit detection for Canvas layers return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance; } }); /* * @class CircleMarker * @aka L.CircleMarker * @inherits Path * * A circle of a fixed size with radius specified in pixels. Extends `Path`. */ var CircleMarker = Path.extend({ // @section // @aka CircleMarker options options: { fill: true, // @option radius: Number = 10 // Radius of the circle marker, in pixels radius: 10 }, initialize: function (latlng, options) { setOptions(this, options); this._latlng = toLatLng(latlng); this._radius = this.options.radius; }, // @method setLatLng(latLng: LatLng): this // Sets the position of a circle marker to a new location. setLatLng: function (latlng) { var oldLatLng = this._latlng; this._latlng = toLatLng(latlng); this.redraw(); // @event move: Event // Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng}); }, // @method getLatLng(): LatLng // Returns the current geographical position of the circle marker getLatLng: function () { return this._latlng; }, // @method setRadius(radius: Number): this // Sets the radius of a circle marker. Units are in pixels. setRadius: function (radius) { this.options.radius = this._radius = radius; return this.redraw(); }, // @method getRadius(): Number // Returns the current radius of the circle getRadius: function () { return this._radius; }, setStyle : function (options) { var radius = options && options.radius || this._radius; Path.prototype.setStyle.call(this, options); this.setRadius(radius); return this; }, _project: function () { this._point = this._map.latLngToLayerPoint(this._latlng); this._updateBounds(); }, _updateBounds: function () { var r = this._radius, r2 = this._radiusY || r, w = this._clickTolerance(), p = [r + w, r2 + w]; this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p)); }, _update: function () { if (this._map) { this._updatePath(); } }, _updatePath: function () { this._renderer._updateCircle(this); }, _empty: function () { return this._radius && !this._renderer._bounds.intersects(this._pxBounds); }, // Needed by the `Canvas` renderer for interactivity _containsPoint: function (p) { return p.distanceTo(this._point) <= this._radius + this._clickTolerance(); } }); // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options) // Instantiates a circle marker object given a geographical point, and an optional options object. function circleMarker(latlng, options) { return new CircleMarker(latlng, options); } /* * @class Circle * @aka L.Circle * @inherits CircleMarker * * A class for drawing circle overlays on a map. Extends `CircleMarker`. * * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion). * * @example * * ```js * L.circle([50.5, 30.5], {radius: 200}).addTo(map); * ``` */ var Circle = CircleMarker.extend({ initialize: function (latlng, options, legacyOptions) { if (typeof options === 'number') { // Backwards compatibility with 0.7.x factory (latlng, radius, options?) options = extend({}, legacyOptions, {radius: options}); } setOptions(this, options); this._latlng = toLatLng(latlng); if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); } // @section // @aka Circle options // @option radius: Number; Radius of the circle, in meters. this._mRadius = this.options.radius; }, // @method setRadius(radius: Number): this // Sets the radius of a circle. Units are in meters. setRadius: function (radius) { this._mRadius = radius; return this.redraw(); }, // @method getRadius(): Number // Returns the current radius of a circle. Units are in meters. getRadius: function () { return this._mRadius; }, // @method getBounds(): LatLngBounds // Returns the `LatLngBounds` of the path. getBounds: function () { var half = [this._radius, this._radiusY || this._radius]; return new LatLngBounds( this._map.layerPointToLatLng(this._point.subtract(half)), this._map.layerPointToLatLng(this._point.add(half))); }, setStyle: Path.prototype.setStyle, _project: function () { var lng = this._latlng.lng, lat = this._latlng.lat, map = this._map, crs = map.options.crs; if (crs.distance === Earth.distance) { var d = Math.PI / 180, latR = (this._mRadius / Earth.R) / d, top = map.project([lat + latR, lng]), bottom = map.project([lat - latR, lng]), p = top.add(bottom).divideBy(2), lat2 = map.unproject(p).lat, lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) / (Math.cos(lat * d) * Math.cos(lat2 * d))) / d; if (isNaN(lngR) || lngR === 0) { lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425 } this._point = p.subtract(map.getPixelOrigin()); this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x; this._radiusY = p.y - top.y; } else { var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0])); this._point = map.latLngToLayerPoint(this._latlng); this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x; } this._updateBounds(); } }); // @factory L.circle(latlng: LatLng, options?: Circle options) // Instantiates a circle object given a geographical point, and an options object // which contains the circle radius. // @alternative // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options) // Obsolete way of instantiating a circle, for compatibility with 0.7.x code. // Do not use in new applications or plugins. function circle(latlng, options, legacyOptions) { return new Circle(latlng, options, legacyOptions); } /* * @class Polyline * @aka L.Polyline * @inherits Path * * A class for drawing polyline overlays on a map. Extends `Path`. * * @example * * ```js * // create a red polyline from an array of LatLng points * var latlngs = [ * [45.51, -122.68], * [37.77, -122.43], * [34.04, -118.2] * ]; * * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map); * * // zoom the map to the polyline * map.fitBounds(polyline.getBounds()); * ``` * * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape: * * ```js * // create a red polyline from an array of arrays of LatLng points * var latlngs = [ * [[45.51, -122.68], * [37.77, -122.43], * [34.04, -118.2]], * [[40.78, -73.91], * [41.83, -87.62], * [32.76, -96.72]] * ]; * ``` */ var Polyline = Path.extend({ // @section // @aka Polyline options options: { // @option smoothFactor: Number = 1.0 // How much to simplify the polyline on each zoom level. More means // better performance and smoother look, and less means more accurate representation. smoothFactor: 1.0, // @option noClip: Boolean = false // Disable polyline clipping. noClip: false }, initialize: function (latlngs, options) { setOptions(this, options); this._setLatLngs(latlngs); }, // @method getLatLngs(): LatLng[] // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline. getLatLngs: function () { return this._latlngs; }, // @method setLatLngs(latlngs: LatLng[]): this // Replaces all the points in the polyline with the given array of geographical points. setLatLngs: function (latlngs) { this._setLatLngs(latlngs); return this.redraw(); }, // @method isEmpty(): Boolean // Returns `true` if the Polyline has no LatLngs. isEmpty: function () { return !this._latlngs.length; }, // @method closestLayerPoint(p: Point): Point // Returns the point closest to `p` on the Polyline. closestLayerPoint: function (p) { var minDistance = Infinity, minPoint = null, closest = _sqClosestPointOnSegment, p1, p2; for (var j = 0, jLen = this._parts.length; j < jLen; j++) { var points = this._parts[j]; for (var i = 1, len = points.length; i < len; i++) { p1 = points[i - 1]; p2 = points[i]; var sqDist = closest(p, p1, p2, true); if (sqDist < minDistance) { minDistance = sqDist; minPoint = closest(p, p1, p2); } } } if (minPoint) { minPoint.distance = Math.sqrt(minDistance); } return minPoint; }, // @method getCenter(): LatLng // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline. getCenter: function () { // throws error when not yet added to map as this center calculation requires projected coordinates if (!this._map) { throw new Error('Must add layer to map before using getCenter()'); } var i, halfDist, segDist, dist, p1, p2, ratio, points = this._rings[0], len = points.length; if (!len) { return null; } // polyline centroid algorithm; only uses the first ring if there are multiple for (i = 0, halfDist = 0; i < len - 1; i++) { halfDist += points[i].distanceTo(points[i + 1]) / 2; } // The line is so small in the current view that all points are on the same pixel. if (halfDist === 0) { return this._map.layerPointToLatLng(points[0]); } for (i = 0, dist = 0; i < len - 1; i++) { p1 = points[i]; p2 = points[i + 1]; segDist = p1.distanceTo(p2); dist += segDist; if (dist > halfDist) { ratio = (dist - halfDist) / segDist; return this._map.layerPointToLatLng([ p2.x - ratio * (p2.x - p1.x), p2.y - ratio * (p2.y - p1.y) ]); } } }, // @method getBounds(): LatLngBounds // Returns the `LatLngBounds` of the path. getBounds: function () { return this._bounds; }, // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this // Adds a given point to the polyline. By default, adds to the first ring of // the polyline in case of a multi-polyline, but can be overridden by passing // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)). addLatLng: function (latlng, latlngs) { latlngs = latlngs || this._defaultShape(); latlng = toLatLng(latlng); latlngs.push(latlng); this._bounds.extend(latlng); return this.redraw(); }, _setLatLngs: function (latlngs) { this._bounds = new LatLngBounds(); this._latlngs = this._convertLatLngs(latlngs); }, _defaultShape: function () { return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0]; }, // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way _convertLatLngs: function (latlngs) { var result = [], flat = isFlat(latlngs); for (var i = 0, len = latlngs.length; i < len; i++) { if (flat) { result[i] = toLatLng(latlngs[i]); this._bounds.extend(result[i]); } else { result[i] = this._convertLatLngs(latlngs[i]); } } return result; }, _project: function () { var pxBounds = new Bounds(); this._rings = []; this._projectLatlngs(this._latlngs, this._rings, pxBounds); if (this._bounds.isValid() && pxBounds.isValid()) { this._rawPxBounds = pxBounds; this._updateBounds(); } }, _updateBounds: function () { var w = this._clickTolerance(), p = new Point(w, w); this._pxBounds = new Bounds([ this._rawPxBounds.min.subtract(p), this._rawPxBounds.max.add(p) ]); }, // recursively turns latlngs into a set of rings with projected coordinates _projectLatlngs: function (latlngs, result, projectedBounds) { var flat = latlngs[0] instanceof LatLng, len = latlngs.length, i, ring; if (flat) { ring = []; for (i = 0; i < len; i++) { ring[i] = this._map.latLngToLayerPoint(latlngs[i]); projectedBounds.extend(ring[i]); } result.push(ring); } else { for (i = 0; i < len; i++) { this._projectLatlngs(latlngs[i], result, projectedBounds); } } }, // clip polyline by renderer bounds so that we have less to render for performance _clipPoints: function () { var bounds = this._renderer._bounds; this._parts = []; if (!this._pxBounds || !this._pxBounds.intersects(bounds)) { return; } if (this.options.noClip) { this._parts = this._rings; return; } var parts = this._parts, i, j, k, len, len2, segment, points; for (i = 0, k = 0, len = this._rings.length; i < len; i++) { points = this._rings[i]; for (j = 0, len2 = points.length; j < len2 - 1; j++) { segment = clipSegment(points[j], points[j + 1], bounds, j, true); if (!segment) { continue; } parts[k] = parts[k] || []; parts[k].push(segment[0]); // if segment goes out of screen, or it's the last one, it's the end of the line part if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) { parts[k].push(segment[1]); k++; } } } }, // simplify each clipped part of the polyline for performance _simplifyPoints: function () { var parts = this._parts, tolerance = this.options.smoothFactor; for (var i = 0, len = parts.length; i < len; i++) { parts[i] = simplify(parts[i], tolerance); } }, _update: function () { if (!this._map) { return; } this._clipPoints(); this._simplifyPoints(); this._updatePath(); }, _updatePath: function () { this._renderer._updatePoly(this); }, // Needed by the `Canvas` renderer for interactivity _containsPoint: function (p, closed) { var i, j, k, len, len2, part, w = this._clickTolerance(); if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; } // hit detection for polylines for (i = 0, len = this._parts.length; i < len; i++) { part = this._parts[i]; for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { if (!closed && (j === 0)) { continue; } if (pointToSegmentDistance(p, part[k], part[j]) <= w) { return true; } } } return false; } }); // @factory L.polyline(latlngs: LatLng[], options?: Polyline options) // Instantiates a polyline object given an array of geographical points and // optionally an options object. You can create a `Polyline` object with // multiple separate lines (`MultiPolyline`) by passing an array of arrays // of geographic points. function polyline(latlngs, options) { return new Polyline(latlngs, options); } // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1. Polyline._flat = _flat; /* * @class Polygon * @aka L.Polygon * @inherits Polyline * * A class for drawing polygon overlays on a map. Extends `Polyline`. * * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points. * * * @example * * ```js * // create a red polygon from an array of LatLng points * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]]; * * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map); * * // zoom the map to the polygon * map.fitBounds(polygon.getBounds()); * ``` * * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape: * * ```js * var latlngs = [ * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole * ]; * ``` * * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape. * * ```js * var latlngs = [ * [ // first polygon * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole * ], * [ // second polygon * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]] * ] * ]; * ``` */ var Polygon = Polyline.extend({ options: { fill: true }, isEmpty: function () { return !this._latlngs.length || !this._latlngs[0].length; }, getCenter: function () { // throws error when not yet added to map as this center calculation requires projected coordinates if (!this._map) { throw new Error('Must add layer to map before using getCenter()'); } var i, j, p1, p2, f, area, x, y, center, points = this._rings[0], len = points.length; if (!len) { return null; } // polygon centroid algorithm; only uses the first ring if there are multiple area = x = y = 0; for (i = 0, j = len - 1; i < len; j = i++) { p1 = points[i]; p2 = points[j]; f = p1.y * p2.x - p2.y * p1.x; x += (p1.x + p2.x) * f; y += (p1.y + p2.y) * f; area += f * 3; } if (area === 0) { // Polygon is so small that all points are on same pixel. center = points[0]; } else { center = [x / area, y / area]; } return this._map.layerPointToLatLng(center); }, _convertLatLngs: function (latlngs) { var result = Polyline.prototype._convertLatLngs.call(this, latlngs), len = result.length; // remove last point if it equals first one if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) { result.pop(); } return result; }, _setLatLngs: function (latlngs) { Polyline.prototype._setLatLngs.call(this, latlngs); if (isFlat(this._latlngs)) { this._latlngs = [this._latlngs]; } }, _defaultShape: function () { return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0]; }, _clipPoints: function () { // polygons need a different clipping algorithm so we redefine that var bounds = this._renderer._bounds, w = this.options.weight, p = new Point(w, w); // increase clip padding by stroke width to avoid stroke on clip edges bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p)); this._parts = []; if (!this._pxBounds || !this._pxBounds.intersects(bounds)) { return; } if (this.options.noClip) { this._parts = this._rings; return; } for (var i = 0, len = this._rings.length, clipped; i < len; i++) { clipped = clipPolygon(this._rings[i], bounds, true); if (clipped.length) { this._parts.push(clipped); } } }, _updatePath: function () { this._renderer._updatePoly(this, true); }, // Needed by the `Canvas` renderer for interactivity _containsPoint: function (p) { var inside = false, part, p1, p2, i, j, k, len, len2; if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; } // ray casting algorithm for detecting if point is in polygon for (i = 0, len = this._parts.length; i < len; i++) { part = this._parts[i]; for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) { p1 = part[j]; p2 = part[k]; if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { inside = !inside; } } } // also check if it's on polygon stroke return inside || Polyline.prototype._containsPoint.call(this, p, true); } }); // @factory L.polygon(latlngs: LatLng[], options?: Polyline options) function polygon(latlngs, options) { return new Polygon(latlngs, options); } /* * @class GeoJSON * @aka L.GeoJSON * @inherits FeatureGroup * * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse * GeoJSON data and display it on the map. Extends `FeatureGroup`. * * @example * * ```js * L.geoJSON(data, { * style: function (feature) { * return {color: feature.properties.color}; * } * }).bindPopup(function (layer) { * return layer.feature.properties.description; * }).addTo(map); * ``` */ var GeoJSON = FeatureGroup.extend({ /* @section * @aka GeoJSON options * * @option pointToLayer: Function = * * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally * called when data is added, passing the GeoJSON point feature and its `LatLng`. * The default is to spawn a default `Marker`: * ```js * function(geoJsonPoint, latlng) { * return L.marker(latlng); * } * ``` * * @option style: Function = * * A `Function` defining the `Path options` for styling GeoJSON lines and polygons, * called internally when data is added. * The default value is to not override any defaults: * ```js * function (geoJsonFeature) { * return {} * } * ``` * * @option onEachFeature: Function = * * A `Function` that will be called once for each created `Feature`, after it has * been created and styled. Useful for attaching events and popups to features. * The default is to do nothing with the newly created layers: * ```js * function (feature, layer) {} * ``` * * @option filter: Function = * * A `Function` that will be used to decide whether to include a feature or not. * The default is to include all features: * ```js * function (geoJsonFeature) { * return true; * } * ``` * Note: dynamically changing the `filter` option will have effect only on newly * added data. It will _not_ re-evaluate already included features. * * @option coordsToLatLng: Function = * * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s. * The default is the `coordsToLatLng` static method. * * @option markersInheritOptions: Boolean = false * Whether default Markers for "Point" type Features inherit from group options. */ initialize: function (geojson, options) { setOptions(this, options); this._layers = {}; if (geojson) { this.addData(geojson); } }, // @method addData( <GeoJSON> data ): this // Adds a GeoJSON object to the layer. addData: function (geojson) { var features = isArray(geojson) ? geojson : geojson.features, i, len, feature; if (features) { for (i = 0, len = features.length; i < len; i++) { // only add this if geometry or geometries are set and not null feature = features[i]; if (feature.geometries || feature.geometry || feature.features || feature.coordinates) { this.addData(feature); } } return this; } var options = this.options; if (options.filter && !options.filter(geojson)) { return this; } var layer = geometryToLayer(geojson, options); if (!layer) { return this; } layer.feature = asFeature(geojson); layer.defaultOptions = layer.options; this.resetStyle(layer); if (options.onEachFeature) { options.onEachFeature(geojson, layer); } return this.addLayer(layer); }, // @method resetStyle( <Path> layer? ): this // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events. // If `layer` is omitted, the style of all features in the current layer is reset. resetStyle: function (layer) { if (layer === undefined) { return this.eachLayer(this.resetStyle, this); } // reset any custom styles layer.options = extend({}, layer.defaultOptions); this._setLayerStyle(layer, this.options.style); return this; }, // @method setStyle( <Function> style ): this // Changes styles of GeoJSON vector layers with the given style function. setStyle: function (style) { return this.eachLayer(function (layer) { this._setLayerStyle(layer, style); }, this); }, _setLayerStyle: function (layer, style) { if (layer.setStyle) { if (typeof style === 'function') { style = style(layer.feature); } layer.setStyle(style); } } }); // @section // There are several static functions which can be called without instantiating L.GeoJSON: // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer // Creates a `Layer` from a given GeoJSON feature. Can use a custom // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng) // functions if provided as options. function geometryToLayer(geojson, options) { var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson, coords = geometry ? geometry.coordinates : null, layers = [], pointToLayer = options && options.pointToLayer, _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng, latlng, latlngs, i, len; if (!coords && !geometry) { return null; } switch (geometry.type) { case 'Point': latlng = _coordsToLatLng(coords); return _pointToLayer(pointToLayer, geojson, latlng, options); case 'MultiPoint': for (i = 0, len = coords.length; i < len; i++) { latlng = _coordsToLatLng(coords[i]); layers.push(_pointToLayer(pointToLayer, geojson, latlng, options)); } return new FeatureGroup(layers); case 'LineString': case 'MultiLineString': latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng); return new Polyline(latlngs, options); case 'Polygon': case 'MultiPolygon': latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng); return new Polygon(latlngs, options); case 'GeometryCollection': for (i = 0, len = geometry.geometries.length; i < len; i++) { var layer = geometryToLayer({ geometry: geometry.geometries[i], type: 'Feature', properties: geojson.properties }, options); if (layer) { layers.push(layer); } } return new FeatureGroup(layers); default: throw new Error('Invalid GeoJSON object.'); } } function _pointToLayer(pointToLayerFn, geojson, latlng, options) { return pointToLayerFn ? pointToLayerFn(geojson, latlng) : new Marker(latlng, options && options.markersInheritOptions && options); } // @function coordsToLatLng(coords: Array): LatLng // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude) // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points. function coordsToLatLng(coords) { return new LatLng(coords[1], coords[0], coords[2]); } // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default). // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) { var latlngs = []; for (var i = 0, len = coords.length, latlng; i < len; i++) { latlng = levelsDeep ? coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) : (_coordsToLatLng || coordsToLatLng)(coords[i]); latlngs.push(latlng); } return latlngs; } // @function latLngToCoords(latlng: LatLng, precision?: Number): Array // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng) function latLngToCoords(latlng, precision) { precision = typeof precision === 'number' ? precision : 6; return latlng.alt !== undefined ? [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] : [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)]; } // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs) // `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default. function latLngsToCoords(latlngs, levelsDeep, closed, precision) { var coords = []; for (var i = 0, len = latlngs.length; i < len; i++) { coords.push(levelsDeep ? latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) : latLngToCoords(latlngs[i], precision)); } if (!levelsDeep && closed) { coords.push(coords[0]); } return coords; } function getFeature(layer, newGeometry) { return layer.feature ? extend({}, layer.feature, {geometry: newGeometry}) : asFeature(newGeometry); } // @function asFeature(geojson: Object): Object // Normalize GeoJSON geometries/features into GeoJSON features. function asFeature(geojson) { if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') { return geojson; } return { type: 'Feature', properties: {}, geometry: geojson }; } var PointToGeoJSON = { toGeoJSON: function (precision) { return getFeature(this, { type: 'Point', coordinates: latLngToCoords(this.getLatLng(), precision) }); } }; // @namespace Marker // @section Other methods // @method toGeoJSON(precision?: Number): Object // `precision` is the number of decimal places for coordinates. // The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature). Marker.include(PointToGeoJSON); // @namespace CircleMarker // @method toGeoJSON(precision?: Number): Object // `precision` is the number of decimal places for coordinates. // The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature). Circle.include(PointToGeoJSON); CircleMarker.include(PointToGeoJSON); // @namespace Polyline // @method toGeoJSON(precision?: Number): Object // `precision` is the number of decimal places for coordinates. // The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature). Polyline.include({ toGeoJSON: function (precision) { var multi = !isFlat(this._latlngs); var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision); return getFeature(this, { type: (multi ? 'Multi' : '') + 'LineString', coordinates: coords }); } }); // @namespace Polygon // @method toGeoJSON(precision?: Number): Object // `precision` is the number of decimal places for coordinates. // The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature). Polygon.include({ toGeoJSON: function (precision) { var holes = !isFlat(this._latlngs), multi = holes && !isFlat(this._latlngs[0]); var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision); if (!holes) { coords = [coords]; } return getFeature(this, { type: (multi ? 'Multi' : '') + 'Polygon', coordinates: coords }); } }); // @namespace LayerGroup LayerGroup.include({ toMultiPoint: function (precision) { var coords = []; this.eachLayer(function (layer) { coords.push(layer.toGeoJSON(precision).geometry.coordinates); }); return getFeature(this, { type: 'MultiPoint', coordinates: coords }); }, // @method toGeoJSON(precision?: Number): Object // `precision` is the number of decimal places for coordinates. // The default value is 6 places. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`). toGeoJSON: function (precision) { var type = this.feature && this.feature.geometry && this.feature.geometry.type; if (type === 'MultiPoint') { return this.toMultiPoint(precision); } var isGeometryCollection = type === 'GeometryCollection', jsons = []; this.eachLayer(function (layer) { if (layer.toGeoJSON) { var json = layer.toGeoJSON(precision); if (isGeometryCollection) { jsons.push(json.geometry); } else { var feature = asFeature(json); // Squash nested feature collections if (feature.type === 'FeatureCollection') { jsons.push.apply(jsons, feature.features); } else { jsons.push(feature); } } } }); if (isGeometryCollection) { return getFeature(this, { geometries: jsons, type: 'GeometryCollection' }); } return { type: 'FeatureCollection', features: jsons }; } }); // @namespace GeoJSON // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options) // Creates a GeoJSON layer. Optionally accepts an object in // [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map // (you can alternatively add it later with `addData` method) and an `options` object. function geoJSON(geojson, options) { return new GeoJSON(geojson, options); } // Backward compatibility. var geoJson = geoJSON; /* * @class ImageOverlay * @aka L.ImageOverlay * @inherits Interactive layer * * Used to load and display a single image over specific bounds of the map. Extends `Layer`. * * @example * * ```js * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg', * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]]; * L.imageOverlay(imageUrl, imageBounds).addTo(map); * ``` */ var ImageOverlay = Layer.extend({ // @section // @aka ImageOverlay options options: { // @option opacity: Number = 1.0 // The opacity of the image overlay. opacity: 1, // @option alt: String = '' // Text for the `alt` attribute of the image (useful for accessibility). alt: '', // @option interactive: Boolean = false // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. interactive: false, // @option crossOrigin: Boolean|String = false // Whether the crossOrigin attribute will be added to the image. // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. crossOrigin: false, // @option errorOverlayUrl: String = '' // URL to the overlay image to show in place of the overlay that failed to load. errorOverlayUrl: '', // @option zIndex: Number = 1 // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer. zIndex: 1, // @option className: String = '' // A custom class name to assign to the image. Empty by default. className: '' }, initialize: function (url, bounds, options) { // (String, LatLngBounds, Object) this._url = url; this._bounds = toLatLngBounds(bounds); setOptions(this, options); }, onAdd: function () { if (!this._image) { this._initImage(); if (this.options.opacity < 1) { this._updateOpacity(); } } if (this.options.interactive) { addClass(this._image, 'leaflet-interactive'); this.addInteractiveTarget(this._image); } this.getPane().appendChild(this._image); this._reset(); }, onRemove: function () { remove(this._image); if (this.options.interactive) { this.removeInteractiveTarget(this._image); } }, // @method setOpacity(opacity: Number): this // Sets the opacity of the overlay. setOpacity: function (opacity) { this.options.opacity = opacity; if (this._image) { this._updateOpacity(); } return this; }, setStyle: function (styleOpts) { if (styleOpts.opacity) { this.setOpacity(styleOpts.opacity); } return this; }, // @method bringToFront(): this // Brings the layer to the top of all overlays. bringToFront: function () { if (this._map) { toFront(this._image); } return this; }, // @method bringToBack(): this // Brings the layer to the bottom of all overlays. bringToBack: function () { if (this._map) { toBack(this._image); } return this; }, // @method setUrl(url: String): this // Changes the URL of the image. setUrl: function (url) { this._url = url; if (this._image) { this._image.src = url; } return this; }, // @method setBounds(bounds: LatLngBounds): this // Update the bounds that this ImageOverlay covers setBounds: function (bounds) { this._bounds = toLatLngBounds(bounds); if (this._map) { this._reset(); } return this; }, getEvents: function () { var events = { zoom: this._reset, viewreset: this._reset }; if (this._zoomAnimated) { events.zoomanim = this._animateZoom; } return events; }, // @method setZIndex(value: Number): this // Changes the [zIndex](#imageoverlay-zindex) of the image overlay. setZIndex: function (value) { this.options.zIndex = value; this._updateZIndex(); return this; }, // @method getBounds(): LatLngBounds // Get the bounds that this ImageOverlay covers getBounds: function () { return this._bounds; }, // @method getElement(): HTMLElement // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement) // used by this overlay. getElement: function () { return this._image; }, _initImage: function () { var wasElementSupplied = this._url.tagName === 'IMG'; var img = this._image = wasElementSupplied ? this._url : create$1('img'); addClass(img, 'leaflet-image-layer'); if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); } if (this.options.className) { addClass(img, this.options.className); } img.onselectstart = falseFn; img.onmousemove = falseFn; // @event load: Event // Fired when the ImageOverlay layer has loaded its image img.onload = bind(this.fire, this, 'load'); img.onerror = bind(this._overlayOnError, this, 'error'); if (this.options.crossOrigin || this.options.crossOrigin === '') { img.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin; } if (this.options.zIndex) { this._updateZIndex(); } if (wasElementSupplied) { this._url = img.src; return; } img.src = this._url; img.alt = this.options.alt; }, _animateZoom: function (e) { var scale = this._map.getZoomScale(e.zoom), offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min; setTransform(this._image, offset, scale); }, _reset: function () { var image = this._image, bounds = new Bounds( this._map.latLngToLayerPoint(this._bounds.getNorthWest()), this._map.latLngToLayerPoint(this._bounds.getSouthEast())), size = bounds.getSize(); setPosition(image, bounds.min); image.style.width = size.x + 'px'; image.style.height = size.y + 'px'; }, _updateOpacity: function () { setOpacity(this._image, this.options.opacity); }, _updateZIndex: function () { if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) { this._image.style.zIndex = this.options.zIndex; } }, _overlayOnError: function () { // @event error: Event // Fired when the ImageOverlay layer fails to load its image this.fire('error'); var errorUrl = this.options.errorOverlayUrl; if (errorUrl && this._url !== errorUrl) { this._url = errorUrl; this._image.src = errorUrl; } } }); // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options) // Instantiates an image overlay object given the URL of the image and the // geographical bounds it is tied to. var imageOverlay = function (url, bounds, options) { return new ImageOverlay(url, bounds, options); }; /* * @class VideoOverlay * @aka L.VideoOverlay * @inherits ImageOverlay * * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`. * * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video) * HTML5 element. * * @example * * ```js * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm', * videoBounds = [[ 32, -130], [ 13, -100]]; * L.videoOverlay(videoUrl, videoBounds ).addTo(map); * ``` */ var VideoOverlay = ImageOverlay.extend({ // @section // @aka VideoOverlay options options: { // @option autoplay: Boolean = true // Whether the video starts playing automatically when loaded. autoplay: true, // @option loop: Boolean = true // Whether the video will loop back to the beginning when played. loop: true, // @option keepAspectRatio: Boolean = true // Whether the video will save aspect ratio after the projection. // Relevant for supported browsers. Browser compatibility- https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit keepAspectRatio: true }, _initImage: function () { var wasElementSupplied = this._url.tagName === 'VIDEO'; var vid = this._image = wasElementSupplied ? this._url : create$1('video'); addClass(vid, 'leaflet-image-layer'); if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); } if (this.options.className) { addClass(vid, this.options.className); } vid.onselectstart = falseFn; vid.onmousemove = falseFn; // @event load: Event // Fired when the video has finished loading the first frame vid.onloadeddata = bind(this.fire, this, 'load'); if (wasElementSupplied) { var sourceElements = vid.getElementsByTagName('source'); var sources = []; for (var j = 0; j < sourceElements.length; j++) { sources.push(sourceElements[j].src); } this._url = (sourceElements.length > 0) ? sources : [vid.src]; return; } if (!isArray(this._url)) { this._url = [this._url]; } if (!this.options.keepAspectRatio && vid.style.hasOwnProperty('objectFit')) { vid.style['objectFit'] = 'fill'; } vid.autoplay = !!this.options.autoplay; vid.loop = !!this.options.loop; for (var i = 0; i < this._url.length; i++) { var source = create$1('source'); source.src = this._url[i]; vid.appendChild(source); } } // @method getElement(): HTMLVideoElement // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement) // used by this overlay. }); // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options) // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the // geographical bounds it is tied to. function videoOverlay(video, bounds, options) { return new VideoOverlay(video, bounds, options); } /* * @class SVGOverlay * @aka L.SVGOverlay * @inherits ImageOverlay * * Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends `ImageOverlay`. * * An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element. * * @example * * ```js * var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg"); * svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg"); * svgElement.setAttribute('viewBox', "0 0 200 200"); * svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>'; * var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ]; * L.svgOverlay(svgElement, svgElementBounds).addTo(map); * ``` */ var SVGOverlay = ImageOverlay.extend({ _initImage: function () { var el = this._image = this._url; addClass(el, 'leaflet-image-layer'); if (this._zoomAnimated) { addClass(el, 'leaflet-zoom-animated'); } if (this.options.className) { addClass(el, this.options.className); } el.onselectstart = falseFn; el.onmousemove = falseFn; } // @method getElement(): SVGElement // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement) // used by this overlay. }); // @factory L.svgOverlay(svg: String|SVGElement, bounds: LatLngBounds, options?: SVGOverlay options) // Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to. // A viewBox attribute is required on the SVG element to zoom in and out properly. function svgOverlay(el, bounds, options) { return new SVGOverlay(el, bounds, options); } /* * @class DivOverlay * @inherits Layer * @aka L.DivOverlay * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins. */ // @namespace DivOverlay var DivOverlay = Layer.extend({ // @section // @aka DivOverlay options options: { // @option offset: Point = Point(0, 7) // The offset of the popup position. Useful to control the anchor // of the popup when opening it on some overlays. offset: [0, 7], // @option className: String = '' // A custom CSS class name to assign to the popup. className: '', // @option pane: String = 'popupPane' // `Map pane` where the popup will be added. pane: 'popupPane' }, initialize: function (options, source) { setOptions(this, options); this._source = source; }, onAdd: function (map) { this._zoomAnimated = map._zoomAnimated; if (!this._container) { this._initLayout(); } if (map._fadeAnimated) { setOpacity(this._container, 0); } clearTimeout(this._removeTimeout); this.getPane().appendChild(this._container); this.update(); if (map._fadeAnimated) { setOpacity(this._container, 1); } this.bringToFront(); }, onRemove: function (map) { if (map._fadeAnimated) { setOpacity(this._container, 0); this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200); } else { remove(this._container); } }, // @namespace Popup // @method getLatLng: LatLng // Returns the geographical point of popup. getLatLng: function () { return this._latlng; }, // @method setLatLng(latlng: LatLng): this // Sets the geographical point where the popup will open. setLatLng: function (latlng) { this._latlng = toLatLng(latlng); if (this._map) { this._updatePosition(); this._adjustPan(); } return this; }, // @method getContent: String|HTMLElement // Returns the content of the popup. getContent: function () { return this._content; }, // @method setContent(htmlContent: String|HTMLElement|Function): this // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup. setContent: function (content) { this._content = content; this.update(); return this; }, // @method getElement: String|HTMLElement // Alias for [getContent()](#popup-getcontent) getElement: function () { return this._container; }, // @method update: null // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded. update: function () { if (!this._map) { return; } this._container.style.visibility = 'hidden'; this._updateContent(); this._updateLayout(); this._updatePosition(); this._container.style.visibility = ''; this._adjustPan(); }, getEvents: function () { var events = { zoom: this._updatePosition, viewreset: this._updatePosition }; if (this._zoomAnimated) { events.zoomanim = this._animateZoom; } return events; }, // @method isOpen: Boolean // Returns `true` when the popup is visible on the map. isOpen: function () { return !!this._map && this._map.hasLayer(this); }, // @method bringToFront: this // Brings this popup in front of other popups (in the same map pane). bringToFront: function () { if (this._map) { toFront(this._container); } return this; }, // @method bringToBack: this // Brings this popup to the back of other popups (in the same map pane). bringToBack: function () { if (this._map) { toBack(this._container); } return this; }, _prepareOpen: function (parent, layer, latlng) { if (!(layer instanceof Layer)) { latlng = layer; layer = parent; } if (layer instanceof FeatureGroup) { for (var id in parent._layers) { layer = parent._layers[id]; break; } } if (!latlng) { if (layer.getCenter) { latlng = layer.getCenter(); } else if (layer.getLatLng) { latlng = layer.getLatLng(); } else { throw new Error('Unable to get source layer LatLng.'); } } // set overlay source to this layer this._source = layer; // update the overlay (content, layout, ect...) this.update(); return latlng; }, _updateContent: function () { if (!this._content) { return; } var node = this._contentNode; var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content; if (typeof content === 'string') { node.innerHTML = content; } else { while (node.hasChildNodes()) { node.removeChild(node.firstChild); } node.appendChild(content); } this.fire('contentupdate'); }, _updatePosition: function () { if (!this._map) { return; } var pos = this._map.latLngToLayerPoint(this._latlng), offset = toPoint(this.options.offset), anchor = this._getAnchor(); if (this._zoomAnimated) { setPosition(this._container, pos.add(anchor)); } else { offset = offset.add(pos).add(anchor); } var bottom = this._containerBottom = -offset.y, left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x; // bottom position the popup in case the height of the popup changes (images loading etc) this._container.style.bottom = bottom + 'px'; this._container.style.left = left + 'px'; }, _getAnchor: function () { return [0, 0]; } }); /* * @class Popup * @inherits DivOverlay * @aka L.Popup * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to * open popups while making sure that only one popup is open at one time * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want. * * @example * * If you want to just bind a popup to marker click and then open it, it's really easy: * * ```js * marker.bindPopup(popupContent).openPopup(); * ``` * Path overlays like polylines also have a `bindPopup` method. * Here's a more complicated way to open a popup on a map: * * ```js * var popup = L.popup() * .setLatLng(latlng) * .setContent('<p>Hello world!<br />This is a nice popup.</p>') * .openOn(map); * ``` */ // @namespace Popup var Popup = DivOverlay.extend({ // @section // @aka Popup options options: { // @option maxWidth: Number = 300 // Max width of the popup, in pixels. maxWidth: 300, // @option minWidth: Number = 50 // Min width of the popup, in pixels. minWidth: 50, // @option maxHeight: Number = null // If set, creates a scrollable container of the given height // inside a popup if its content exceeds it. maxHeight: null, // @option autoPan: Boolean = true // Set it to `false` if you don't want the map to do panning animation // to fit the opened popup. autoPan: true, // @option autoPanPaddingTopLeft: Point = null // The margin between the popup and the top left corner of the map // view after autopanning was performed. autoPanPaddingTopLeft: null, // @option autoPanPaddingBottomRight: Point = null // The margin between the popup and the bottom right corner of the map // view after autopanning was performed. autoPanPaddingBottomRight: null, // @option autoPanPadding: Point = Point(5, 5) // Equivalent of setting both top left and bottom right autopan padding to the same value. autoPanPadding: [5, 5], // @option keepInView: Boolean = false // Set it to `true` if you want to prevent users from panning the popup // off of the screen while it is open. keepInView: false, // @option closeButton: Boolean = true // Controls the presence of a close button in the popup. closeButton: true, // @option autoClose: Boolean = true // Set it to `false` if you want to override the default behavior of // the popup closing when another popup is opened. autoClose: true, // @option closeOnEscapeKey: Boolean = true // Set it to `false` if you want to override the default behavior of // the ESC key for closing of the popup. closeOnEscapeKey: true, // @option closeOnClick: Boolean = * // Set it if you want to override the default behavior of the popup closing when user clicks // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option. // @option className: String = '' // A custom CSS class name to assign to the popup. className: '' }, // @namespace Popup // @method openOn(map: Map): this // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`. openOn: function (map) { map.openPopup(this); return this; }, onAdd: function (map) { DivOverlay.prototype.onAdd.call(this, map); // @namespace Map // @section Popup events // @event popupopen: PopupEvent // Fired when a popup is opened in the map map.fire('popupopen', {popup: this}); if (this._source) { // @namespace Layer // @section Popup events // @event popupopen: PopupEvent // Fired when a popup bound to this layer is opened this._source.fire('popupopen', {popup: this}, true); // For non-path layers, we toggle the popup when clicking // again the layer, so prevent the map to reopen it. if (!(this._source instanceof Path)) { this._source.on('preclick', stopPropagation); } } }, onRemove: function (map) { DivOverlay.prototype.onRemove.call(this, map); // @namespace Map // @section Popup events // @event popupclose: PopupEvent // Fired when a popup in the map is closed map.fire('popupclose', {popup: this}); if (this._source) { // @namespace Layer // @section Popup events // @event popupclose: PopupEvent // Fired when a popup bound to this layer is closed this._source.fire('popupclose', {popup: this}, true); if (!(this._source instanceof Path)) { this._source.off('preclick', stopPropagation); } } }, getEvents: function () { var events = DivOverlay.prototype.getEvents.call(this); if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) { events.preclick = this._close; } if (this.options.keepInView) { events.moveend = this._adjustPan; } return events; }, _close: function () { if (this._map) { this._map.closePopup(this); } }, _initLayout: function () { var prefix = 'leaflet-popup', container = this._container = create$1('div', prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-animated'); var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container); this._contentNode = create$1('div', prefix + '-content', wrapper); disableClickPropagation(wrapper); disableScrollPropagation(this._contentNode); on(wrapper, 'contextmenu', stopPropagation); this._tipContainer = create$1('div', prefix + '-tip-container', container); this._tip = create$1('div', prefix + '-tip', this._tipContainer); if (this.options.closeButton) { var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container); closeButton.href = '#close'; closeButton.innerHTML = '&#215;'; on(closeButton, 'click', this._onCloseButtonClick, this); } }, _updateLayout: function () { var container = this._contentNode, style = container.style; style.width = ''; style.whiteSpace = 'nowrap'; var width = container.offsetWidth; width = Math.min(width, this.options.maxWidth); width = Math.max(width, this.options.minWidth); style.width = (width + 1) + 'px'; style.whiteSpace = ''; style.height = ''; var height = container.offsetHeight, maxHeight = this.options.maxHeight, scrolledClass = 'leaflet-popup-scrolled'; if (maxHeight && height > maxHeight) { style.height = maxHeight + 'px'; addClass(container, scrolledClass); } else { removeClass(container, scrolledClass); } this._containerWidth = this._container.offsetWidth; }, _animateZoom: function (e) { var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center), anchor = this._getAnchor(); setPosition(this._container, pos.add(anchor)); }, _adjustPan: function () { if (!this.options.autoPan) { return; } if (this._map._panAnim) { this._map._panAnim.stop(); } var map = this._map, marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0, containerHeight = this._container.offsetHeight + marginBottom, containerWidth = this._containerWidth, layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom); layerPos._add(getPosition(this._container)); var containerPos = map.layerPointToContainerPoint(layerPos), padding = toPoint(this.options.autoPanPadding), paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding), paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding), size = map.getSize(), dx = 0, dy = 0; if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right dx = containerPos.x + containerWidth - size.x + paddingBR.x; } if (containerPos.x - dx - paddingTL.x < 0) { // left dx = containerPos.x - paddingTL.x; } if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom dy = containerPos.y + containerHeight - size.y + paddingBR.y; } if (containerPos.y - dy - paddingTL.y < 0) { // top dy = containerPos.y - paddingTL.y; } // @namespace Map // @section Popup events // @event autopanstart: Event // Fired when the map starts autopanning when opening a popup. if (dx || dy) { map .fire('autopanstart') .panBy([dx, dy]); } }, _onCloseButtonClick: function (e) { this._close(); stop(e); }, _getAnchor: function () { // Where should we anchor the popup on the source layer? return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]); } }); // @namespace Popup // @factory L.popup(options?: Popup options, source?: Layer) // Instantiates a `Popup` object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers. var popup = function (options, source) { return new Popup(options, source); }; /* @namespace Map * @section Interaction Options * @option closePopupOnClick: Boolean = true * Set it to `false` if you don't want popups to close when user clicks the map. */ Map.mergeOptions({ closePopupOnClick: true }); // @namespace Map // @section Methods for Layers and Controls Map.include({ // @method openPopup(popup: Popup): this // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability). // @alternative // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this // Creates a popup with the specified content and options and opens it in the given point on a map. openPopup: function (popup, latlng, options) { if (!(popup instanceof Popup)) { popup = new Popup(options).setContent(popup); } if (latlng) { popup.setLatLng(latlng); } if (this.hasLayer(popup)) { return this; } if (this._popup && this._popup.options.autoClose) { this.closePopup(); } this._popup = popup; return this.addLayer(popup); }, // @method closePopup(popup?: Popup): this // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one). closePopup: function (popup) { if (!popup || popup === this._popup) { popup = this._popup; this._popup = null; } if (popup) { this.removeLayer(popup); } return this; } }); /* * @namespace Layer * @section Popup methods example * * All layers share a set of methods convenient for binding popups to it. * * ```js * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map); * layer.openPopup(); * layer.closePopup(); * ``` * * Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened. */ // @section Popup methods Layer.include({ // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this // Binds a popup to the layer with the passed `content` and sets up the // necessary event listeners. If a `Function` is passed it will receive // the layer as the first argument and should return a `String` or `HTMLElement`. bindPopup: function (content, options) { if (content instanceof Popup) { setOptions(content, options); this._popup = content; content._source = this; } else { if (!this._popup || options) { this._popup = new Popup(options, this); } this._popup.setContent(content); } if (!this._popupHandlersAdded) { this.on({ click: this._openPopup, keypress: this._onKeyPress, remove: this.closePopup, move: this._movePopup }); this._popupHandlersAdded = true; } return this; }, // @method unbindPopup(): this // Removes the popup previously bound with `bindPopup`. unbindPopup: function () { if (this._popup) { this.off({ click: this._openPopup, keypress: this._onKeyPress, remove: this.closePopup, move: this._movePopup }); this._popupHandlersAdded = false; this._popup = null; } return this; }, // @method openPopup(latlng?: LatLng): this // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. openPopup: function (layer, latlng) { if (this._popup && this._map) { latlng = this._popup._prepareOpen(this, layer, latlng); // open the popup on the map this._map.openPopup(this._popup, latlng); } return this; }, // @method closePopup(): this // Closes the popup bound to this layer if it is open. closePopup: function () { if (this._popup) { this._popup._close(); } return this; }, // @method togglePopup(): this // Opens or closes the popup bound to this layer depending on its current state. togglePopup: function (target) { if (this._popup) { if (this._popup._map) { this.closePopup(); } else { this.openPopup(target); } } return this; }, // @method isPopupOpen(): boolean // Returns `true` if the popup bound to this layer is currently open. isPopupOpen: function () { return (this._popup ? this._popup.isOpen() : false); }, // @method setPopupContent(content: String|HTMLElement|Popup): this // Sets the content of the popup bound to this layer. setPopupContent: function (content) { if (this._popup) { this._popup.setContent(content); } return this; }, // @method getPopup(): Popup // Returns the popup bound to this layer. getPopup: function () { return this._popup; }, _openPopup: function (e) { var layer = e.layer || e.target; if (!this._popup) { return; } if (!this._map) { return; } // prevent map click stop(e); // if this inherits from Path its a vector and we can just // open the popup at the new location if (layer instanceof Path) { this.openPopup(e.layer || e.target, e.latlng); return; } // otherwise treat it like a marker and figure out // if we should toggle it open/closed if (this._map.hasLayer(this._popup) && this._popup._source === layer) { this.closePopup(); } else { this.openPopup(layer, e.latlng); } }, _movePopup: function (e) { this._popup.setLatLng(e.latlng); }, _onKeyPress: function (e) { if (e.originalEvent.keyCode === 13) { this._openPopup(e); } } }); /* * @class Tooltip * @inherits DivOverlay * @aka L.Tooltip * Used to display small texts on top of map layers. * * @example * * ```js * marker.bindTooltip("my tooltip text").openTooltip(); * ``` * Note about tooltip offset. Leaflet takes two options in consideration * for computing tooltip offsetting: * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip. * Add a positive x offset to move the tooltip to the right, and a positive y offset to * move it to the bottom. Negatives will move to the left and top. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You * should adapt this value if you use a custom icon. */ // @namespace Tooltip var Tooltip = DivOverlay.extend({ // @section // @aka Tooltip options options: { // @option pane: String = 'tooltipPane' // `Map pane` where the tooltip will be added. pane: 'tooltipPane', // @option offset: Point = Point(0, 0) // Optional offset of the tooltip position. offset: [0, 0], // @option direction: String = 'auto' // Direction where to open the tooltip. Possible values are: `right`, `left`, // `top`, `bottom`, `center`, `auto`. // `auto` will dynamically switch between `right` and `left` according to the tooltip // position on the map. direction: 'auto', // @option permanent: Boolean = false // Whether to open the tooltip permanently or only on mouseover. permanent: false, // @option sticky: Boolean = false // If true, the tooltip will follow the mouse instead of being fixed at the feature center. sticky: false, // @option interactive: Boolean = false // If true, the tooltip will listen to the feature events. interactive: false, // @option opacity: Number = 0.9 // Tooltip container opacity. opacity: 0.9 }, onAdd: function (map) { DivOverlay.prototype.onAdd.call(this, map); this.setOpacity(this.options.opacity); // @namespace Map // @section Tooltip events // @event tooltipopen: TooltipEvent // Fired when a tooltip is opened in the map. map.fire('tooltipopen', {tooltip: this}); if (this._source) { // @namespace Layer // @section Tooltip events // @event tooltipopen: TooltipEvent // Fired when a tooltip bound to this layer is opened. this._source.fire('tooltipopen', {tooltip: this}, true); } }, onRemove: function (map) { DivOverlay.prototype.onRemove.call(this, map); // @namespace Map // @section Tooltip events // @event tooltipclose: TooltipEvent // Fired when a tooltip in the map is closed. map.fire('tooltipclose', {tooltip: this}); if (this._source) { // @namespace Layer // @section Tooltip events // @event tooltipclose: TooltipEvent // Fired when a tooltip bound to this layer is closed. this._source.fire('tooltipclose', {tooltip: this}, true); } }, getEvents: function () { var events = DivOverlay.prototype.getEvents.call(this); if (touch && !this.options.permanent) { events.preclick = this._close; } return events; }, _close: function () { if (this._map) { this._map.closeTooltip(this); } }, _initLayout: function () { var prefix = 'leaflet-tooltip', className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide'); this._contentNode = this._container = create$1('div', className); }, _updateLayout: function () {}, _adjustPan: function () {}, _setPosition: function (pos) { var map = this._map, container = this._container, centerPoint = map.latLngToContainerPoint(map.getCenter()), tooltipPoint = map.layerPointToContainerPoint(pos), direction = this.options.direction, tooltipWidth = container.offsetWidth, tooltipHeight = container.offsetHeight, offset = toPoint(this.options.offset), anchor = this._getAnchor(); if (direction === 'top') { pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true)); } else if (direction === 'bottom') { pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true)); } else if (direction === 'center') { pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true)); } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) { direction = 'right'; pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true)); } else { direction = 'left'; pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true)); } removeClass(container, 'leaflet-tooltip-right'); removeClass(container, 'leaflet-tooltip-left'); removeClass(container, 'leaflet-tooltip-top'); removeClass(container, 'leaflet-tooltip-bottom'); addClass(container, 'leaflet-tooltip-' + direction); setPosition(container, pos); }, _updatePosition: function () { var pos = this._map.latLngToLayerPoint(this._latlng); this._setPosition(pos); }, setOpacity: function (opacity) { this.options.opacity = opacity; if (this._container) { setOpacity(this._container, opacity); } }, _animateZoom: function (e) { var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center); this._setPosition(pos); }, _getAnchor: function () { // Where should we anchor the tooltip on the source layer? return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]); } }); // @namespace Tooltip // @factory L.tooltip(options?: Tooltip options, source?: Layer) // Instantiates a Tooltip object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers. var tooltip = function (options, source) { return new Tooltip(options, source); }; // @namespace Map // @section Methods for Layers and Controls Map.include({ // @method openTooltip(tooltip: Tooltip): this // Opens the specified tooltip. // @alternative // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this // Creates a tooltip with the specified content and options and open it. openTooltip: function (tooltip, latlng, options) { if (!(tooltip instanceof Tooltip)) { tooltip = new Tooltip(options).setContent(tooltip); } if (latlng) { tooltip.setLatLng(latlng); } if (this.hasLayer(tooltip)) { return this; } return this.addLayer(tooltip); }, // @method closeTooltip(tooltip?: Tooltip): this // Closes the tooltip given as parameter. closeTooltip: function (tooltip) { if (tooltip) { this.removeLayer(tooltip); } return this; } }); /* * @namespace Layer * @section Tooltip methods example * * All layers share a set of methods convenient for binding tooltips to it. * * ```js * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map); * layer.openTooltip(); * layer.closeTooltip(); * ``` */ // @section Tooltip methods Layer.include({ // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this // Binds a tooltip to the layer with the passed `content` and sets up the // necessary event listeners. If a `Function` is passed it will receive // the layer as the first argument and should return a `String` or `HTMLElement`. bindTooltip: function (content, options) { if (content instanceof Tooltip) { setOptions(content, options); this._tooltip = content; content._source = this; } else { if (!this._tooltip || options) { this._tooltip = new Tooltip(options, this); } this._tooltip.setContent(content); } this._initTooltipInteractions(); if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) { this.openTooltip(); } return this; }, // @method unbindTooltip(): this // Removes the tooltip previously bound with `bindTooltip`. unbindTooltip: function () { if (this._tooltip) { this._initTooltipInteractions(true); this.closeTooltip(); this._tooltip = null; } return this; }, _initTooltipInteractions: function (remove$$1) { if (!remove$$1 && this._tooltipHandlersAdded) { return; } var onOff = remove$$1 ? 'off' : 'on', events = { remove: this.closeTooltip, move: this._moveTooltip }; if (!this._tooltip.options.permanent) { events.mouseover = this._openTooltip; events.mouseout = this.closeTooltip; if (this._tooltip.options.sticky) { events.mousemove = this._moveTooltip; } if (touch) { events.click = this._openTooltip; } } else { events.add = this._openTooltip; } this[onOff](events); this._tooltipHandlersAdded = !remove$$1; }, // @method openTooltip(latlng?: LatLng): this // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. openTooltip: function (layer, latlng) { if (this._tooltip && this._map) { latlng = this._tooltip._prepareOpen(this, layer, latlng); // open the tooltip on the map this._map.openTooltip(this._tooltip, latlng); // Tooltip container may not be defined if not permanent and never // opened. if (this._tooltip.options.interactive && this._tooltip._container) { addClass(this._tooltip._container, 'leaflet-clickable'); this.addInteractiveTarget(this._tooltip._container); } } return this; }, // @method closeTooltip(): this // Closes the tooltip bound to this layer if it is open. closeTooltip: function () { if (this._tooltip) { this._tooltip._close(); if (this._tooltip.options.interactive && this._tooltip._container) { removeClass(this._tooltip._container, 'leaflet-clickable'); this.removeInteractiveTarget(this._tooltip._container); } } return this; }, // @method toggleTooltip(): this // Opens or closes the tooltip bound to this layer depending on its current state. toggleTooltip: function (target) { if (this._tooltip) { if (this._tooltip._map) { this.closeTooltip(); } else { this.openTooltip(target); } } return this; }, // @method isTooltipOpen(): boolean // Returns `true` if the tooltip bound to this layer is currently open. isTooltipOpen: function () { return this._tooltip.isOpen(); }, // @method setTooltipContent(content: String|HTMLElement|Tooltip): this // Sets the content of the tooltip bound to this layer. setTooltipContent: function (content) { if (this._tooltip) { this._tooltip.setContent(content); } return this; }, // @method getTooltip(): Tooltip // Returns the tooltip bound to this layer. getTooltip: function () { return this._tooltip; }, _openTooltip: function (e) { var layer = e.layer || e.target; if (!this._tooltip || !this._map) { return; } this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined); }, _moveTooltip: function (e) { var latlng = e.latlng, containerPoint, layerPoint; if (this._tooltip.options.sticky && e.originalEvent) { containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent); layerPoint = this._map.containerPointToLayerPoint(containerPoint); latlng = this._map.layerPointToLatLng(layerPoint); } this._tooltip.setLatLng(latlng); } }); /* * @class DivIcon * @aka L.DivIcon * @inherits Icon * * Represents a lightweight icon for markers that uses a simple `<div>` * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options. * * @example * ```js * var myIcon = L.divIcon({className: 'my-div-icon'}); * // you can set .my-div-icon styles in CSS * * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map); * ``` * * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow. */ var DivIcon = Icon.extend({ options: { // @section // @aka DivIcon options iconSize: [12, 12], // also can be set through CSS // iconAnchor: (Point), // popupAnchor: (Point), // @option html: String|HTMLElement = '' // Custom HTML code to put inside the div element, empty by default. Alternatively, // an instance of `HTMLElement`. html: false, // @option bgPos: Point = [0, 0] // Optional relative position of the background, in pixels bgPos: null, className: 'leaflet-div-icon' }, createIcon: function (oldIcon) { var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'), options = this.options; if (options.html instanceof Element) { empty(div); div.appendChild(options.html); } else { div.innerHTML = options.html !== false ? options.html : ''; } if (options.bgPos) { var bgPos = toPoint(options.bgPos); div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px'; } this._setIconStyles(div, 'icon'); return div; }, createShadow: function () { return null; } }); // @factory L.divIcon(options: DivIcon options) // Creates a `DivIcon` instance with the given options. function divIcon(options) { return new DivIcon(options); } Icon.Default = IconDefault; /* * @class GridLayer * @inherits Layer * @aka L.GridLayer * * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`. * GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you. * * * @section Synchronous usage * @example * * To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a `Point` object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile. * * ```js * var CanvasLayer = L.GridLayer.extend({ * createTile: function(coords){ * // create a <canvas> element for drawing * var tile = L.DomUtil.create('canvas', 'leaflet-tile'); * * // setup tile width and height according to the options * var size = this.getTileSize(); * tile.width = size.x; * tile.height = size.y; * * // get a canvas context and draw something on it using coords.x, coords.y and coords.z * var ctx = tile.getContext('2d'); * * // return the tile so it can be rendered on screen * return tile; * } * }); * ``` * * @section Asynchronous usage * @example * * Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback. * * ```js * var CanvasLayer = L.GridLayer.extend({ * createTile: function(coords, done){ * var error; * * // create a <canvas> element for drawing * var tile = L.DomUtil.create('canvas', 'leaflet-tile'); * * // setup tile width and height according to the options * var size = this.getTileSize(); * tile.width = size.x; * tile.height = size.y; * * // draw something asynchronously and pass the tile to the done() callback * setTimeout(function() { * done(error, tile); * }, 1000); * * return tile; * } * }); * ``` * * @section */ var GridLayer = Layer.extend({ // @section // @aka GridLayer options options: { // @option tileSize: Number|Point = 256 // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise. tileSize: 256, // @option opacity: Number = 1.0 // Opacity of the tiles. Can be used in the `createTile()` function. opacity: 1, // @option updateWhenIdle: Boolean = (depends) // Load new tiles only when panning ends. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers. updateWhenIdle: mobile, // @option updateWhenZooming: Boolean = true // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends. updateWhenZooming: true, // @option updateInterval: Number = 200 // Tiles will not update more than once every `updateInterval` milliseconds when panning. updateInterval: 200, // @option zIndex: Number = 1 // The explicit zIndex of the tile layer. zIndex: 1, // @option bounds: LatLngBounds = undefined // If set, tiles will only be loaded inside the set `LatLngBounds`. bounds: null, // @option minZoom: Number = 0 // The minimum zoom level down to which this layer will be displayed (inclusive). minZoom: 0, // @option maxZoom: Number = undefined // The maximum zoom level up to which this layer will be displayed (inclusive). maxZoom: undefined, // @option maxNativeZoom: Number = undefined // Maximum zoom number the tile source has available. If it is specified, // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded // from `maxNativeZoom` level and auto-scaled. maxNativeZoom: undefined, // @option minNativeZoom: Number = undefined // Minimum zoom number the tile source has available. If it is specified, // the tiles on all zoom levels lower than `minNativeZoom` will be loaded // from `minNativeZoom` level and auto-scaled. minNativeZoom: undefined, // @option noWrap: Boolean = false // Whether the layer is wrapped around the antimeridian. If `true`, the // GridLayer will only be displayed once at low zoom levels. Has no // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting // tiles outside the CRS limits. noWrap: false, // @option pane: String = 'tilePane' // `Map pane` where the grid layer will be added. pane: 'tilePane', // @option className: String = '' // A custom class name to assign to the tile layer. Empty by default. className: '', // @option keepBuffer: Number = 2 // When panning the map, keep this many rows and columns of tiles before unloading them. keepBuffer: 2 }, initialize: function (options) { setOptions(this, options); }, onAdd: function () { this._initContainer(); this._levels = {}; this._tiles = {}; this._resetView(); this._update(); }, beforeAdd: function (map) { map._addZoomLimit(this); }, onRemove: function (map) { this._removeAllTiles(); remove(this._container); map._removeZoomLimit(this); this._container = null; this._tileZoom = undefined; }, // @method bringToFront: this // Brings the tile layer to the top of all tile layers. bringToFront: function () { if (this._map) { toFront(this._container); this._setAutoZIndex(Math.max); } return this; }, // @method bringToBack: this // Brings the tile layer to the bottom of all tile layers. bringToBack: function () { if (this._map) { toBack(this._container); this._setAutoZIndex(Math.min); } return this; }, // @method getContainer: HTMLElement // Returns the HTML element that contains the tiles for this layer. getContainer: function () { return this._container; }, // @method setOpacity(opacity: Number): this // Changes the [opacity](#gridlayer-opacity) of the grid layer. setOpacity: function (opacity) { this.options.opacity = opacity; this._updateOpacity(); return this; }, // @method setZIndex(zIndex: Number): this // Changes the [zIndex](#gridlayer-zindex) of the grid layer. setZIndex: function (zIndex) { this.options.zIndex = zIndex; this._updateZIndex(); return this; }, // @method isLoading: Boolean // Returns `true` if any tile in the grid layer has not finished loading. isLoading: function () { return this._loading; }, // @method redraw: this // Causes the layer to clear all the tiles and request them again. redraw: function () { if (this._map) { this._removeAllTiles(); this._update(); } return this; }, getEvents: function () { var events = { viewprereset: this._invalidateAll, viewreset: this._resetView, zoom: this._resetView, moveend: this._onMoveEnd }; if (!this.options.updateWhenIdle) { // update tiles on move, but not more often than once per given interval if (!this._onMove) { this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this); } events.move = this._onMove; } if (this._zoomAnimated) { events.zoomanim = this._animateZoom; } return events; }, // @section Extension methods // Layers extending `GridLayer` shall reimplement the following method. // @method createTile(coords: Object, done?: Function): HTMLElement // Called only internally, must be overridden by classes extending `GridLayer`. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback // is specified, it must be called when the tile has finished loading and drawing. createTile: function () { return document.createElement('div'); }, // @section // @method getTileSize: Point // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method. getTileSize: function () { var s = this.options.tileSize; return s instanceof Point ? s : new Point(s, s); }, _updateZIndex: function () { if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) { this._container.style.zIndex = this.options.zIndex; } }, _setAutoZIndex: function (compare) { // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back) var layers = this.getPane().children, edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min for (var i = 0, len = layers.length, zIndex; i < len; i++) { zIndex = layers[i].style.zIndex; if (layers[i] !== this._container && zIndex) { edgeZIndex = compare(edgeZIndex, +zIndex); } } if (isFinite(edgeZIndex)) { this.options.zIndex = edgeZIndex + compare(-1, 1); this._updateZIndex(); } }, _updateOpacity: function () { if (!this._map) { return; } // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles if (ielt9) { return; } setOpacity(this._container, this.options.opacity); var now = +new Date(), nextFrame = false, willPrune = false; for (var key in this._tiles) { var tile = this._tiles[key]; if (!tile.current || !tile.loaded) { continue; } var fade = Math.min(1, (now - tile.loaded) / 200); setOpacity(tile.el, fade); if (fade < 1) { nextFrame = true; } else { if (tile.active) { willPrune = true; } else { this._onOpaqueTile(tile); } tile.active = true; } } if (willPrune && !this._noPrune) { this._pruneTiles(); } if (nextFrame) { cancelAnimFrame(this._fadeFrame); this._fadeFrame = requestAnimFrame(this._updateOpacity, this); } }, _onOpaqueTile: falseFn, _initContainer: function () { if (this._container) { return; } this._container = create$1('div', 'leaflet-layer ' + (this.options.className || '')); this._updateZIndex(); if (this.options.opacity < 1) { this._updateOpacity(); } this.getPane().appendChild(this._container); }, _updateLevels: function () { var zoom = this._tileZoom, maxZoom = this.options.maxZoom; if (zoom === undefined) { return undefined; } for (var z in this._levels) { if (this._levels[z].el.children.length || z === zoom) { this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z); this._onUpdateLevel(z); } else { remove(this._levels[z].el); this._removeTilesAtZoom(z); this._onRemoveLevel(z); delete this._levels[z]; } } var level = this._levels[zoom], map = this._map; if (!level) { level = this._levels[zoom] = {}; level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container); level.el.style.zIndex = maxZoom; level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round(); level.zoom = zoom; this._setZoomTransform(level, map.getCenter(), map.getZoom()); // force the browser to consider the newly added element for transition falseFn(level.el.offsetWidth); this._onCreateLevel(level); } this._level = level; return level; }, _onUpdateLevel: falseFn, _onRemoveLevel: falseFn, _onCreateLevel: falseFn, _pruneTiles: function () { if (!this._map) { return; } var key, tile; var zoom = this._map.getZoom(); if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { this._removeAllTiles(); return; } for (key in this._tiles) { tile = this._tiles[key]; tile.retain = tile.current; } for (key in this._tiles) { tile = this._tiles[key]; if (tile.current && !tile.active) { var coords = tile.coords; if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) { this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2); } } } for (key in this._tiles) { if (!this._tiles[key].retain) { this._removeTile(key); } } }, _removeTilesAtZoom: function (zoom) { for (var key in this._tiles) { if (this._tiles[key].coords.z !== zoom) { continue; } this._removeTile(key); } }, _removeAllTiles: function () { for (var key in this._tiles) { this._removeTile(key); } }, _invalidateAll: function () { for (var z in this._levels) { remove(this._levels[z].el); this._onRemoveLevel(z); delete this._levels[z]; } this._removeAllTiles(); this._tileZoom = undefined; }, _retainParent: function (x, y, z, minZoom) { var x2 = Math.floor(x / 2), y2 = Math.floor(y / 2), z2 = z - 1, coords2 = new Point(+x2, +y2); coords2.z = +z2; var key = this._tileCoordsToKey(coords2), tile = this._tiles[key]; if (tile && tile.active) { tile.retain = true; return true; } else if (tile && tile.loaded) { tile.retain = true; } if (z2 > minZoom) { return this._retainParent(x2, y2, z2, minZoom); } return false; }, _retainChildren: function (x, y, z, maxZoom) { for (var i = 2 * x; i < 2 * x + 2; i++) { for (var j = 2 * y; j < 2 * y + 2; j++) { var coords = new Point(i, j); coords.z = z + 1; var key = this._tileCoordsToKey(coords), tile = this._tiles[key]; if (tile && tile.active) { tile.retain = true; continue; } else if (tile && tile.loaded) { tile.retain = true; } if (z + 1 < maxZoom) { this._retainChildren(i, j, z + 1, maxZoom); } } } }, _resetView: function (e) { var animating = e && (e.pinch || e.flyTo); this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating); }, _animateZoom: function (e) { this._setView(e.center, e.zoom, true, e.noUpdate); }, _clampZoom: function (zoom) { var options = this.options; if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) { return options.minNativeZoom; } if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) { return options.maxNativeZoom; } return zoom; }, _setView: function (center, zoom, noPrune, noUpdate) { var tileZoom = this._clampZoom(Math.round(zoom)); if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) || (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) { tileZoom = undefined; } var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom); if (!noUpdate || tileZoomChanged) { this._tileZoom = tileZoom; if (this._abortLoading) { this._abortLoading(); } this._updateLevels(); this._resetGrid(); if (tileZoom !== undefined) { this._update(center); } if (!noPrune) { this._pruneTiles(); } // Flag to prevent _updateOpacity from pruning tiles during // a zoom anim or a pinch gesture this._noPrune = !!noPrune; } this._setZoomTransforms(center, zoom); }, _setZoomTransforms: function (center, zoom) { for (var i in this._levels) { this._setZoomTransform(this._levels[i], center, zoom); } }, _setZoomTransform: function (level, center, zoom) { var scale = this._map.getZoomScale(zoom, level.zoom), translate = level.origin.multiplyBy(scale) .subtract(this._map._getNewPixelOrigin(center, zoom)).round(); if (any3d) { setTransform(level.el, translate, scale); } else { setPosition(level.el, translate); } }, _resetGrid: function () { var map = this._map, crs = map.options.crs, tileSize = this._tileSize = this.getTileSize(), tileZoom = this._tileZoom; var bounds = this._map.getPixelWorldBounds(this._tileZoom); if (bounds) { this._globalTileRange = this._pxBoundsToTileRange(bounds); } this._wrapX = crs.wrapLng && !this.options.noWrap && [ Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x), Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y) ]; this._wrapY = crs.wrapLat && !this.options.noWrap && [ Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x), Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y) ]; }, _onMoveEnd: function () { if (!this._map || this._map._animatingZoom) { return; } this._update(); }, _getTiledPixelBounds: function (center) { var map = this._map, mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(), scale = map.getZoomScale(mapZoom, this._tileZoom), pixelCenter = map.project(center, this._tileZoom).floor(), halfSize = map.getSize().divideBy(scale * 2); return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize)); }, // Private method to load tiles in the grid's active zoom level according to map bounds _update: function (center) { var map = this._map; if (!map) { return; } var zoom = this._clampZoom(map.getZoom()); if (center === undefined) { center = map.getCenter(); } if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom var pixelBounds = this._getTiledPixelBounds(center), tileRange = this._pxBoundsToTileRange(pixelBounds), tileCenter = tileRange.getCenter(), queue = [], margin = this.options.keepBuffer, noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]), tileRange.getTopRight().add([margin, -margin])); // Sanity check: panic if the tile range contains Infinity somewhere. if (!(isFinite(tileRange.min.x) && isFinite(tileRange.min.y) && isFinite(tileRange.max.x) && isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); } for (var key in this._tiles) { var c = this._tiles[key].coords; if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) { this._tiles[key].current = false; } } // _update just loads more tiles. If the tile zoom level differs too much // from the map's, let _setView reset levels and prune old tiles. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; } // create a queue of coordinates to load tiles from for (var j = tileRange.min.y; j <= tileRange.max.y; j++) { for (var i = tileRange.min.x; i <= tileRange.max.x; i++) { var coords = new Point(i, j); coords.z = this._tileZoom; if (!this._isValidTile(coords)) { continue; } var tile = this._tiles[this._tileCoordsToKey(coords)]; if (tile) { tile.current = true; } else { queue.push(coords); } } } // sort tile queue to load tiles in order of their distance to center queue.sort(function (a, b) { return a.distanceTo(tileCenter) - b.distanceTo(tileCenter); }); if (queue.length !== 0) { // if it's the first batch of tiles to load if (!this._loading) { this._loading = true; // @event loading: Event // Fired when the grid layer starts loading tiles. this.fire('loading'); } // create DOM fragment to append tiles in one batch var fragment = document.createDocumentFragment(); for (i = 0; i < queue.length; i++) { this._addTile(queue[i], fragment); } this._level.el.appendChild(fragment); } }, _isValidTile: function (coords) { var crs = this._map.options.crs; if (!crs.infinite) { // don't load tile if it's out of bounds and not wrapped var bounds = this._globalTileRange; if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) || (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; } } if (!this.options.bounds) { return true; } // don't load tile if it doesn't intersect the bounds in options var tileBounds = this._tileCoordsToBounds(coords); return toLatLngBounds(this.options.bounds).overlaps(tileBounds); }, _keyToBounds: function (key) { return this._tileCoordsToBounds(this._keyToTileCoords(key)); }, _tileCoordsToNwSe: function (coords) { var map = this._map, tileSize = this.getTileSize(), nwPoint = coords.scaleBy(tileSize), sePoint = nwPoint.add(tileSize), nw = map.unproject(nwPoint, coords.z), se = map.unproject(sePoint, coords.z); return [nw, se]; }, // converts tile coordinates to its geographical bounds _tileCoordsToBounds: function (coords) { var bp = this._tileCoordsToNwSe(coords), bounds = new LatLngBounds(bp[0], bp[1]); if (!this.options.noWrap) { bounds = this._map.wrapLatLngBounds(bounds); } return bounds; }, // converts tile coordinates to key for the tile cache _tileCoordsToKey: function (coords) { return coords.x + ':' + coords.y + ':' + coords.z; }, // converts tile cache key to coordinates _keyToTileCoords: function (key) { var k = key.split(':'), coords = new Point(+k[0], +k[1]); coords.z = +k[2]; return coords; }, _removeTile: function (key) { var tile = this._tiles[key]; if (!tile) { return; } remove(tile.el); delete this._tiles[key]; // @event tileunload: TileEvent // Fired when a tile is removed (e.g. when a tile goes off the screen). this.fire('tileunload', { tile: tile.el, coords: this._keyToTileCoords(key) }); }, _initTile: function (tile) { addClass(tile, 'leaflet-tile'); var tileSize = this.getTileSize(); tile.style.width = tileSize.x + 'px'; tile.style.height = tileSize.y + 'px'; tile.onselectstart = falseFn; tile.onmousemove = falseFn; // update opacity on tiles in IE7-8 because of filter inheritance problems if (ielt9 && this.options.opacity < 1) { setOpacity(tile, this.options.opacity); } // without this hack, tiles disappear after zoom on Chrome for Android // https://github.com/Leaflet/Leaflet/issues/2078 if (android && !android23) { tile.style.WebkitBackfaceVisibility = 'hidden'; } }, _addTile: function (coords, container) { var tilePos = this._getTilePos(coords), key = this._tileCoordsToKey(coords); var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords)); this._initTile(tile); // if createTile is defined with a second argument ("done" callback), // we know that tile is async and will be ready later; otherwise if (this.createTile.length < 2) { // mark tile as ready, but delay one frame for opacity animation to happen requestAnimFrame(bind(this._tileReady, this, coords, null, tile)); } setPosition(tile, tilePos); // save tile in cache this._tiles[key] = { el: tile, coords: coords, current: true }; container.appendChild(tile); // @event tileloadstart: TileEvent // Fired when a tile is requested and starts loading. this.fire('tileloadstart', { tile: tile, coords: coords }); }, _tileReady: function (coords, err, tile) { if (err) { // @event tileerror: TileErrorEvent // Fired when there is an error loading a tile. this.fire('tileerror', { error: err, tile: tile, coords: coords }); } var key = this._tileCoordsToKey(coords); tile = this._tiles[key]; if (!tile) { return; } tile.loaded = +new Date(); if (this._map._fadeAnimated) { setOpacity(tile.el, 0); cancelAnimFrame(this._fadeFrame); this._fadeFrame = requestAnimFrame(this._updateOpacity, this); } else { tile.active = true; this._pruneTiles(); } if (!err) { addClass(tile.el, 'leaflet-tile-loaded'); // @event tileload: TileEvent // Fired when a tile loads. this.fire('tileload', { tile: tile.el, coords: coords }); } if (this._noTilesToLoad()) { this._loading = false; // @event load: Event // Fired when the grid layer loaded all visible tiles. this.fire('load'); if (ielt9 || !this._map._fadeAnimated) { requestAnimFrame(this._pruneTiles, this); } else { // Wait a bit more than 0.2 secs (the duration of the tile fade-in) // to trigger a pruning. setTimeout(bind(this._pruneTiles, this), 250); } } }, _getTilePos: function (coords) { return coords.scaleBy(this.getTileSize()).subtract(this._level.origin); }, _wrapCoords: function (coords) { var newCoords = new Point( this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x, this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y); newCoords.z = coords.z; return newCoords; }, _pxBoundsToTileRange: function (bounds) { var tileSize = this.getTileSize(); return new Bounds( bounds.min.unscaleBy(tileSize).floor(), bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1])); }, _noTilesToLoad: function () { for (var key in this._tiles) { if (!this._tiles[key].loaded) { return false; } } return true; } }); // @factory L.gridLayer(options?: GridLayer options) // Creates a new instance of GridLayer with the supplied options. function gridLayer(options) { return new GridLayer(options); } /* * @class TileLayer * @inherits GridLayer * @aka L.TileLayer * Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under `Layer`. Extends `GridLayer`. * * @example * * ```js * L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'}).addTo(map); * ``` * * @section URL template * @example * * A string of the following form: * * ``` * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png' * ``` * * `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "&commat;2x" to the URL to load retina tiles. * * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this: * * ``` * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'}); * ``` */ var TileLayer = GridLayer.extend({ // @section // @aka TileLayer options options: { // @option minZoom: Number = 0 // The minimum zoom level down to which this layer will be displayed (inclusive). minZoom: 0, // @option maxZoom: Number = 18 // The maximum zoom level up to which this layer will be displayed (inclusive). maxZoom: 18, // @option subdomains: String|String[] = 'abc' // Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings. subdomains: 'abc', // @option errorTileUrl: String = '' // URL to the tile image to show in place of the tile that failed to load. errorTileUrl: '', // @option zoomOffset: Number = 0 // The zoom number used in tile URLs will be offset with this value. zoomOffset: 0, // @option tms: Boolean = false // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services). tms: false, // @option zoomReverse: Boolean = false // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`) zoomReverse: false, // @option detectRetina: Boolean = false // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution. detectRetina: false, // @option crossOrigin: Boolean|String = false // Whether the crossOrigin attribute will be added to the tiles. // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. crossOrigin: false }, initialize: function (url, options) { this._url = url; options = setOptions(this, options); // detecting retina displays, adjusting tileSize and zoom levels if (options.detectRetina && retina && options.maxZoom > 0) { options.tileSize = Math.floor(options.tileSize / 2); if (!options.zoomReverse) { options.zoomOffset++; options.maxZoom--; } else { options.zoomOffset--; options.minZoom++; } options.minZoom = Math.max(0, options.minZoom); } if (typeof options.subdomains === 'string') { options.subdomains = options.subdomains.split(''); } // for https://github.com/Leaflet/Leaflet/issues/137 if (!android) { this.on('tileunload', this._onTileRemove); } }, // @method setUrl(url: String, noRedraw?: Boolean): this // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`). // If the URL does not change, the layer will not be redrawn unless // the noRedraw parameter is set to false. setUrl: function (url, noRedraw) { if (this._url === url && noRedraw === undefined) { noRedraw = true; } this._url = url; if (!noRedraw) { this.redraw(); } return this; }, // @method createTile(coords: Object, done?: Function): HTMLElement // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile) // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done` // callback is called when the tile has been loaded. createTile: function (coords, done) { var tile = document.createElement('img'); on(tile, 'load', bind(this._tileOnLoad, this, done, tile)); on(tile, 'error', bind(this._tileOnError, this, done, tile)); if (this.options.crossOrigin || this.options.crossOrigin === '') { tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin; } /* Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons http://www.w3.org/TR/WCAG20-TECHS/H67 */ tile.alt = ''; /* Set role="presentation" to force screen readers to ignore this https://www.w3.org/TR/wai-aria/roles#textalternativecomputation */ tile.setAttribute('role', 'presentation'); tile.src = this.getTileUrl(coords); return tile; }, // @section Extension methods // @uninheritable // Layers extending `TileLayer` might reimplement the following method. // @method getTileUrl(coords: Object): String // Called only internally, returns the URL for a tile given its coordinates. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes. getTileUrl: function (coords) { var data = { r: retina ? '@2x' : '', s: this._getSubdomain(coords), x: coords.x, y: coords.y, z: this._getZoomForUrl() }; if (this._map && !this._map.options.crs.infinite) { var invertedY = this._globalTileRange.max.y - coords.y; if (this.options.tms) { data['y'] = invertedY; } data['-y'] = invertedY; } return template(this._url, extend(data, this.options)); }, _tileOnLoad: function (done, tile) { // For https://github.com/Leaflet/Leaflet/issues/3332 if (ielt9) { setTimeout(bind(done, this, null, tile), 0); } else { done(null, tile); } }, _tileOnError: function (done, tile, e) { var errorUrl = this.options.errorTileUrl; if (errorUrl && tile.getAttribute('src') !== errorUrl) { tile.src = errorUrl; } done(e, tile); }, _onTileRemove: function (e) { e.tile.onload = null; }, _getZoomForUrl: function () { var zoom = this._tileZoom, maxZoom = this.options.maxZoom, zoomReverse = this.options.zoomReverse, zoomOffset = this.options.zoomOffset; if (zoomReverse) { zoom = maxZoom - zoom; } return zoom + zoomOffset; }, _getSubdomain: function (tilePoint) { var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length; return this.options.subdomains[index]; }, // stops loading all tiles in the background layer _abortLoading: function () { var i, tile; for (i in this._tiles) { if (this._tiles[i].coords.z !== this._tileZoom) { tile = this._tiles[i].el; tile.onload = falseFn; tile.onerror = falseFn; if (!tile.complete) { tile.src = emptyImageUrl; remove(tile); delete this._tiles[i]; } } } }, _removeTile: function (key) { var tile = this._tiles[key]; if (!tile) { return; } // Cancels any pending http requests associated with the tile // unless we're on Android's stock browser, // see https://github.com/Leaflet/Leaflet/issues/137 if (!androidStock) { tile.el.setAttribute('src', emptyImageUrl); } return GridLayer.prototype._removeTile.call(this, key); }, _tileReady: function (coords, err, tile) { if (!this._map || (tile && tile.getAttribute('src') === emptyImageUrl)) { return; } return GridLayer.prototype._tileReady.call(this, coords, err, tile); } }); // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options) // Instantiates a tile layer object given a `URL template` and optionally an options object. function tileLayer(url, options) { return new TileLayer(url, options); } /* * @class TileLayer.WMS * @inherits TileLayer * @aka L.TileLayer.WMS * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`. * * @example * * ```js * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", { * layers: 'nexrad-n0r-900913', * format: 'image/png', * transparent: true, * attribution: "Weather data © 2012 IEM Nexrad" * }); * ``` */ var TileLayerWMS = TileLayer.extend({ // @section // @aka TileLayer.WMS options // If any custom options not documented here are used, they will be sent to the // WMS server as extra parameters in each request URL. This can be useful for // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html). defaultWmsParams: { service: 'WMS', request: 'GetMap', // @option layers: String = '' // **(required)** Comma-separated list of WMS layers to show. layers: '', // @option styles: String = '' // Comma-separated list of WMS styles. styles: '', // @option format: String = 'image/jpeg' // WMS image format (use `'image/png'` for layers with transparency). format: 'image/jpeg', // @option transparent: Boolean = false // If `true`, the WMS service will return images with transparency. transparent: false, // @option version: String = '1.1.1' // Version of the WMS service to use version: '1.1.1' }, options: { // @option crs: CRS = null // Coordinate Reference System to use for the WMS requests, defaults to // map CRS. Don't change this if you're not sure what it means. crs: null, // @option uppercase: Boolean = false // If `true`, WMS request parameter keys will be uppercase. uppercase: false }, initialize: function (url, options) { this._url = url; var wmsParams = extend({}, this.defaultWmsParams); // all keys that are not TileLayer options go to WMS params for (var i in options) { if (!(i in this.options)) { wmsParams[i] = options[i]; } } options = setOptions(this, options); var realRetina = options.detectRetina && retina ? 2 : 1; var tileSize = this.getTileSize(); wmsParams.width = tileSize.x * realRetina; wmsParams.height = tileSize.y * realRetina; this.wmsParams = wmsParams; }, onAdd: function (map) { this._crs = this.options.crs || map.options.crs; this._wmsVersion = parseFloat(this.wmsParams.version); var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs'; this.wmsParams[projectionKey] = this._crs.code; TileLayer.prototype.onAdd.call(this, map); }, getTileUrl: function (coords) { var tileBounds = this._tileCoordsToNwSe(coords), crs = this._crs, bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])), min = bounds.min, max = bounds.max, bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ? [min.y, min.x, max.y, max.x] : [min.x, min.y, max.x, max.y]).join(','), url = TileLayer.prototype.getTileUrl.call(this, coords); return url + getParamString(this.wmsParams, url, this.options.uppercase) + (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox; }, // @method setParams(params: Object, noRedraw?: Boolean): this // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true). setParams: function (params, noRedraw) { extend(this.wmsParams, params); if (!noRedraw) { this.redraw(); } return this; } }); // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options) // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object. function tileLayerWMS(url, options) { return new TileLayerWMS(url, options); } TileLayer.WMS = TileLayerWMS; tileLayer.wms = tileLayerWMS; /* * @class Renderer * @inherits Layer * @aka L.Renderer * * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the * DOM container of the renderer, its bounds, and its zoom animation. * * A `Renderer` works as an implicit layer group for all `Path`s - the renderer * itself can be added or removed to the map. All paths use a renderer, which can * be implicit (the map will decide the type of renderer and use it automatically) * or explicit (using the [`renderer`](#path-renderer) option of the path). * * Do not use this class directly, use `SVG` and `Canvas` instead. * * @event update: Event * Fired when the renderer updates its bounds, center and zoom, for example when * its map has moved */ var Renderer = Layer.extend({ // @section // @aka Renderer options options: { // @option padding: Number = 0.1 // How much to extend the clip area around the map view (relative to its size) // e.g. 0.1 would be 10% of map view in each direction padding: 0.1, // @option tolerance: Number = 0 // How much to extend click tolerance round a path/object on the map tolerance : 0 }, initialize: function (options) { setOptions(this, options); stamp(this); this._layers = this._layers || {}; }, onAdd: function () { if (!this._container) { this._initContainer(); // defined by renderer implementations if (this._zoomAnimated) { addClass(this._container, 'leaflet-zoom-animated'); } } this.getPane().appendChild(this._container); this._update(); this.on('update', this._updatePaths, this); }, onRemove: function () { this.off('update', this._updatePaths, this); this._destroyContainer(); }, getEvents: function () { var events = { viewreset: this._reset, zoom: this._onZoom, moveend: this._update, zoomend: this._onZoomEnd }; if (this._zoomAnimated) { events.zoomanim = this._onAnimZoom; } return events; }, _onAnimZoom: function (ev) { this._updateTransform(ev.center, ev.zoom); }, _onZoom: function () { this._updateTransform(this._map.getCenter(), this._map.getZoom()); }, _updateTransform: function (center, zoom) { var scale = this._map.getZoomScale(zoom, this._zoom), position = getPosition(this._container), viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding), currentCenterPoint = this._map.project(this._center, zoom), destCenterPoint = this._map.project(center, zoom), centerOffset = destCenterPoint.subtract(currentCenterPoint), topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset); if (any3d) { setTransform(this._container, topLeftOffset, scale); } else { setPosition(this._container, topLeftOffset); } }, _reset: function () { this._update(); this._updateTransform(this._center, this._zoom); for (var id in this._layers) { this._layers[id]._reset(); } }, _onZoomEnd: function () { for (var id in this._layers) { this._layers[id]._project(); } }, _updatePaths: function () { for (var id in this._layers) { this._layers[id]._update(); } }, _update: function () { // Update pixel bounds of renderer container (for positioning/sizing/clipping later) // Subclasses are responsible of firing the 'update' event. var p = this.options.padding, size = this._map.getSize(), min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round(); this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round()); this._center = this._map.getCenter(); this._zoom = this._map.getZoom(); } }); /* * @class Canvas * @inherits Renderer * @aka L.Canvas * * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API). * Inherits `Renderer`. * * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not * available in all web browsers, notably IE8, and overlapping geometries might * not display properly in some edge cases. * * @example * * Use Canvas by default for all paths in the map: * * ```js * var map = L.map('map', { * renderer: L.canvas() * }); * ``` * * Use a Canvas renderer with extra padding for specific vector geometries: * * ```js * var map = L.map('map'); * var myRenderer = L.canvas({ padding: 0.5 }); * var line = L.polyline( coordinates, { renderer: myRenderer } ); * var circle = L.circle( center, { renderer: myRenderer } ); * ``` */ var Canvas = Renderer.extend({ getEvents: function () { var events = Renderer.prototype.getEvents.call(this); events.viewprereset = this._onViewPreReset; return events; }, _onViewPreReset: function () { // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once this._postponeUpdatePaths = true; }, onAdd: function () { Renderer.prototype.onAdd.call(this); // Redraw vectors since canvas is cleared upon removal, // in case of removing the renderer itself from the map. this._draw(); }, _initContainer: function () { var container = this._container = document.createElement('canvas'); on(container, 'mousemove', this._onMouseMove, this); on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this); on(container, 'mouseout', this._handleMouseOut, this); this._ctx = container.getContext('2d'); }, _destroyContainer: function () { cancelAnimFrame(this._redrawRequest); delete this._ctx; remove(this._container); off(this._container); delete this._container; }, _updatePaths: function () { if (this._postponeUpdatePaths) { return; } var layer; this._redrawBounds = null; for (var id in this._layers) { layer = this._layers[id]; layer._update(); } this._redraw(); }, _update: function () { if (this._map._animatingZoom && this._bounds) { return; } Renderer.prototype._update.call(this); var b = this._bounds, container = this._container, size = b.getSize(), m = retina ? 2 : 1; setPosition(container, b.min); // set canvas size (also clearing it); use double size on retina container.width = m * size.x; container.height = m * size.y; container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; if (retina) { this._ctx.scale(2, 2); } // translate so we use the same path coordinates after canvas element moves this._ctx.translate(-b.min.x, -b.min.y); // Tell paths to redraw themselves this.fire('update'); }, _reset: function () { Renderer.prototype._reset.call(this); if (this._postponeUpdatePaths) { this._postponeUpdatePaths = false; this._updatePaths(); } }, _initPath: function (layer) { this._updateDashArray(layer); this._layers[stamp(layer)] = layer; var order = layer._order = { layer: layer, prev: this._drawLast, next: null }; if (this._drawLast) { this._drawLast.next = order; } this._drawLast = order; this._drawFirst = this._drawFirst || this._drawLast; }, _addPath: function (layer) { this._requestRedraw(layer); }, _removePath: function (layer) { var order = layer._order; var next = order.next; var prev = order.prev; if (next) { next.prev = prev; } else { this._drawLast = prev; } if (prev) { prev.next = next; } else { this._drawFirst = next; } delete layer._order; delete this._layers[stamp(layer)]; this._requestRedraw(layer); }, _updatePath: function (layer) { // Redraw the union of the layer's old pixel // bounds and the new pixel bounds. this._extendRedrawBounds(layer); layer._project(); layer._update(); // The redraw will extend the redraw bounds // with the new pixel bounds. this._requestRedraw(layer); }, _updateStyle: function (layer) { this._updateDashArray(layer); this._requestRedraw(layer); }, _updateDashArray: function (layer) { if (typeof layer.options.dashArray === 'string') { var parts = layer.options.dashArray.split(/[, ]+/), dashArray = [], dashValue, i; for (i = 0; i < parts.length; i++) { dashValue = Number(parts[i]); // Ignore dash array containing invalid lengths if (isNaN(dashValue)) { return; } dashArray.push(dashValue); } layer.options._dashArray = dashArray; } else { layer.options._dashArray = layer.options.dashArray; } }, _requestRedraw: function (layer) { if (!this._map) { return; } this._extendRedrawBounds(layer); this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this); }, _extendRedrawBounds: function (layer) { if (layer._pxBounds) { var padding = (layer.options.weight || 0) + 1; this._redrawBounds = this._redrawBounds || new Bounds(); this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding])); this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding])); } }, _redraw: function () { this._redrawRequest = null; if (this._redrawBounds) { this._redrawBounds.min._floor(); this._redrawBounds.max._ceil(); } this._clear(); // clear layers in redraw bounds this._draw(); // draw layers this._redrawBounds = null; }, _clear: function () { var bounds = this._redrawBounds; if (bounds) { var size = bounds.getSize(); this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y); } else { this._ctx.clearRect(0, 0, this._container.width, this._container.height); } }, _draw: function () { var layer, bounds = this._redrawBounds; this._ctx.save(); if (bounds) { var size = bounds.getSize(); this._ctx.beginPath(); this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y); this._ctx.clip(); } this._drawing = true; for (var order = this._drawFirst; order; order = order.next) { layer = order.layer; if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) { layer._updatePath(); } } this._drawing = false; this._ctx.restore(); // Restore state before clipping. }, _updatePoly: function (layer, closed) { if (!this._drawing) { return; } var i, j, len2, p, parts = layer._parts, len = parts.length, ctx = this._ctx; if (!len) { return; } ctx.beginPath(); for (i = 0; i < len; i++) { for (j = 0, len2 = parts[i].length; j < len2; j++) { p = parts[i][j]; ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y); } if (closed) { ctx.closePath(); } } this._fillStroke(ctx, layer); // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature }, _updateCircle: function (layer) { if (!this._drawing || layer._empty()) { return; } var p = layer._point, ctx = this._ctx, r = Math.max(Math.round(layer._radius), 1), s = (Math.max(Math.round(layer._radiusY), 1) || r) / r; if (s !== 1) { ctx.save(); ctx.scale(1, s); } ctx.beginPath(); ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false); if (s !== 1) { ctx.restore(); } this._fillStroke(ctx, layer); }, _fillStroke: function (ctx, layer) { var options = layer.options; if (options.fill) { ctx.globalAlpha = options.fillOpacity; ctx.fillStyle = options.fillColor || options.color; ctx.fill(options.fillRule || 'evenodd'); } if (options.stroke && options.weight !== 0) { if (ctx.setLineDash) { ctx.setLineDash(layer.options && layer.options._dashArray || []); } ctx.globalAlpha = options.opacity; ctx.lineWidth = options.weight; ctx.strokeStyle = options.color; ctx.lineCap = options.lineCap; ctx.lineJoin = options.lineJoin; ctx.stroke(); } }, // Canvas obviously doesn't have mouse events for individual drawn objects, // so we emulate that by calculating what's under the mouse on mousemove/click manually _onClick: function (e) { var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer; for (var order = this._drawFirst; order; order = order.next) { layer = order.layer; if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) { clickedLayer = layer; } } if (clickedLayer) { fakeStop(e); this._fireEvent([clickedLayer], e); } },<|fim▁hole|> var point = this._map.mouseEventToLayerPoint(e); this._handleMouseHover(e, point); }, _handleMouseOut: function (e) { var layer = this._hoveredLayer; if (layer) { // if we're leaving the layer, fire mouseout removeClass(this._container, 'leaflet-interactive'); this._fireEvent([layer], e, 'mouseout'); this._hoveredLayer = null; this._mouseHoverThrottled = false; } }, _handleMouseHover: function (e, point) { if (this._mouseHoverThrottled) { return; } var layer, candidateHoveredLayer; for (var order = this._drawFirst; order; order = order.next) { layer = order.layer; if (layer.options.interactive && layer._containsPoint(point)) { candidateHoveredLayer = layer; } } if (candidateHoveredLayer !== this._hoveredLayer) { this._handleMouseOut(e); if (candidateHoveredLayer) { addClass(this._container, 'leaflet-interactive'); // change cursor this._fireEvent([candidateHoveredLayer], e, 'mouseover'); this._hoveredLayer = candidateHoveredLayer; } } if (this._hoveredLayer) { this._fireEvent([this._hoveredLayer], e); } this._mouseHoverThrottled = true; setTimeout(L.bind(function () { this._mouseHoverThrottled = false; }, this), 32); }, _fireEvent: function (layers, e, type) { this._map._fireDOMEvent(e, type || e.type, layers); }, _bringToFront: function (layer) { var order = layer._order; if (!order) { return; } var next = order.next; var prev = order.prev; if (next) { next.prev = prev; } else { // Already last return; } if (prev) { prev.next = next; } else if (next) { // Update first entry unless this is the // single entry this._drawFirst = next; } order.prev = this._drawLast; this._drawLast.next = order; order.next = null; this._drawLast = order; this._requestRedraw(layer); }, _bringToBack: function (layer) { var order = layer._order; if (!order) { return; } var next = order.next; var prev = order.prev; if (prev) { prev.next = next; } else { // Already first return; } if (next) { next.prev = prev; } else if (prev) { // Update last entry unless this is the // single entry this._drawLast = prev; } order.prev = null; order.next = this._drawFirst; this._drawFirst.prev = order; this._drawFirst = order; this._requestRedraw(layer); } }); // @factory L.canvas(options?: Renderer options) // Creates a Canvas renderer with the given options. function canvas$1(options) { return canvas ? new Canvas(options) : null; } /* * Thanks to Dmitry Baranovsky and his Raphael library for inspiration! */ var vmlCreate = (function () { try { document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml'); return function (name) { return document.createElement('<lvml:' + name + ' class="lvml">'); }; } catch (e) { return function (name) { return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">'); }; } })(); /* * @class SVG * * * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility * with old versions of Internet Explorer. */ // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences var vmlMixin = { _initContainer: function () { this._container = create$1('div', 'leaflet-vml-container'); }, _update: function () { if (this._map._animatingZoom) { return; } Renderer.prototype._update.call(this); this.fire('update'); }, _initPath: function (layer) { var container = layer._container = vmlCreate('shape'); addClass(container, 'leaflet-vml-shape ' + (this.options.className || '')); container.coordsize = '1 1'; layer._path = vmlCreate('path'); container.appendChild(layer._path); this._updateStyle(layer); this._layers[stamp(layer)] = layer; }, _addPath: function (layer) { var container = layer._container; this._container.appendChild(container); if (layer.options.interactive) { layer.addInteractiveTarget(container); } }, _removePath: function (layer) { var container = layer._container; remove(container); layer.removeInteractiveTarget(container); delete this._layers[stamp(layer)]; }, _updateStyle: function (layer) { var stroke = layer._stroke, fill = layer._fill, options = layer.options, container = layer._container; container.stroked = !!options.stroke; container.filled = !!options.fill; if (options.stroke) { if (!stroke) { stroke = layer._stroke = vmlCreate('stroke'); } container.appendChild(stroke); stroke.weight = options.weight + 'px'; stroke.color = options.color; stroke.opacity = options.opacity; if (options.dashArray) { stroke.dashStyle = isArray(options.dashArray) ? options.dashArray.join(' ') : options.dashArray.replace(/( *, *)/g, ' '); } else { stroke.dashStyle = ''; } stroke.endcap = options.lineCap.replace('butt', 'flat'); stroke.joinstyle = options.lineJoin; } else if (stroke) { container.removeChild(stroke); layer._stroke = null; } if (options.fill) { if (!fill) { fill = layer._fill = vmlCreate('fill'); } container.appendChild(fill); fill.color = options.fillColor || options.color; fill.opacity = options.fillOpacity; } else if (fill) { container.removeChild(fill); layer._fill = null; } }, _updateCircle: function (layer) { var p = layer._point.round(), r = Math.round(layer._radius), r2 = Math.round(layer._radiusY || r); this._setPath(layer, layer._empty() ? 'M0 0' : 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360)); }, _setPath: function (layer, path) { layer._path.v = path; }, _bringToFront: function (layer) { toFront(layer._container); }, _bringToBack: function (layer) { toBack(layer._container); } }; var create$2 = vml ? vmlCreate : svgCreate; /* * @class SVG * @inherits Renderer * @aka L.SVG * * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG). * Inherits `Renderer`. * * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not * available in all web browsers, notably Android 2.x and 3.x. * * Although SVG is not available on IE7 and IE8, these browsers support * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language) * (a now deprecated technology), and the SVG renderer will fall back to VML in * this case. * * @example * * Use SVG by default for all paths in the map: * * ```js * var map = L.map('map', { * renderer: L.svg() * }); * ``` * * Use a SVG renderer with extra padding for specific vector geometries: * * ```js * var map = L.map('map'); * var myRenderer = L.svg({ padding: 0.5 }); * var line = L.polyline( coordinates, { renderer: myRenderer } ); * var circle = L.circle( center, { renderer: myRenderer } ); * ``` */ var SVG = Renderer.extend({ getEvents: function () { var events = Renderer.prototype.getEvents.call(this); events.zoomstart = this._onZoomStart; return events; }, _initContainer: function () { this._container = create$2('svg'); // makes it possible to click through svg root; we'll reset it back in individual paths this._container.setAttribute('pointer-events', 'none'); this._rootGroup = create$2('g'); this._container.appendChild(this._rootGroup); }, _destroyContainer: function () { remove(this._container); off(this._container); delete this._container; delete this._rootGroup; delete this._svgSize; }, _onZoomStart: function () { // Drag-then-pinch interactions might mess up the center and zoom. // In this case, the easiest way to prevent this is re-do the renderer // bounds and padding when the zooming starts. this._update(); }, _update: function () { if (this._map._animatingZoom && this._bounds) { return; } Renderer.prototype._update.call(this); var b = this._bounds, size = b.getSize(), container = this._container; // set size of svg-container if changed if (!this._svgSize || !this._svgSize.equals(size)) { this._svgSize = size; container.setAttribute('width', size.x); container.setAttribute('height', size.y); } // movement: update container viewBox so that we don't have to change coordinates of individual layers setPosition(container, b.min); container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' ')); this.fire('update'); }, // methods below are called by vector layers implementations _initPath: function (layer) { var path = layer._path = create$2('path'); // @namespace Path // @option className: String = null // Custom class name set on an element. Only for SVG renderer. if (layer.options.className) { addClass(path, layer.options.className); } if (layer.options.interactive) { addClass(path, 'leaflet-interactive'); } this._updateStyle(layer); this._layers[stamp(layer)] = layer; }, _addPath: function (layer) { if (!this._rootGroup) { this._initContainer(); } this._rootGroup.appendChild(layer._path); layer.addInteractiveTarget(layer._path); }, _removePath: function (layer) { remove(layer._path); layer.removeInteractiveTarget(layer._path); delete this._layers[stamp(layer)]; }, _updatePath: function (layer) { layer._project(); layer._update(); }, _updateStyle: function (layer) { var path = layer._path, options = layer.options; if (!path) { return; } if (options.stroke) { path.setAttribute('stroke', options.color); path.setAttribute('stroke-opacity', options.opacity); path.setAttribute('stroke-width', options.weight); path.setAttribute('stroke-linecap', options.lineCap); path.setAttribute('stroke-linejoin', options.lineJoin); if (options.dashArray) { path.setAttribute('stroke-dasharray', options.dashArray); } else { path.removeAttribute('stroke-dasharray'); } if (options.dashOffset) { path.setAttribute('stroke-dashoffset', options.dashOffset); } else { path.removeAttribute('stroke-dashoffset'); } } else { path.setAttribute('stroke', 'none'); } if (options.fill) { path.setAttribute('fill', options.fillColor || options.color); path.setAttribute('fill-opacity', options.fillOpacity); path.setAttribute('fill-rule', options.fillRule || 'evenodd'); } else { path.setAttribute('fill', 'none'); } }, _updatePoly: function (layer, closed) { this._setPath(layer, pointsToPath(layer._parts, closed)); }, _updateCircle: function (layer) { var p = layer._point, r = Math.max(Math.round(layer._radius), 1), r2 = Math.max(Math.round(layer._radiusY), 1) || r, arc = 'a' + r + ',' + r2 + ' 0 1,0 '; // drawing a circle with two half-arcs var d = layer._empty() ? 'M0 0' : 'M' + (p.x - r) + ',' + p.y + arc + (r * 2) + ',0 ' + arc + (-r * 2) + ',0 '; this._setPath(layer, d); }, _setPath: function (layer, path) { layer._path.setAttribute('d', path); }, // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements _bringToFront: function (layer) { toFront(layer._path); }, _bringToBack: function (layer) { toBack(layer._path); } }); if (vml) { SVG.include(vmlMixin); } // @namespace SVG // @factory L.svg(options?: Renderer options) // Creates a SVG renderer with the given options. function svg$1(options) { return svg || vml ? new SVG(options) : null; } Map.include({ // @namespace Map; @method getRenderer(layer: Path): Renderer // Returns the instance of `Renderer` that should be used to render the given // `Path`. It will ensure that the `renderer` options of the map and paths // are respected, and that the renderers do exist on the map. getRenderer: function (layer) { // @namespace Path; @option renderer: Renderer // Use this specific instance of `Renderer` for this path. Takes // precedence over the map's [default renderer](#map-renderer). var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer; if (!renderer) { renderer = this._renderer = this._createRenderer(); } if (!this.hasLayer(renderer)) { this.addLayer(renderer); } return renderer; }, _getPaneRenderer: function (name) { if (name === 'overlayPane' || name === undefined) { return false; } var renderer = this._paneRenderers[name]; if (renderer === undefined) { renderer = this._createRenderer({pane: name}); this._paneRenderers[name] = renderer; } return renderer; }, _createRenderer: function (options) { // @namespace Map; @option preferCanvas: Boolean = false // Whether `Path`s should be rendered on a `Canvas` renderer. // By default, all `Path`s are rendered in a `SVG` renderer. return (this.options.preferCanvas && canvas$1(options)) || svg$1(options); } }); /* * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object. */ /* * @class Rectangle * @aka L.Rectangle * @inherits Polygon * * A class for drawing rectangle overlays on a map. Extends `Polygon`. * * @example * * ```js * // define rectangle geographical bounds * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]]; * * // create an orange rectangle * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map); * * // zoom the map to the rectangle bounds * map.fitBounds(bounds); * ``` * */ var Rectangle = Polygon.extend({ initialize: function (latLngBounds, options) { Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options); }, // @method setBounds(latLngBounds: LatLngBounds): this // Redraws the rectangle with the passed bounds. setBounds: function (latLngBounds) { return this.setLatLngs(this._boundsToLatLngs(latLngBounds)); }, _boundsToLatLngs: function (latLngBounds) { latLngBounds = toLatLngBounds(latLngBounds); return [ latLngBounds.getSouthWest(), latLngBounds.getNorthWest(), latLngBounds.getNorthEast(), latLngBounds.getSouthEast() ]; } }); // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options) function rectangle(latLngBounds, options) { return new Rectangle(latLngBounds, options); } SVG.create = create$2; SVG.pointsToPath = pointsToPath; GeoJSON.geometryToLayer = geometryToLayer; GeoJSON.coordsToLatLng = coordsToLatLng; GeoJSON.coordsToLatLngs = coordsToLatLngs; GeoJSON.latLngToCoords = latLngToCoords; GeoJSON.latLngsToCoords = latLngsToCoords; GeoJSON.getFeature = getFeature; GeoJSON.asFeature = asFeature; /* * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map * (zoom to a selected bounding box), enabled by default. */ // @namespace Map // @section Interaction Options Map.mergeOptions({ // @option boxZoom: Boolean = true // Whether the map can be zoomed to a rectangular area specified by // dragging the mouse while pressing the shift key. boxZoom: true }); var BoxZoom = Handler.extend({ initialize: function (map) { this._map = map; this._container = map._container; this._pane = map._panes.overlayPane; this._resetStateTimeout = 0; map.on('unload', this._destroy, this); }, addHooks: function () { on(this._container, 'mousedown', this._onMouseDown, this); }, removeHooks: function () { off(this._container, 'mousedown', this._onMouseDown, this); }, moved: function () { return this._moved; }, _destroy: function () { remove(this._pane); delete this._pane; }, _resetState: function () { this._resetStateTimeout = 0; this._moved = false; }, _clearDeferredResetState: function () { if (this._resetStateTimeout !== 0) { clearTimeout(this._resetStateTimeout); this._resetStateTimeout = 0; } }, _onMouseDown: function (e) { if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; } // Clear the deferred resetState if it hasn't executed yet, otherwise it // will interrupt the interaction and orphan a box element in the container. this._clearDeferredResetState(); this._resetState(); disableTextSelection(); disableImageDrag(); this._startPoint = this._map.mouseEventToContainerPoint(e); on(document, { contextmenu: stop, mousemove: this._onMouseMove, mouseup: this._onMouseUp, keydown: this._onKeyDown }, this); }, _onMouseMove: function (e) { if (!this._moved) { this._moved = true; this._box = create$1('div', 'leaflet-zoom-box', this._container); addClass(this._container, 'leaflet-crosshair'); this._map.fire('boxzoomstart'); } this._point = this._map.mouseEventToContainerPoint(e); var bounds = new Bounds(this._point, this._startPoint), size = bounds.getSize(); setPosition(this._box, bounds.min); this._box.style.width = size.x + 'px'; this._box.style.height = size.y + 'px'; }, _finish: function () { if (this._moved) { remove(this._box); removeClass(this._container, 'leaflet-crosshair'); } enableTextSelection(); enableImageDrag(); off(document, { contextmenu: stop, mousemove: this._onMouseMove, mouseup: this._onMouseUp, keydown: this._onKeyDown }, this); }, _onMouseUp: function (e) { if ((e.which !== 1) && (e.button !== 1)) { return; } this._finish(); if (!this._moved) { return; } // Postpone to next JS tick so internal click event handling // still see it as "moved". this._clearDeferredResetState(); this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0); var bounds = new LatLngBounds( this._map.containerPointToLatLng(this._startPoint), this._map.containerPointToLatLng(this._point)); this._map .fitBounds(bounds) .fire('boxzoomend', {boxZoomBounds: bounds}); }, _onKeyDown: function (e) { if (e.keyCode === 27) { this._finish(); } } }); // @section Handlers // @property boxZoom: Handler // Box (shift-drag with mouse) zoom handler. Map.addInitHook('addHandler', 'boxZoom', BoxZoom); /* * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default. */ // @namespace Map // @section Interaction Options Map.mergeOptions({ // @option doubleClickZoom: Boolean|String = true // Whether the map can be zoomed in by double clicking on it and // zoomed out by double clicking while holding shift. If passed // `'center'`, double-click zoom will zoom to the center of the // view regardless of where the mouse was. doubleClickZoom: true }); var DoubleClickZoom = Handler.extend({ addHooks: function () { this._map.on('dblclick', this._onDoubleClick, this); }, removeHooks: function () { this._map.off('dblclick', this._onDoubleClick, this); }, _onDoubleClick: function (e) { var map = this._map, oldZoom = map.getZoom(), delta = map.options.zoomDelta, zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta; if (map.options.doubleClickZoom === 'center') { map.setZoom(zoom); } else { map.setZoomAround(e.containerPoint, zoom); } } }); // @section Handlers // // Map properties include interaction handlers that allow you to control // interaction behavior in runtime, enabling or disabling certain features such // as dragging or touch zoom (see `Handler` methods). For example: // // ```js // map.doubleClickZoom.disable(); // ``` // // @property doubleClickZoom: Handler // Double click zoom handler. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom); /* * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default. */ // @namespace Map // @section Interaction Options Map.mergeOptions({ // @option dragging: Boolean = true // Whether the map be draggable with mouse/touch or not. dragging: true, // @section Panning Inertia Options // @option inertia: Boolean = * // If enabled, panning of the map will have an inertia effect where // the map builds momentum while dragging and continues moving in // the same direction for some time. Feels especially nice on touch // devices. Enabled by default unless running on old Android devices. inertia: !android23, // @option inertiaDeceleration: Number = 3000 // The rate with which the inertial movement slows down, in pixels/second². inertiaDeceleration: 3400, // px/s^2 // @option inertiaMaxSpeed: Number = Infinity // Max speed of the inertial movement, in pixels/second. inertiaMaxSpeed: Infinity, // px/s // @option easeLinearity: Number = 0.2 easeLinearity: 0.2, // TODO refactor, move to CRS // @option worldCopyJump: Boolean = false // With this option enabled, the map tracks when you pan to another "copy" // of the world and seamlessly jumps to the original one so that all overlays // like markers and vector layers are still visible. worldCopyJump: false, // @option maxBoundsViscosity: Number = 0.0 // If `maxBounds` is set, this option will control how solid the bounds // are when dragging the map around. The default value of `0.0` allows the // user to drag outside the bounds at normal speed, higher values will // slow down map dragging outside bounds, and `1.0` makes the bounds fully // solid, preventing the user from dragging outside the bounds. maxBoundsViscosity: 0.0 }); var Drag = Handler.extend({ addHooks: function () { if (!this._draggable) { var map = this._map; this._draggable = new Draggable(map._mapPane, map._container); this._draggable.on({ dragstart: this._onDragStart, drag: this._onDrag, dragend: this._onDragEnd }, this); this._draggable.on('predrag', this._onPreDragLimit, this); if (map.options.worldCopyJump) { this._draggable.on('predrag', this._onPreDragWrap, this); map.on('zoomend', this._onZoomEnd, this); map.whenReady(this._onZoomEnd, this); } } addClass(this._map._container, 'leaflet-grab leaflet-touch-drag'); this._draggable.enable(); this._positions = []; this._times = []; }, removeHooks: function () { removeClass(this._map._container, 'leaflet-grab'); removeClass(this._map._container, 'leaflet-touch-drag'); this._draggable.disable(); }, moved: function () { return this._draggable && this._draggable._moved; }, moving: function () { return this._draggable && this._draggable._moving; }, _onDragStart: function () { var map = this._map; map._stop(); if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) { var bounds = toLatLngBounds(this._map.options.maxBounds); this._offsetLimit = toBounds( this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1), this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1) .add(this._map.getSize())); this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity)); } else { this._offsetLimit = null; } map .fire('movestart') .fire('dragstart'); if (map.options.inertia) { this._positions = []; this._times = []; } }, _onDrag: function (e) { if (this._map.options.inertia) { var time = this._lastTime = +new Date(), pos = this._lastPos = this._draggable._absPos || this._draggable._newPos; this._positions.push(pos); this._times.push(time); this._prunePositions(time); } this._map .fire('move', e) .fire('drag', e); }, _prunePositions: function (time) { while (this._positions.length > 1 && time - this._times[0] > 50) { this._positions.shift(); this._times.shift(); } }, _onZoomEnd: function () { var pxCenter = this._map.getSize().divideBy(2), pxWorldCenter = this._map.latLngToLayerPoint([0, 0]); this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x; this._worldWidth = this._map.getPixelWorldBounds().getSize().x; }, _viscousLimit: function (value, threshold) { return value - (value - threshold) * this._viscosity; }, _onPreDragLimit: function () { if (!this._viscosity || !this._offsetLimit) { return; } var offset = this._draggable._newPos.subtract(this._draggable._startPos); var limit = this._offsetLimit; if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); } if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); } if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); } if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); } this._draggable._newPos = this._draggable._startPos.add(offset); }, _onPreDragWrap: function () { // TODO refactor to be able to adjust map pane position after zoom var worldWidth = this._worldWidth, halfWidth = Math.round(worldWidth / 2), dx = this._initialWorldOffset, x = this._draggable._newPos.x, newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx, newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx, newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2; this._draggable._absPos = this._draggable._newPos.clone(); this._draggable._newPos.x = newX; }, _onDragEnd: function (e) { var map = this._map, options = map.options, noInertia = !options.inertia || this._times.length < 2; map.fire('dragend', e); if (noInertia) { map.fire('moveend'); } else { this._prunePositions(+new Date()); var direction = this._lastPos.subtract(this._positions[0]), duration = (this._lastTime - this._times[0]) / 1000, ease = options.easeLinearity, speedVector = direction.multiplyBy(ease / duration), speed = speedVector.distanceTo([0, 0]), limitedSpeed = Math.min(options.inertiaMaxSpeed, speed), limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed), decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease), offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round(); if (!offset.x && !offset.y) { map.fire('moveend'); } else { offset = map._limitOffset(offset, map.options.maxBounds); requestAnimFrame(function () { map.panBy(offset, { duration: decelerationDuration, easeLinearity: ease, noMoveStart: true, animate: true }); }); } } } }); // @section Handlers // @property dragging: Handler // Map dragging handler (by both mouse and touch). Map.addInitHook('addHandler', 'dragging', Drag); /* * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default. */ // @namespace Map // @section Keyboard Navigation Options Map.mergeOptions({ // @option keyboard: Boolean = true // Makes the map focusable and allows users to navigate the map with keyboard // arrows and `+`/`-` keys. keyboard: true, // @option keyboardPanDelta: Number = 80 // Amount of pixels to pan when pressing an arrow key. keyboardPanDelta: 80 }); var Keyboard = Handler.extend({ keyCodes: { left: [37], right: [39], down: [40], up: [38], zoomIn: [187, 107, 61, 171], zoomOut: [189, 109, 54, 173] }, initialize: function (map) { this._map = map; this._setPanDelta(map.options.keyboardPanDelta); this._setZoomDelta(map.options.zoomDelta); }, addHooks: function () { var container = this._map._container; // make the container focusable by tabbing if (container.tabIndex <= 0) { container.tabIndex = '0'; } on(container, { focus: this._onFocus, blur: this._onBlur, mousedown: this._onMouseDown }, this); this._map.on({ focus: this._addHooks, blur: this._removeHooks }, this); }, removeHooks: function () { this._removeHooks(); off(this._map._container, { focus: this._onFocus, blur: this._onBlur, mousedown: this._onMouseDown }, this); this._map.off({ focus: this._addHooks, blur: this._removeHooks }, this); }, _onMouseDown: function () { if (this._focused) { return; } var body = document.body, docEl = document.documentElement, top = body.scrollTop || docEl.scrollTop, left = body.scrollLeft || docEl.scrollLeft; this._map._container.focus(); window.scrollTo(left, top); }, _onFocus: function () { this._focused = true; this._map.fire('focus'); }, _onBlur: function () { this._focused = false; this._map.fire('blur'); }, _setPanDelta: function (panDelta) { var keys = this._panKeys = {}, codes = this.keyCodes, i, len; for (i = 0, len = codes.left.length; i < len; i++) { keys[codes.left[i]] = [-1 * panDelta, 0]; } for (i = 0, len = codes.right.length; i < len; i++) { keys[codes.right[i]] = [panDelta, 0]; } for (i = 0, len = codes.down.length; i < len; i++) { keys[codes.down[i]] = [0, panDelta]; } for (i = 0, len = codes.up.length; i < len; i++) { keys[codes.up[i]] = [0, -1 * panDelta]; } }, _setZoomDelta: function (zoomDelta) { var keys = this._zoomKeys = {}, codes = this.keyCodes, i, len; for (i = 0, len = codes.zoomIn.length; i < len; i++) { keys[codes.zoomIn[i]] = zoomDelta; } for (i = 0, len = codes.zoomOut.length; i < len; i++) { keys[codes.zoomOut[i]] = -zoomDelta; } }, _addHooks: function () { on(document, 'keydown', this._onKeyDown, this); }, _removeHooks: function () { off(document, 'keydown', this._onKeyDown, this); }, _onKeyDown: function (e) { if (e.altKey || e.ctrlKey || e.metaKey) { return; } var key = e.keyCode, map = this._map, offset; if (key in this._panKeys) { if (!map._panAnim || !map._panAnim._inProgress) { offset = this._panKeys[key]; if (e.shiftKey) { offset = toPoint(offset).multiplyBy(3); } map.panBy(offset); if (map.options.maxBounds) { map.panInsideBounds(map.options.maxBounds); } } } else if (key in this._zoomKeys) { map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]); } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) { map.closePopup(); } else { return; } stop(e); } }); // @section Handlers // @section Handlers // @property keyboard: Handler // Keyboard navigation handler. Map.addInitHook('addHandler', 'keyboard', Keyboard); /* * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map. */ // @namespace Map // @section Interaction Options Map.mergeOptions({ // @section Mousewheel options // @option scrollWheelZoom: Boolean|String = true // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`, // it will zoom to the center of the view regardless of where the mouse was. scrollWheelZoom: true, // @option wheelDebounceTime: Number = 40 // Limits the rate at which a wheel can fire (in milliseconds). By default // user can't zoom via wheel more often than once per 40 ms. wheelDebounceTime: 40, // @option wheelPxPerZoomLevel: Number = 60 // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta)) // mean a change of one full zoom level. Smaller values will make wheel-zooming // faster (and vice versa). wheelPxPerZoomLevel: 60 }); var ScrollWheelZoom = Handler.extend({ addHooks: function () { on(this._map._container, 'mousewheel', this._onWheelScroll, this); this._delta = 0; }, removeHooks: function () { off(this._map._container, 'mousewheel', this._onWheelScroll, this); }, _onWheelScroll: function (e) { var delta = getWheelDelta(e); var debounce = this._map.options.wheelDebounceTime; this._delta += delta; this._lastMousePos = this._map.mouseEventToContainerPoint(e); if (!this._startTime) { this._startTime = +new Date(); } var left = Math.max(debounce - (+new Date() - this._startTime), 0); clearTimeout(this._timer); this._timer = setTimeout(bind(this._performZoom, this), left); stop(e); }, _performZoom: function () { var map = this._map, zoom = map.getZoom(), snap = this._map.options.zoomSnap || 0; map._stop(); // stop panning and fly animations if any // map the delta with a sigmoid function to -4..4 range leaning on -1..1 var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4), d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2, d4 = snap ? Math.ceil(d3 / snap) * snap : d3, delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom; this._delta = 0; this._startTime = null; if (!delta) { return; } if (map.options.scrollWheelZoom === 'center') { map.setZoom(zoom + delta); } else { map.setZoomAround(this._lastMousePos, zoom + delta); } } }); // @section Handlers // @property scrollWheelZoom: Handler // Scroll wheel zoom handler. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom); /* * L.Map.Tap is used to enable mobile hacks like quick taps and long hold. */ // @namespace Map // @section Interaction Options Map.mergeOptions({ // @section Touch interaction options // @option tap: Boolean = true // Enables mobile hacks for supporting instant taps (fixing 200ms click // delay on iOS/Android) and touch holds (fired as `contextmenu` events). tap: true, // @option tapTolerance: Number = 15 // The max number of pixels a user can shift his finger during touch // for it to be considered a valid tap. tapTolerance: 15 }); var Tap = Handler.extend({ addHooks: function () { on(this._map._container, 'touchstart', this._onDown, this); }, removeHooks: function () { off(this._map._container, 'touchstart', this._onDown, this); }, _onDown: function (e) { if (!e.touches) { return; } preventDefault(e); this._fireClick = true; // don't simulate click or track longpress if more than 1 touch if (e.touches.length > 1) { this._fireClick = false; clearTimeout(this._holdTimeout); return; } var first = e.touches[0], el = first.target; this._startPos = this._newPos = new Point(first.clientX, first.clientY); // if touching a link, highlight it if (el.tagName && el.tagName.toLowerCase() === 'a') { addClass(el, 'leaflet-active'); } // simulate long hold but setting a timeout this._holdTimeout = setTimeout(bind(function () { if (this._isTapValid()) { this._fireClick = false; this._onUp(); this._simulateEvent('contextmenu', first); } }, this), 1000); this._simulateEvent('mousedown', first); on(document, { touchmove: this._onMove, touchend: this._onUp }, this); }, _onUp: function (e) { clearTimeout(this._holdTimeout); off(document, { touchmove: this._onMove, touchend: this._onUp }, this); if (this._fireClick && e && e.changedTouches) { var first = e.changedTouches[0], el = first.target; if (el && el.tagName && el.tagName.toLowerCase() === 'a') { removeClass(el, 'leaflet-active'); } this._simulateEvent('mouseup', first); // simulate click if the touch didn't move too much if (this._isTapValid()) { this._simulateEvent('click', first); } } }, _isTapValid: function () { return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance; }, _onMove: function (e) { var first = e.touches[0]; this._newPos = new Point(first.clientX, first.clientY); this._simulateEvent('mousemove', first); }, _simulateEvent: function (type, e) { var simulatedEvent = document.createEvent('MouseEvents'); simulatedEvent._simulated = true; e.target._simulatedClick = true; simulatedEvent.initMouseEvent( type, true, true, window, 1, e.screenX, e.screenY, e.clientX, e.clientY, false, false, false, false, 0, null); e.target.dispatchEvent(simulatedEvent); } }); // @section Handlers // @property tap: Handler // Mobile touch hacks (quick tap and touch hold) handler. if (touch && !pointer) { Map.addInitHook('addHandler', 'tap', Tap); } /* * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers. */ // @namespace Map // @section Interaction Options Map.mergeOptions({ // @section Touch interaction options // @option touchZoom: Boolean|String = * // Whether the map can be zoomed by touch-dragging with two fingers. If // passed `'center'`, it will zoom to the center of the view regardless of // where the touch events (fingers) were. Enabled for touch-capable web // browsers except for old Androids. touchZoom: touch && !android23, // @option bounceAtZoomLimits: Boolean = true // Set it to false if you don't want the map to zoom beyond min/max zoom // and then bounce back when pinch-zooming. bounceAtZoomLimits: true }); var TouchZoom = Handler.extend({ addHooks: function () { addClass(this._map._container, 'leaflet-touch-zoom'); on(this._map._container, 'touchstart', this._onTouchStart, this); }, removeHooks: function () { removeClass(this._map._container, 'leaflet-touch-zoom'); off(this._map._container, 'touchstart', this._onTouchStart, this); }, _onTouchStart: function (e) { var map = this._map; if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; } var p1 = map.mouseEventToContainerPoint(e.touches[0]), p2 = map.mouseEventToContainerPoint(e.touches[1]); this._centerPoint = map.getSize()._divideBy(2); this._startLatLng = map.containerPointToLatLng(this._centerPoint); if (map.options.touchZoom !== 'center') { this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2)); } this._startDist = p1.distanceTo(p2); this._startZoom = map.getZoom(); this._moved = false; this._zooming = true; map._stop(); on(document, 'touchmove', this._onTouchMove, this); on(document, 'touchend', this._onTouchEnd, this); preventDefault(e); }, _onTouchMove: function (e) { if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; } var map = this._map, p1 = map.mouseEventToContainerPoint(e.touches[0]), p2 = map.mouseEventToContainerPoint(e.touches[1]), scale = p1.distanceTo(p2) / this._startDist; this._zoom = map.getScaleZoom(scale, this._startZoom); if (!map.options.bounceAtZoomLimits && ( (this._zoom < map.getMinZoom() && scale < 1) || (this._zoom > map.getMaxZoom() && scale > 1))) { this._zoom = map._limitZoom(this._zoom); } if (map.options.touchZoom === 'center') { this._center = this._startLatLng; if (scale === 1) { return; } } else { // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint); if (scale === 1 && delta.x === 0 && delta.y === 0) { return; } this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom); } if (!this._moved) { map._moveStart(true, false); this._moved = true; } cancelAnimFrame(this._animRequest); var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false}); this._animRequest = requestAnimFrame(moveFn, this, true); preventDefault(e); }, _onTouchEnd: function () { if (!this._moved || !this._zooming) { this._zooming = false; return; } this._zooming = false; cancelAnimFrame(this._animRequest); off(document, 'touchmove', this._onTouchMove); off(document, 'touchend', this._onTouchEnd); // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate. if (this._map.options.zoomAnimation) { this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap); } else { this._map._resetView(this._center, this._map._limitZoom(this._zoom)); } } }); // @section Handlers // @property touchZoom: Handler // Touch zoom handler. Map.addInitHook('addHandler', 'touchZoom', TouchZoom); Map.BoxZoom = BoxZoom; Map.DoubleClickZoom = DoubleClickZoom; Map.Drag = Drag; Map.Keyboard = Keyboard; Map.ScrollWheelZoom = ScrollWheelZoom; Map.Tap = Tap; Map.TouchZoom = TouchZoom; Object.freeze = freeze; exports.version = version; exports.Control = Control; exports.control = control; exports.Browser = Browser; exports.Evented = Evented; exports.Mixin = Mixin; exports.Util = Util; exports.Class = Class; exports.Handler = Handler; exports.extend = extend; exports.bind = bind; exports.stamp = stamp; exports.setOptions = setOptions; exports.DomEvent = DomEvent; exports.DomUtil = DomUtil; exports.PosAnimation = PosAnimation; exports.Draggable = Draggable; exports.LineUtil = LineUtil; exports.PolyUtil = PolyUtil; exports.Point = Point; exports.point = toPoint; exports.Bounds = Bounds; exports.bounds = toBounds; exports.Transformation = Transformation; exports.transformation = toTransformation; exports.Projection = index; exports.LatLng = LatLng; exports.latLng = toLatLng; exports.LatLngBounds = LatLngBounds; exports.latLngBounds = toLatLngBounds; exports.CRS = CRS; exports.GeoJSON = GeoJSON; exports.geoJSON = geoJSON; exports.geoJson = geoJson; exports.Layer = Layer; exports.LayerGroup = LayerGroup; exports.layerGroup = layerGroup; exports.FeatureGroup = FeatureGroup; exports.featureGroup = featureGroup; exports.ImageOverlay = ImageOverlay; exports.imageOverlay = imageOverlay; exports.VideoOverlay = VideoOverlay; exports.videoOverlay = videoOverlay; exports.SVGOverlay = SVGOverlay; exports.svgOverlay = svgOverlay; exports.DivOverlay = DivOverlay; exports.Popup = Popup; exports.popup = popup; exports.Tooltip = Tooltip; exports.tooltip = tooltip; exports.Icon = Icon; exports.icon = icon; exports.DivIcon = DivIcon; exports.divIcon = divIcon; exports.Marker = Marker; exports.marker = marker; exports.TileLayer = TileLayer; exports.tileLayer = tileLayer; exports.GridLayer = GridLayer; exports.gridLayer = gridLayer; exports.SVG = SVG; exports.svg = svg$1; exports.Renderer = Renderer; exports.Canvas = Canvas; exports.canvas = canvas$1; exports.Path = Path; exports.CircleMarker = CircleMarker; exports.circleMarker = circleMarker; exports.Circle = Circle; exports.circle = circle; exports.Polyline = Polyline; exports.polyline = polyline; exports.Polygon = Polygon; exports.polygon = polygon; exports.Rectangle = Rectangle; exports.rectangle = rectangle; exports.Map = Map; exports.map = createMap; var oldL = window.L; exports.noConflict = function() { window.L = oldL; return this; } // Always export us to window global (see #2364) window.L = exports; }))); //# sourceMappingURL=leaflet-src.js.map<|fim▁end|>
_onMouseMove: function (e) { if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }