You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

17459 lines
440 KiB

2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*!
  2. * Paper.js v0.12.15 - The Swiss Army Knife of Vector Graphics Scripting.
  3. * http://paperjs.org/
  4. *
  5. * Copyright (c) 2011 - 2020, Jürg Lehni & Jonathan Puckey
  6. * http://juerglehni.com/ & https://puckey.studio/
  7. *
  8. * Distributed under the MIT license. See LICENSE file for details.
  9. *
  10. * All rights reserved.
  11. *
  12. * Date: Wed Mar 17 10:49:48 2021 +0100
  13. *
  14. ***
  15. *
  16. * Straps.js - Class inheritance library with support for bean-style accessors
  17. *
  18. * Copyright (c) 2006 - 2020 Jürg Lehni
  19. * http://juerglehni.com/
  20. *
  21. * Distributed under the MIT license.
  22. *
  23. ***
  24. *
  25. * Acorn.js
  26. * https://marijnhaverbeke.nl/acorn/
  27. *
  28. * Acorn is a tiny, fast JavaScript parser written in JavaScript,
  29. * created by Marijn Haverbeke and released under an MIT license.
  30. *
  31. */
  32. var paper = function(self, undefined) {
  33. self = self || require('./node/self.js');
  34. var window = self.window,
  35. document = self.document;
  36. var Base = new function() {
  37. var hidden = /^(statics|enumerable|beans|preserve)$/,
  38. array = [],
  39. slice = array.slice,
  40. create = Object.create,
  41. describe = Object.getOwnPropertyDescriptor,
  42. define = Object.defineProperty,
  43. forEach = array.forEach || function(iter, bind) {
  44. for (var i = 0, l = this.length; i < l; i++) {
  45. iter.call(bind, this[i], i, this);
  46. }
  47. },
  48. forIn = function(iter, bind) {
  49. for (var i in this) {
  50. if (this.hasOwnProperty(i))
  51. iter.call(bind, this[i], i, this);
  52. }
  53. },
  54. set = Object.assign || function(dst) {
  55. for (var i = 1, l = arguments.length; i < l; i++) {
  56. var src = arguments[i];
  57. for (var key in src) {
  58. if (src.hasOwnProperty(key))
  59. dst[key] = src[key];
  60. }
  61. }
  62. return dst;
  63. },
  64. each = function(obj, iter, bind) {
  65. if (obj) {
  66. var desc = describe(obj, 'length');
  67. (desc && typeof desc.value === 'number' ? forEach : forIn)
  68. .call(obj, iter, bind = bind || obj);
  69. }
  70. return bind;
  71. };
  72. function inject(dest, src, enumerable, beans, preserve) {
  73. var beansNames = {};
  74. function field(name, val) {
  75. val = val || (val = describe(src, name))
  76. && (val.get ? val : val.value);
  77. if (typeof val === 'string' && val[0] === '#')
  78. val = dest[val.substring(1)] || val;
  79. var isFunc = typeof val === 'function',
  80. res = val,
  81. prev = preserve || isFunc && !val.base
  82. ? (val && val.get ? name in dest : dest[name])
  83. : null,
  84. bean;
  85. if (!preserve || !prev) {
  86. if (isFunc && prev)
  87. val.base = prev;
  88. if (isFunc && beans !== false
  89. && (bean = name.match(/^([gs]et|is)(([A-Z])(.*))$/)))
  90. beansNames[bean[3].toLowerCase() + bean[4]] = bean[2];
  91. if (!res || isFunc || !res.get || typeof res.get !== 'function'
  92. || !Base.isPlainObject(res)) {
  93. res = { value: res, writable: true };
  94. }
  95. if ((describe(dest, name)
  96. || { configurable: true }).configurable) {
  97. res.configurable = true;
  98. res.enumerable = enumerable != null ? enumerable : !bean;
  99. }
  100. define(dest, name, res);
  101. }
  102. }
  103. if (src) {
  104. for (var name in src) {
  105. if (src.hasOwnProperty(name) && !hidden.test(name))
  106. field(name);
  107. }
  108. for (var name in beansNames) {
  109. var part = beansNames[name],
  110. set = dest['set' + part],
  111. get = dest['get' + part] || set && dest['is' + part];
  112. if (get && (beans === true || get.length === 0))
  113. field(name, { get: get, set: set });
  114. }
  115. }
  116. return dest;
  117. }
  118. function Base() {
  119. for (var i = 0, l = arguments.length; i < l; i++) {
  120. var src = arguments[i];
  121. if (src)
  122. set(this, src);
  123. }
  124. return this;
  125. }
  126. return inject(Base, {
  127. inject: function(src) {
  128. if (src) {
  129. var statics = src.statics === true ? src : src.statics,
  130. beans = src.beans,
  131. preserve = src.preserve;
  132. if (statics !== src)
  133. inject(this.prototype, src, src.enumerable, beans, preserve);
  134. inject(this, statics, null, beans, preserve);
  135. }
  136. for (var i = 1, l = arguments.length; i < l; i++)
  137. this.inject(arguments[i]);
  138. return this;
  139. },
  140. extend: function() {
  141. var base = this,
  142. ctor,
  143. proto;
  144. for (var i = 0, obj, l = arguments.length;
  145. i < l && !(ctor && proto); i++) {
  146. obj = arguments[i];
  147. ctor = ctor || obj.initialize;
  148. proto = proto || obj.prototype;
  149. }
  150. ctor = ctor || function() {
  151. base.apply(this, arguments);
  152. };
  153. proto = ctor.prototype = proto || create(this.prototype);
  154. define(proto, 'constructor',
  155. { value: ctor, writable: true, configurable: true });
  156. inject(ctor, this);
  157. if (arguments.length)
  158. this.inject.apply(ctor, arguments);
  159. ctor.base = base;
  160. return ctor;
  161. }
  162. }).inject({
  163. enumerable: false,
  164. initialize: Base,
  165. set: Base,
  166. inject: function() {
  167. for (var i = 0, l = arguments.length; i < l; i++) {
  168. var src = arguments[i];
  169. if (src) {
  170. inject(this, src, src.enumerable, src.beans, src.preserve);
  171. }
  172. }
  173. return this;
  174. },
  175. extend: function() {
  176. var res = create(this);
  177. return res.inject.apply(res, arguments);
  178. },
  179. each: function(iter, bind) {
  180. return each(this, iter, bind);
  181. },
  182. clone: function() {
  183. return new this.constructor(this);
  184. },
  185. statics: {
  186. set: set,
  187. each: each,
  188. create: create,
  189. define: define,
  190. describe: describe,
  191. clone: function(obj) {
  192. return set(new obj.constructor(), obj);
  193. },
  194. isPlainObject: function(obj) {
  195. var ctor = obj != null && obj.constructor;
  196. return ctor && (ctor === Object || ctor === Base
  197. || ctor.name === 'Object');
  198. },
  199. pick: function(a, b) {
  200. return a !== undefined ? a : b;
  201. },
  202. slice: function(list, begin, end) {
  203. return slice.call(list, begin, end);
  204. }
  205. }
  206. });
  207. };
  208. if (typeof module !== 'undefined')
  209. module.exports = Base;
  210. Base.inject({
  211. enumerable: false,
  212. toString: function() {
  213. return this._id != null
  214. ? (this._class || 'Object') + (this._name
  215. ? " '" + this._name + "'"
  216. : ' @' + this._id)
  217. : '{ ' + Base.each(this, function(value, key) {
  218. if (!/^_/.test(key)) {
  219. var type = typeof value;
  220. this.push(key + ': ' + (type === 'number'
  221. ? Formatter.instance.number(value)
  222. : type === 'string' ? "'" + value + "'" : value));
  223. }
  224. }, []).join(', ') + ' }';
  225. },
  226. getClassName: function() {
  227. return this._class || '';
  228. },
  229. importJSON: function(json) {
  230. return Base.importJSON(json, this);
  231. },
  232. exportJSON: function(options) {
  233. return Base.exportJSON(this, options);
  234. },
  235. toJSON: function() {
  236. return Base.serialize(this);
  237. },
  238. set: function(props, exclude) {
  239. if (props)
  240. Base.filter(this, props, exclude, this._prioritize);
  241. return this;
  242. }
  243. }, {
  244. beans: false,
  245. statics: {
  246. exports: {},
  247. extend: function extend() {
  248. var res = extend.base.apply(this, arguments),
  249. name = res.prototype._class;
  250. if (name && !Base.exports[name])
  251. Base.exports[name] = res;
  252. return res;
  253. },
  254. equals: function(obj1, obj2) {
  255. if (obj1 === obj2)
  256. return true;
  257. if (obj1 && obj1.equals)
  258. return obj1.equals(obj2);
  259. if (obj2 && obj2.equals)
  260. return obj2.equals(obj1);
  261. if (obj1 && obj2
  262. && typeof obj1 === 'object' && typeof obj2 === 'object') {
  263. if (Array.isArray(obj1) && Array.isArray(obj2)) {
  264. var length = obj1.length;
  265. if (length !== obj2.length)
  266. return false;
  267. while (length--) {
  268. if (!Base.equals(obj1[length], obj2[length]))
  269. return false;
  270. }
  271. } else {
  272. var keys = Object.keys(obj1),
  273. length = keys.length;
  274. if (length !== Object.keys(obj2).length)
  275. return false;
  276. while (length--) {
  277. var key = keys[length];
  278. if (!(obj2.hasOwnProperty(key)
  279. && Base.equals(obj1[key], obj2[key])))
  280. return false;
  281. }
  282. }
  283. return true;
  284. }
  285. return false;
  286. },
  287. read: function(list, start, options, amount) {
  288. if (this === Base) {
  289. var value = this.peek(list, start);
  290. list.__index++;
  291. return value;
  292. }
  293. var proto = this.prototype,
  294. readIndex = proto._readIndex,
  295. begin = start || readIndex && list.__index || 0,
  296. length = list.length,
  297. obj = list[begin];
  298. amount = amount || length - begin;
  299. if (obj instanceof this
  300. || options && options.readNull && obj == null && amount <= 1) {
  301. if (readIndex)
  302. list.__index = begin + 1;
  303. return obj && options && options.clone ? obj.clone() : obj;
  304. }
  305. obj = Base.create(proto);
  306. if (readIndex)
  307. obj.__read = true;
  308. obj = obj.initialize.apply(obj, begin > 0 || begin + amount < length
  309. ? Base.slice(list, begin, begin + amount)
  310. : list) || obj;
  311. if (readIndex) {
  312. list.__index = begin + obj.__read;
  313. var filtered = obj.__filtered;
  314. if (filtered) {
  315. list.__filtered = filtered;
  316. obj.__filtered = undefined;
  317. }
  318. obj.__read = undefined;
  319. }
  320. return obj;
  321. },
  322. peek: function(list, start) {
  323. return list[list.__index = start || list.__index || 0];
  324. },
  325. remain: function(list) {
  326. return list.length - (list.__index || 0);
  327. },
  328. readList: function(list, start, options, amount) {
  329. var res = [],
  330. entry,
  331. begin = start || 0,
  332. end = amount ? begin + amount : list.length;
  333. for (var i = begin; i < end; i++) {
  334. res.push(Array.isArray(entry = list[i])
  335. ? this.read(entry, 0, options)
  336. : this.read(list, i, options, 1));
  337. }
  338. return res;
  339. },
  340. readNamed: function(list, name, start, options, amount) {
  341. var value = this.getNamed(list, name),
  342. hasValue = value !== undefined;
  343. if (hasValue) {
  344. var filtered = list.__filtered;
  345. if (!filtered) {
  346. var source = this.getSource(list);
  347. filtered = list.__filtered = Base.create(source);
  348. filtered.__unfiltered = source;
  349. }
  350. filtered[name] = undefined;
  351. }
  352. return this.read(hasValue ? [value] : list, start, options, amount);
  353. },
  354. readSupported: function(list, dest) {
  355. var source = this.getSource(list),
  356. that = this,
  357. read = false;
  358. if (source) {
  359. Object.keys(source).forEach(function(key) {
  360. if (key in dest) {
  361. var value = that.readNamed(list, key);
  362. if (value !== undefined) {
  363. dest[key] = value;
  364. }
  365. read = true;
  366. }
  367. });
  368. }
  369. return read;
  370. },
  371. getSource: function(list) {
  372. var source = list.__source;
  373. if (source === undefined) {
  374. var arg = list.length === 1 && list[0];
  375. source = list.__source = arg && Base.isPlainObject(arg)
  376. ? arg : null;
  377. }
  378. return source;
  379. },
  380. getNamed: function(list, name) {
  381. var source = this.getSource(list);
  382. if (source) {
  383. return name ? source[name] : list.__filtered || source;
  384. }
  385. },
  386. hasNamed: function(list, name) {
  387. return !!this.getNamed(list, name);
  388. },
  389. filter: function(dest, source, exclude, prioritize) {
  390. var processed;
  391. function handleKey(key) {
  392. if (!(exclude && key in exclude) &&
  393. !(processed && key in processed)) {
  394. var value = source[key];
  395. if (value !== undefined)
  396. dest[key] = value;
  397. }
  398. }
  399. if (prioritize) {
  400. var keys = {};
  401. for (var i = 0, key, l = prioritize.length; i < l; i++) {
  402. if ((key = prioritize[i]) in source) {
  403. handleKey(key);
  404. keys[key] = true;
  405. }
  406. }
  407. processed = keys;
  408. }
  409. Object.keys(source.__unfiltered || source).forEach(handleKey);
  410. return dest;
  411. },
  412. isPlainValue: function(obj, asString) {
  413. return Base.isPlainObject(obj) || Array.isArray(obj)
  414. || asString && typeof obj === 'string';
  415. },
  416. serialize: function(obj, options, compact, dictionary) {
  417. options = options || {};
  418. var isRoot = !dictionary,
  419. res;
  420. if (isRoot) {
  421. options.formatter = new Formatter(options.precision);
  422. dictionary = {
  423. length: 0,
  424. definitions: {},
  425. references: {},
  426. add: function(item, create) {
  427. var id = '#' + item._id,
  428. ref = this.references[id];
  429. if (!ref) {
  430. this.length++;
  431. var res = create.call(item),
  432. name = item._class;
  433. if (name && res[0] !== name)
  434. res.unshift(name);
  435. this.definitions[id] = res;
  436. ref = this.references[id] = [id];
  437. }
  438. return ref;
  439. }
  440. };
  441. }
  442. if (obj && obj._serialize) {
  443. res = obj._serialize(options, dictionary);
  444. var name = obj._class;
  445. if (name && !obj._compactSerialize && (isRoot || !compact)
  446. && res[0] !== name) {
  447. res.unshift(name);
  448. }
  449. } else if (Array.isArray(obj)) {
  450. res = [];
  451. for (var i = 0, l = obj.length; i < l; i++)
  452. res[i] = Base.serialize(obj[i], options, compact, dictionary);
  453. } else if (Base.isPlainObject(obj)) {
  454. res = {};
  455. var keys = Object.keys(obj);
  456. for (var i = 0, l = keys.length; i < l; i++) {
  457. var key = keys[i];
  458. res[key] = Base.serialize(obj[key], options, compact,
  459. dictionary);
  460. }
  461. } else if (typeof obj === 'number') {
  462. res = options.formatter.number(obj, options.precision);
  463. } else {
  464. res = obj;
  465. }
  466. return isRoot && dictionary.length > 0
  467. ? [['dictionary', dictionary.definitions], res]
  468. : res;
  469. },
  470. deserialize: function(json, create, _data, _setDictionary, _isRoot) {
  471. var res = json,
  472. isFirst = !_data,
  473. hasDictionary = isFirst && json && json.length
  474. && json[0][0] === 'dictionary';
  475. _data = _data || {};
  476. if (Array.isArray(json)) {
  477. var type = json[0],
  478. isDictionary = type === 'dictionary';
  479. if (json.length == 1 && /^#/.test(type)) {
  480. return _data.dictionary[type];
  481. }
  482. type = Base.exports[type];
  483. res = [];
  484. for (var i = type ? 1 : 0, l = json.length; i < l; i++) {
  485. res.push(Base.deserialize(json[i], create, _data,
  486. isDictionary, hasDictionary));
  487. }
  488. if (type) {
  489. var args = res;
  490. if (create) {
  491. res = create(type, args, isFirst || _isRoot);
  492. } else {
  493. res = new type(args);
  494. }
  495. }
  496. } else if (Base.isPlainObject(json)) {
  497. res = {};
  498. if (_setDictionary)
  499. _data.dictionary = res;
  500. for (var key in json)
  501. res[key] = Base.deserialize(json[key], create, _data);
  502. }
  503. return hasDictionary ? res[1] : res;
  504. },
  505. exportJSON: function(obj, options) {
  506. var json = Base.serialize(obj, options);
  507. return options && options.asString == false
  508. ? json
  509. : JSON.stringify(json);
  510. },
  511. importJSON: function(json, target) {
  512. return Base.deserialize(
  513. typeof json === 'string' ? JSON.parse(json) : json,
  514. function(ctor, args, isRoot) {
  515. var useTarget = isRoot && target
  516. && target.constructor === ctor,
  517. obj = useTarget ? target
  518. : Base.create(ctor.prototype);
  519. if (args.length === 1 && obj instanceof Item
  520. && (useTarget || !(obj instanceof Layer))) {
  521. var arg = args[0];
  522. if (Base.isPlainObject(arg)) {
  523. arg.insert = false;
  524. if (useTarget) {
  525. args = args.concat([{ insert: true }]);
  526. }
  527. }
  528. }
  529. (useTarget ? obj.set : ctor).apply(obj, args);
  530. if (useTarget)
  531. target = null;
  532. return obj;
  533. });
  534. },
  535. push: function(list, items) {
  536. var itemsLength = items.length;
  537. if (itemsLength < 4096) {
  538. list.push.apply(list, items);
  539. } else {
  540. var startLength = list.length;
  541. list.length += itemsLength;
  542. for (var i = 0; i < itemsLength; i++) {
  543. list[startLength + i] = items[i];
  544. }
  545. }
  546. return list;
  547. },
  548. splice: function(list, items, index, remove) {
  549. var amount = items && items.length,
  550. append = index === undefined;
  551. index = append ? list.length : index;
  552. if (index > list.length)
  553. index = list.length;
  554. for (var i = 0; i < amount; i++)
  555. items[i]._index = index + i;
  556. if (append) {
  557. Base.push(list, items);
  558. return [];
  559. } else {
  560. var args = [index, remove];
  561. if (items)
  562. Base.push(args, items);
  563. var removed = list.splice.apply(list, args);
  564. for (var i = 0, l = removed.length; i < l; i++)
  565. removed[i]._index = undefined;
  566. for (var i = index + amount, l = list.length; i < l; i++)
  567. list[i]._index = i;
  568. return removed;
  569. }
  570. },
  571. capitalize: function(str) {
  572. return str.replace(/\b[a-z]/g, function(match) {
  573. return match.toUpperCase();
  574. });
  575. },
  576. camelize: function(str) {
  577. return str.replace(/-(.)/g, function(match, chr) {
  578. return chr.toUpperCase();
  579. });
  580. },
  581. hyphenate: function(str) {
  582. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  583. }
  584. }});
  585. var Emitter = {
  586. on: function(type, func) {
  587. if (typeof type !== 'string') {
  588. Base.each(type, function(value, key) {
  589. this.on(key, value);
  590. }, this);
  591. } else {
  592. var types = this._eventTypes,
  593. entry = types && types[type],
  594. handlers = this._callbacks = this._callbacks || {};
  595. handlers = handlers[type] = handlers[type] || [];
  596. if (handlers.indexOf(func) === -1) {
  597. handlers.push(func);
  598. if (entry && entry.install && handlers.length === 1)
  599. entry.install.call(this, type);
  600. }
  601. }
  602. return this;
  603. },
  604. off: function(type, func) {
  605. if (typeof type !== 'string') {
  606. Base.each(type, function(value, key) {
  607. this.off(key, value);
  608. }, this);
  609. return;
  610. }
  611. var types = this._eventTypes,
  612. entry = types && types[type],
  613. handlers = this._callbacks && this._callbacks[type],
  614. index;
  615. if (handlers) {
  616. if (!func || (index = handlers.indexOf(func)) !== -1
  617. && handlers.length === 1) {
  618. if (entry && entry.uninstall)
  619. entry.uninstall.call(this, type);
  620. delete this._callbacks[type];
  621. } else if (index !== -1) {
  622. handlers.splice(index, 1);
  623. }
  624. }
  625. return this;
  626. },
  627. once: function(type, func) {
  628. return this.on(type, function handler() {
  629. func.apply(this, arguments);
  630. this.off(type, handler);
  631. });
  632. },
  633. emit: function(type, event) {
  634. var handlers = this._callbacks && this._callbacks[type];
  635. if (!handlers)
  636. return false;
  637. var args = Base.slice(arguments, 1),
  638. setTarget = event && event.target && !event.currentTarget;
  639. handlers = handlers.slice();
  640. if (setTarget)
  641. event.currentTarget = this;
  642. for (var i = 0, l = handlers.length; i < l; i++) {
  643. if (handlers[i].apply(this, args) == false) {
  644. if (event && event.stop)
  645. event.stop();
  646. break;
  647. }
  648. }
  649. if (setTarget)
  650. delete event.currentTarget;
  651. return true;
  652. },
  653. responds: function(type) {
  654. return !!(this._callbacks && this._callbacks[type]);
  655. },
  656. attach: '#on',
  657. detach: '#off',
  658. fire: '#emit',
  659. _installEvents: function(install) {
  660. var types = this._eventTypes,
  661. handlers = this._callbacks,
  662. key = install ? 'install' : 'uninstall';
  663. if (types) {
  664. for (var type in handlers) {
  665. if (handlers[type].length > 0) {
  666. var entry = types[type],
  667. func = entry && entry[key];
  668. if (func)
  669. func.call(this, type);
  670. }
  671. }
  672. }
  673. },
  674. statics: {
  675. inject: function inject(src) {
  676. var events = src._events;
  677. if (events) {
  678. var types = {};
  679. Base.each(events, function(entry, key) {
  680. var isString = typeof entry === 'string',
  681. name = isString ? entry : key,
  682. part = Base.capitalize(name),
  683. type = name.substring(2).toLowerCase();
  684. types[type] = isString ? {} : entry;
  685. name = '_' + name;
  686. src['get' + part] = function() {
  687. return this[name];
  688. };
  689. src['set' + part] = function(func) {
  690. var prev = this[name];
  691. if (prev)
  692. this.off(type, prev);
  693. if (func)
  694. this.on(type, func);
  695. this[name] = func;
  696. };
  697. });
  698. src._eventTypes = types;
  699. }
  700. return inject.base.apply(this, arguments);
  701. }
  702. }
  703. };
  704. var PaperScope = Base.extend({
  705. _class: 'PaperScope',
  706. initialize: function PaperScope() {
  707. paper = this;
  708. this.settings = new Base({
  709. applyMatrix: true,
  710. insertItems: true,
  711. handleSize: 4,
  712. hitTolerance: 0
  713. });
  714. this.project = null;
  715. this.projects = [];
  716. this.tools = [];
  717. this._id = PaperScope._id++;
  718. PaperScope._scopes[this._id] = this;
  719. var proto = PaperScope.prototype;
  720. if (!this.support) {
  721. var ctx = CanvasProvider.getContext(1, 1) || {};
  722. proto.support = {
  723. nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,
  724. nativeBlendModes: BlendMode.nativeModes
  725. };
  726. CanvasProvider.release(ctx);
  727. }
  728. if (!this.agent) {
  729. var user = self.navigator.userAgent.toLowerCase(),
  730. os = (/(darwin|win|mac|linux|freebsd|sunos)/.exec(user)||[])[0],
  731. platform = os === 'darwin' ? 'mac' : os,
  732. agent = proto.agent = proto.browser = { platform: platform };
  733. if (platform)
  734. agent[platform] = true;
  735. user.replace(
  736. /(opera|chrome|safari|webkit|firefox|msie|trident|atom|node|jsdom)\/?\s*([.\d]+)(?:.*version\/([.\d]+))?(?:.*rv\:v?([.\d]+))?/g,
  737. function(match, n, v1, v2, rv) {
  738. if (!agent.chrome) {
  739. var v = n === 'opera' ? v2 :
  740. /^(node|trident)$/.test(n) ? rv : v1;
  741. agent.version = v;
  742. agent.versionNumber = parseFloat(v);
  743. n = { trident: 'msie', jsdom: 'node' }[n] || n;
  744. agent.name = n;
  745. agent[n] = true;
  746. }
  747. }
  748. );
  749. if (agent.chrome)
  750. delete agent.webkit;
  751. if (agent.atom)
  752. delete agent.chrome;
  753. }
  754. },
  755. version: "0.12.15",
  756. getView: function() {
  757. var project = this.project;
  758. return project && project._view;
  759. },
  760. getPaper: function() {
  761. return this;
  762. },
  763. execute: function(code, options) {
  764. var exports = paper.PaperScript.execute(code, this, options);
  765. View.updateFocus();
  766. return exports;
  767. },
  768. install: function(scope) {
  769. var that = this;
  770. Base.each(['project', 'view', 'tool'], function(key) {
  771. Base.define(scope, key, {
  772. configurable: true,
  773. get: function() {
  774. return that[key];
  775. }
  776. });
  777. });
  778. for (var key in this)
  779. if (!/^_/.test(key) && this[key])
  780. scope[key] = this[key];
  781. },
  782. setup: function(element) {
  783. paper = this;
  784. this.project = new Project(element);
  785. return this;
  786. },
  787. createCanvas: function(width, height) {
  788. return CanvasProvider.getCanvas(width, height);
  789. },
  790. activate: function() {
  791. paper = this;
  792. },
  793. clear: function() {
  794. var projects = this.projects,
  795. tools = this.tools;
  796. for (var i = projects.length - 1; i >= 0; i--)
  797. projects[i].remove();
  798. for (var i = tools.length - 1; i >= 0; i--)
  799. tools[i].remove();
  800. },
  801. remove: function() {
  802. this.clear();
  803. delete PaperScope._scopes[this._id];
  804. },
  805. statics: new function() {
  806. function handleAttribute(name) {
  807. name += 'Attribute';
  808. return function(el, attr) {
  809. return el[name](attr) || el[name]('data-paper-' + attr);
  810. };
  811. }
  812. return {
  813. _scopes: {},
  814. _id: 0,
  815. get: function(id) {
  816. return this._scopes[id] || null;
  817. },
  818. getAttribute: handleAttribute('get'),
  819. hasAttribute: handleAttribute('has')
  820. };
  821. }
  822. });
  823. var PaperScopeItem = Base.extend(Emitter, {
  824. initialize: function(activate) {
  825. this._scope = paper;
  826. this._index = this._scope[this._list].push(this) - 1;
  827. if (activate || !this._scope[this._reference])
  828. this.activate();
  829. },
  830. activate: function() {
  831. if (!this._scope)
  832. return false;
  833. var prev = this._scope[this._reference];
  834. if (prev && prev !== this)
  835. prev.emit('deactivate');
  836. this._scope[this._reference] = this;
  837. this.emit('activate', prev);
  838. return true;
  839. },
  840. isActive: function() {
  841. return this._scope[this._reference] === this;
  842. },
  843. remove: function() {
  844. if (this._index == null)
  845. return false;
  846. Base.splice(this._scope[this._list], null, this._index, 1);
  847. if (this._scope[this._reference] == this)
  848. this._scope[this._reference] = null;
  849. this._scope = null;
  850. return true;
  851. },
  852. getView: function() {
  853. return this._scope.getView();
  854. }
  855. });
  856. var CollisionDetection = {
  857. findItemBoundsCollisions: function(items1, items2, tolerance) {
  858. function getBounds(items) {
  859. var bounds = new Array(items.length);
  860. for (var i = 0; i < items.length; i++) {
  861. var rect = items[i].getBounds();
  862. bounds[i] = [rect.left, rect.top, rect.right, rect.bottom];
  863. }
  864. return bounds;
  865. }
  866. var bounds1 = getBounds(items1),
  867. bounds2 = !items2 || items2 === items1
  868. ? bounds1
  869. : getBounds(items2);
  870. return this.findBoundsCollisions(bounds1, bounds2, tolerance || 0);
  871. },
  872. findCurveBoundsCollisions: function(curves1, curves2, tolerance, bothAxis) {
  873. function getBounds(curves) {
  874. var min = Math.min,
  875. max = Math.max,
  876. bounds = new Array(curves.length);
  877. for (var i = 0; i < curves.length; i++) {
  878. var v = curves[i];
  879. bounds[i] = [
  880. min(v[0], v[2], v[4], v[6]),
  881. min(v[1], v[3], v[5], v[7]),
  882. max(v[0], v[2], v[4], v[6]),
  883. max(v[1], v[3], v[5], v[7])
  884. ];
  885. }
  886. return bounds;
  887. }
  888. var bounds1 = getBounds(curves1),
  889. bounds2 = !curves2 || curves2 === curves1
  890. ? bounds1
  891. : getBounds(curves2);
  892. if (bothAxis) {
  893. var hor = this.findBoundsCollisions(
  894. bounds1, bounds2, tolerance || 0, false, true),
  895. ver = this.findBoundsCollisions(
  896. bounds1, bounds2, tolerance || 0, true, true),
  897. list = [];
  898. for (var i = 0, l = hor.length; i < l; i++) {
  899. list[i] = { hor: hor[i], ver: ver[i] };
  900. }
  901. return list;
  902. }
  903. return this.findBoundsCollisions(bounds1, bounds2, tolerance || 0);
  904. },
  905. findBoundsCollisions: function(boundsA, boundsB, tolerance,
  906. sweepVertical, onlySweepAxisCollisions) {
  907. var self = !boundsB || boundsA === boundsB,
  908. allBounds = self ? boundsA : boundsA.concat(boundsB),
  909. lengthA = boundsA.length,
  910. lengthAll = allBounds.length;
  911. function binarySearch(indices, coord, value) {
  912. var lo = 0,
  913. hi = indices.length;
  914. while (lo < hi) {
  915. var mid = (hi + lo) >>> 1;
  916. if (allBounds[indices[mid]][coord] < value) {
  917. lo = mid + 1;
  918. } else {
  919. hi = mid;
  920. }
  921. }
  922. return lo - 1;
  923. }
  924. var pri0 = sweepVertical ? 1 : 0,
  925. pri1 = pri0 + 2,
  926. sec0 = sweepVertical ? 0 : 1,
  927. sec1 = sec0 + 2;
  928. var allIndicesByPri0 = new Array(lengthAll);
  929. for (var i = 0; i < lengthAll; i++) {
  930. allIndicesByPri0[i] = i;
  931. }
  932. allIndicesByPri0.sort(function(i1, i2) {
  933. return allBounds[i1][pri0] - allBounds[i2][pri0];
  934. });
  935. var activeIndicesByPri1 = [],
  936. allCollisions = new Array(lengthA);
  937. for (var i = 0; i < lengthAll; i++) {
  938. var curIndex = allIndicesByPri0[i],
  939. curBounds = allBounds[curIndex],
  940. origIndex = self ? curIndex : curIndex - lengthA,
  941. isCurrentA = curIndex < lengthA,
  942. isCurrentB = self || !isCurrentA,
  943. curCollisions = isCurrentA ? [] : null;
  944. if (activeIndicesByPri1.length) {
  945. var pruneCount = binarySearch(activeIndicesByPri1, pri1,
  946. curBounds[pri0] - tolerance) + 1;
  947. activeIndicesByPri1.splice(0, pruneCount);
  948. if (self && onlySweepAxisCollisions) {
  949. curCollisions = curCollisions.concat(activeIndicesByPri1);
  950. for (var j = 0; j < activeIndicesByPri1.length; j++) {
  951. var activeIndex = activeIndicesByPri1[j];
  952. allCollisions[activeIndex].push(origIndex);
  953. }
  954. } else {
  955. var curSec1 = curBounds[sec1],
  956. curSec0 = curBounds[sec0];
  957. for (var j = 0; j < activeIndicesByPri1.length; j++) {
  958. var activeIndex = activeIndicesByPri1[j],
  959. activeBounds = allBounds[activeIndex],
  960. isActiveA = activeIndex < lengthA,
  961. isActiveB = self || activeIndex >= lengthA;
  962. if (
  963. onlySweepAxisCollisions ||
  964. (
  965. isCurrentA && isActiveB ||
  966. isCurrentB && isActiveA
  967. ) && (
  968. curSec1 >= activeBounds[sec0] - tolerance &&
  969. curSec0 <= activeBounds[sec1] + tolerance
  970. )
  971. ) {
  972. if (isCurrentA && isActiveB) {
  973. curCollisions.push(
  974. self ? activeIndex : activeIndex - lengthA);
  975. }
  976. if (isCurrentB && isActiveA) {
  977. allCollisions[activeIndex].push(origIndex);
  978. }
  979. }
  980. }
  981. }
  982. }
  983. if (isCurrentA) {
  984. if (boundsA === boundsB) {
  985. curCollisions.push(curIndex);
  986. }
  987. allCollisions[curIndex] = curCollisions;
  988. }
  989. if (activeIndicesByPri1.length) {
  990. var curPri1 = curBounds[pri1],
  991. index = binarySearch(activeIndicesByPri1, pri1, curPri1);
  992. activeIndicesByPri1.splice(index + 1, 0, curIndex);
  993. } else {
  994. activeIndicesByPri1.push(curIndex);
  995. }
  996. }
  997. for (var i = 0; i < allCollisions.length; i++) {
  998. var collisions = allCollisions[i];
  999. if (collisions) {
  1000. collisions.sort(function(i1, i2) { return i1 - i2; });
  1001. }
  1002. }
  1003. return allCollisions;
  1004. }
  1005. };
  1006. var Formatter = Base.extend({
  1007. initialize: function(precision) {
  1008. this.precision = Base.pick(precision, 5);
  1009. this.multiplier = Math.pow(10, this.precision);
  1010. },
  1011. number: function(val) {
  1012. return this.precision < 16
  1013. ? Math.round(val * this.multiplier) / this.multiplier : val;
  1014. },
  1015. pair: function(val1, val2, separator) {
  1016. return this.number(val1) + (separator || ',') + this.number(val2);
  1017. },
  1018. point: function(val, separator) {
  1019. return this.number(val.x) + (separator || ',') + this.number(val.y);
  1020. },
  1021. size: function(val, separator) {
  1022. return this.number(val.width) + (separator || ',')
  1023. + this.number(val.height);
  1024. },
  1025. rectangle: function(val, separator) {
  1026. return this.point(val, separator) + (separator || ',')
  1027. + this.size(val, separator);
  1028. }
  1029. });
  1030. Formatter.instance = new Formatter();
  1031. var Numerical = new function() {
  1032. var abscissas = [
  1033. [ 0.5773502691896257645091488],
  1034. [0,0.7745966692414833770358531],
  1035. [ 0.3399810435848562648026658,0.8611363115940525752239465],
  1036. [0,0.5384693101056830910363144,0.9061798459386639927976269],
  1037. [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
  1038. [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
  1039. [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
  1040. [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
  1041. [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
  1042. [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
  1043. [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
  1044. [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
  1045. [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
  1046. [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
  1047. [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
  1048. ];
  1049. var weights = [
  1050. [1],
  1051. [0.8888888888888888888888889,0.5555555555555555555555556],
  1052. [0.6521451548625461426269361,0.3478548451374538573730639],
  1053. [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
  1054. [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
  1055. [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
  1056. [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
  1057. [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
  1058. [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
  1059. [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
  1060. [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
  1061. [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
  1062. [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
  1063. [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
  1064. [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
  1065. ];
  1066. var abs = Math.abs,
  1067. sqrt = Math.sqrt,
  1068. pow = Math.pow,
  1069. log2 = Math.log2 || function(x) {
  1070. return Math.log(x) * Math.LOG2E;
  1071. },
  1072. EPSILON = 1e-12,
  1073. MACHINE_EPSILON = 1.12e-16;
  1074. function clamp(value, min, max) {
  1075. return value < min ? min : value > max ? max : value;
  1076. }
  1077. function getDiscriminant(a, b, c) {
  1078. function split(v) {
  1079. var x = v * 134217729,
  1080. y = v - x,
  1081. hi = y + x,
  1082. lo = v - hi;
  1083. return [hi, lo];
  1084. }
  1085. var D = b * b - a * c,
  1086. E = b * b + a * c;
  1087. if (abs(D) * 3 < E) {
  1088. var ad = split(a),
  1089. bd = split(b),
  1090. cd = split(c),
  1091. p = b * b,
  1092. dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1],
  1093. q = a * c,
  1094. dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0])
  1095. + ad[1] * cd[1];
  1096. D = (p - q) + (dp - dq);
  1097. }
  1098. return D;
  1099. }
  1100. function getNormalizationFactor() {
  1101. var norm = Math.max.apply(Math, arguments);
  1102. return norm && (norm < 1e-8 || norm > 1e8)
  1103. ? pow(2, -Math.round(log2(norm)))
  1104. : 0;
  1105. }
  1106. return {
  1107. EPSILON: EPSILON,
  1108. MACHINE_EPSILON: MACHINE_EPSILON,
  1109. CURVETIME_EPSILON: 1e-8,
  1110. GEOMETRIC_EPSILON: 1e-7,
  1111. TRIGONOMETRIC_EPSILON: 1e-8,
  1112. KAPPA: 4 * (sqrt(2) - 1) / 3,
  1113. isZero: function(val) {
  1114. return val >= -EPSILON && val <= EPSILON;
  1115. },
  1116. isMachineZero: function(val) {
  1117. return val >= -MACHINE_EPSILON && val <= MACHINE_EPSILON;
  1118. },
  1119. clamp: clamp,
  1120. integrate: function(f, a, b, n) {
  1121. var x = abscissas[n - 2],
  1122. w = weights[n - 2],
  1123. A = (b - a) * 0.5,
  1124. B = A + a,
  1125. i = 0,
  1126. m = (n + 1) >> 1,
  1127. sum = n & 1 ? w[i++] * f(B) : 0;
  1128. while (i < m) {
  1129. var Ax = A * x[i];
  1130. sum += w[i++] * (f(B + Ax) + f(B - Ax));
  1131. }
  1132. return A * sum;
  1133. },
  1134. findRoot: function(f, df, x, a, b, n, tolerance) {
  1135. for (var i = 0; i < n; i++) {
  1136. var fx = f(x),
  1137. dx = fx / df(x),
  1138. nx = x - dx;
  1139. if (abs(dx) < tolerance) {
  1140. x = nx;
  1141. break;
  1142. }
  1143. if (fx > 0) {
  1144. b = x;
  1145. x = nx <= a ? (a + b) * 0.5 : nx;
  1146. } else {
  1147. a = x;
  1148. x = nx >= b ? (a + b) * 0.5 : nx;
  1149. }
  1150. }
  1151. return clamp(x, a, b);
  1152. },
  1153. solveQuadratic: function(a, b, c, roots, min, max) {
  1154. var x1, x2 = Infinity;
  1155. if (abs(a) < EPSILON) {
  1156. if (abs(b) < EPSILON)
  1157. return abs(c) < EPSILON ? -1 : 0;
  1158. x1 = -c / b;
  1159. } else {
  1160. b *= -0.5;
  1161. var D = getDiscriminant(a, b, c);
  1162. if (D && abs(D) < MACHINE_EPSILON) {
  1163. var f = getNormalizationFactor(abs(a), abs(b), abs(c));
  1164. if (f) {
  1165. a *= f;
  1166. b *= f;
  1167. c *= f;
  1168. D = getDiscriminant(a, b, c);
  1169. }
  1170. }
  1171. if (D >= -MACHINE_EPSILON) {
  1172. var Q = D < 0 ? 0 : sqrt(D),
  1173. R = b + (b < 0 ? -Q : Q);
  1174. if (R === 0) {
  1175. x1 = c / a;
  1176. x2 = -x1;
  1177. } else {
  1178. x1 = R / a;
  1179. x2 = c / R;
  1180. }
  1181. }
  1182. }
  1183. var count = 0,
  1184. boundless = min == null,
  1185. minB = min - EPSILON,
  1186. maxB = max + EPSILON;
  1187. if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB))
  1188. roots[count++] = boundless ? x1 : clamp(x1, min, max);
  1189. if (x2 !== x1
  1190. && isFinite(x2) && (boundless || x2 > minB && x2 < maxB))
  1191. roots[count++] = boundless ? x2 : clamp(x2, min, max);
  1192. return count;
  1193. },
  1194. solveCubic: function(a, b, c, d, roots, min, max) {
  1195. var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)),
  1196. x, b1, c2, qd, q;
  1197. if (f) {
  1198. a *= f;
  1199. b *= f;
  1200. c *= f;
  1201. d *= f;
  1202. }
  1203. function evaluate(x0) {
  1204. x = x0;
  1205. var tmp = a * x;
  1206. b1 = tmp + b;
  1207. c2 = b1 * x + c;
  1208. qd = (tmp + b1) * x + c2;
  1209. q = c2 * x + d;
  1210. }
  1211. if (abs(a) < EPSILON) {
  1212. a = b;
  1213. b1 = c;
  1214. c2 = d;
  1215. x = Infinity;
  1216. } else if (abs(d) < EPSILON) {
  1217. b1 = b;
  1218. c2 = c;
  1219. x = 0;
  1220. } else {
  1221. evaluate(-(b / a) / 3);
  1222. var t = q / a,
  1223. r = pow(abs(t), 1/3),
  1224. s = t < 0 ? -1 : 1,
  1225. td = -qd / a,
  1226. rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r,
  1227. x0 = x - s * rd;
  1228. if (x0 !== x) {
  1229. do {
  1230. evaluate(x0);
  1231. x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON);
  1232. } while (s * x0 > s * x);
  1233. if (abs(a) * x * x > abs(d / x)) {
  1234. c2 = -d / x;
  1235. b1 = (c2 - c) / x;
  1236. }
  1237. }
  1238. }
  1239. var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max),
  1240. boundless = min == null;
  1241. if (isFinite(x) && (count === 0
  1242. || count > 0 && x !== roots[0] && x !== roots[1])
  1243. && (boundless || x > min - EPSILON && x < max + EPSILON))
  1244. roots[count++] = boundless ? x : clamp(x, min, max);
  1245. return count;
  1246. }
  1247. };
  1248. };
  1249. var UID = {
  1250. _id: 1,
  1251. _pools: {},
  1252. get: function(name) {
  1253. if (name) {
  1254. var pool = this._pools[name];
  1255. if (!pool)
  1256. pool = this._pools[name] = { _id: 1 };
  1257. return pool._id++;
  1258. } else {
  1259. return this._id++;
  1260. }
  1261. }
  1262. };
  1263. var Point = Base.extend({
  1264. _class: 'Point',
  1265. _readIndex: true,
  1266. initialize: function Point(arg0, arg1) {
  1267. var type = typeof arg0,
  1268. reading = this.__read,
  1269. read = 0;
  1270. if (type === 'number') {
  1271. var hasY = typeof arg1 === 'number';
  1272. this._set(arg0, hasY ? arg1 : arg0);
  1273. if (reading)
  1274. read = hasY ? 2 : 1;
  1275. } else if (type === 'undefined' || arg0 === null) {
  1276. this._set(0, 0);
  1277. if (reading)
  1278. read = arg0 === null ? 1 : 0;
  1279. } else {
  1280. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1281. read = 1;
  1282. if (Array.isArray(obj)) {
  1283. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1284. } else if ('x' in obj) {
  1285. this._set(obj.x || 0, obj.y || 0);
  1286. } else if ('width' in obj) {
  1287. this._set(obj.width || 0, obj.height || 0);
  1288. } else if ('angle' in obj) {
  1289. this._set(obj.length || 0, 0);
  1290. this.setAngle(obj.angle || 0);
  1291. } else {
  1292. this._set(0, 0);
  1293. read = 0;
  1294. }
  1295. }
  1296. if (reading)
  1297. this.__read = read;
  1298. return this;
  1299. },
  1300. set: '#initialize',
  1301. _set: function(x, y) {
  1302. this.x = x;
  1303. this.y = y;
  1304. return this;
  1305. },
  1306. equals: function(point) {
  1307. return this === point || point
  1308. && (this.x === point.x && this.y === point.y
  1309. || Array.isArray(point)
  1310. && this.x === point[0] && this.y === point[1])
  1311. || false;
  1312. },
  1313. clone: function() {
  1314. return new Point(this.x, this.y);
  1315. },
  1316. toString: function() {
  1317. var f = Formatter.instance;
  1318. return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
  1319. },
  1320. _serialize: function(options) {
  1321. var f = options.formatter;
  1322. return [f.number(this.x), f.number(this.y)];
  1323. },
  1324. getLength: function() {
  1325. return Math.sqrt(this.x * this.x + this.y * this.y);
  1326. },
  1327. setLength: function(length) {
  1328. if (this.isZero()) {
  1329. var angle = this._angle || 0;
  1330. this._set(
  1331. Math.cos(angle) * length,
  1332. Math.sin(angle) * length
  1333. );
  1334. } else {
  1335. var scale = length / this.getLength();
  1336. if (Numerical.isZero(scale))
  1337. this.getAngle();
  1338. this._set(
  1339. this.x * scale,
  1340. this.y * scale
  1341. );
  1342. }
  1343. },
  1344. getAngle: function() {
  1345. return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;
  1346. },
  1347. setAngle: function(angle) {
  1348. this.setAngleInRadians.call(this, angle * Math.PI / 180);
  1349. },
  1350. getAngleInDegrees: '#getAngle',
  1351. setAngleInDegrees: '#setAngle',
  1352. getAngleInRadians: function() {
  1353. if (!arguments.length) {
  1354. return this.isZero()
  1355. ? this._angle || 0
  1356. : this._angle = Math.atan2(this.y, this.x);
  1357. } else {
  1358. var point = Point.read(arguments),
  1359. div = this.getLength() * point.getLength();
  1360. if (Numerical.isZero(div)) {
  1361. return NaN;
  1362. } else {
  1363. var a = this.dot(point) / div;
  1364. return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a);
  1365. }
  1366. }
  1367. },
  1368. setAngleInRadians: function(angle) {
  1369. this._angle = angle;
  1370. if (!this.isZero()) {
  1371. var length = this.getLength();
  1372. this._set(
  1373. Math.cos(angle) * length,
  1374. Math.sin(angle) * length
  1375. );
  1376. }
  1377. },
  1378. getQuadrant: function() {
  1379. return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
  1380. }
  1381. }, {
  1382. beans: false,
  1383. getDirectedAngle: function() {
  1384. var point = Point.read(arguments);
  1385. return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
  1386. },
  1387. getDistance: function() {
  1388. var args = arguments,
  1389. point = Point.read(args),
  1390. x = point.x - this.x,
  1391. y = point.y - this.y,
  1392. d = x * x + y * y,
  1393. squared = Base.read(args);
  1394. return squared ? d : Math.sqrt(d);
  1395. },
  1396. normalize: function(length) {
  1397. if (length === undefined)
  1398. length = 1;
  1399. var current = this.getLength(),
  1400. scale = current !== 0 ? length / current : 0,
  1401. point = new Point(this.x * scale, this.y * scale);
  1402. if (scale >= 0)
  1403. point._angle = this._angle;
  1404. return point;
  1405. },
  1406. rotate: function(angle, center) {
  1407. if (angle === 0)
  1408. return this.clone();
  1409. angle = angle * Math.PI / 180;
  1410. var point = center ? this.subtract(center) : this,
  1411. sin = Math.sin(angle),
  1412. cos = Math.cos(angle);
  1413. point = new Point(
  1414. point.x * cos - point.y * sin,
  1415. point.x * sin + point.y * cos
  1416. );
  1417. return center ? point.add(center) : point;
  1418. },
  1419. transform: function(matrix) {
  1420. return matrix ? matrix._transformPoint(this) : this;
  1421. },
  1422. add: function() {
  1423. var point = Point.read(arguments);
  1424. return new Point(this.x + point.x, this.y + point.y);
  1425. },
  1426. subtract: function() {
  1427. var point = Point.read(arguments);
  1428. return new Point(this.x - point.x, this.y - point.y);
  1429. },
  1430. multiply: function() {
  1431. var point = Point.read(arguments);
  1432. return new Point(this.x * point.x, this.y * point.y);
  1433. },
  1434. divide: function() {
  1435. var point = Point.read(arguments);
  1436. return new Point(this.x / point.x, this.y / point.y);
  1437. },
  1438. modulo: function() {
  1439. var point = Point.read(arguments);
  1440. return new Point(this.x % point.x, this.y % point.y);
  1441. },
  1442. negate: function() {
  1443. return new Point(-this.x, -this.y);
  1444. },
  1445. isInside: function() {
  1446. return Rectangle.read(arguments).contains(this);
  1447. },
  1448. isClose: function() {
  1449. var args = arguments,
  1450. point = Point.read(args),
  1451. tolerance = Base.read(args);
  1452. return this.getDistance(point) <= tolerance;
  1453. },
  1454. isCollinear: function() {
  1455. var point = Point.read(arguments);
  1456. return Point.isCollinear(this.x, this.y, point.x, point.y);
  1457. },
  1458. isColinear: '#isCollinear',
  1459. isOrthogonal: function() {
  1460. var point = Point.read(arguments);
  1461. return Point.isOrthogonal(this.x, this.y, point.x, point.y);
  1462. },
  1463. isZero: function() {
  1464. var isZero = Numerical.isZero;
  1465. return isZero(this.x) && isZero(this.y);
  1466. },
  1467. isNaN: function() {
  1468. return isNaN(this.x) || isNaN(this.y);
  1469. },
  1470. isInQuadrant: function(q) {
  1471. return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0
  1472. && this.y * (q > 2 ? -1 : 1) >= 0;
  1473. },
  1474. dot: function() {
  1475. var point = Point.read(arguments);
  1476. return this.x * point.x + this.y * point.y;
  1477. },
  1478. cross: function() {
  1479. var point = Point.read(arguments);
  1480. return this.x * point.y - this.y * point.x;
  1481. },
  1482. project: function() {
  1483. var point = Point.read(arguments),
  1484. scale = point.isZero() ? 0 : this.dot(point) / point.dot(point);
  1485. return new Point(
  1486. point.x * scale,
  1487. point.y * scale
  1488. );
  1489. },
  1490. statics: {
  1491. min: function() {
  1492. var args = arguments,
  1493. point1 = Point.read(args),
  1494. point2 = Point.read(args);
  1495. return new Point(
  1496. Math.min(point1.x, point2.x),
  1497. Math.min(point1.y, point2.y)
  1498. );
  1499. },
  1500. max: function() {
  1501. var args = arguments,
  1502. point1 = Point.read(args),
  1503. point2 = Point.read(args);
  1504. return new Point(
  1505. Math.max(point1.x, point2.x),
  1506. Math.max(point1.y, point2.y)
  1507. );
  1508. },
  1509. random: function() {
  1510. return new Point(Math.random(), Math.random());
  1511. },
  1512. isCollinear: function(x1, y1, x2, y2) {
  1513. return Math.abs(x1 * y2 - y1 * x2)
  1514. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1515. * 1e-8;
  1516. },
  1517. isOrthogonal: function(x1, y1, x2, y2) {
  1518. return Math.abs(x1 * x2 + y1 * y2)
  1519. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1520. * 1e-8;
  1521. }
  1522. }
  1523. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1524. var op = Math[key];
  1525. this[key] = function() {
  1526. return new Point(op(this.x), op(this.y));
  1527. };
  1528. }, {}));
  1529. var LinkedPoint = Point.extend({
  1530. initialize: function Point(x, y, owner, setter) {
  1531. this._x = x;
  1532. this._y = y;
  1533. this._owner = owner;
  1534. this._setter = setter;
  1535. },
  1536. _set: function(x, y, _dontNotify) {
  1537. this._x = x;
  1538. this._y = y;
  1539. if (!_dontNotify)
  1540. this._owner[this._setter](this);
  1541. return this;
  1542. },
  1543. getX: function() {
  1544. return this._x;
  1545. },
  1546. setX: function(x) {
  1547. this._x = x;
  1548. this._owner[this._setter](this);
  1549. },
  1550. getY: function() {
  1551. return this._y;
  1552. },
  1553. setY: function(y) {
  1554. this._y = y;
  1555. this._owner[this._setter](this);
  1556. },
  1557. isSelected: function() {
  1558. return !!(this._owner._selection & this._getSelection());
  1559. },
  1560. setSelected: function(selected) {
  1561. this._owner._changeSelection(this._getSelection(), selected);
  1562. },
  1563. _getSelection: function() {
  1564. return this._setter === 'setPosition' ? 4 : 0;
  1565. }
  1566. });
  1567. var Size = Base.extend({
  1568. _class: 'Size',
  1569. _readIndex: true,
  1570. initialize: function Size(arg0, arg1) {
  1571. var type = typeof arg0,
  1572. reading = this.__read,
  1573. read = 0;
  1574. if (type === 'number') {
  1575. var hasHeight = typeof arg1 === 'number';
  1576. this._set(arg0, hasHeight ? arg1 : arg0);
  1577. if (reading)
  1578. read = hasHeight ? 2 : 1;
  1579. } else if (type === 'undefined' || arg0 === null) {
  1580. this._set(0, 0);
  1581. if (reading)
  1582. read = arg0 === null ? 1 : 0;
  1583. } else {
  1584. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1585. read = 1;
  1586. if (Array.isArray(obj)) {
  1587. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1588. } else if ('width' in obj) {
  1589. this._set(obj.width || 0, obj.height || 0);
  1590. } else if ('x' in obj) {
  1591. this._set(obj.x || 0, obj.y || 0);
  1592. } else {
  1593. this._set(0, 0);
  1594. read = 0;
  1595. }
  1596. }
  1597. if (reading)
  1598. this.__read = read;
  1599. return this;
  1600. },
  1601. set: '#initialize',
  1602. _set: function(width, height) {
  1603. this.width = width;
  1604. this.height = height;
  1605. return this;
  1606. },
  1607. equals: function(size) {
  1608. return size === this || size && (this.width === size.width
  1609. && this.height === size.height
  1610. || Array.isArray(size) && this.width === size[0]
  1611. && this.height === size[1]) || false;
  1612. },
  1613. clone: function() {
  1614. return new Size(this.width, this.height);
  1615. },
  1616. toString: function() {
  1617. var f = Formatter.instance;
  1618. return '{ width: ' + f.number(this.width)
  1619. + ', height: ' + f.number(this.height) + ' }';
  1620. },
  1621. _serialize: function(options) {
  1622. var f = options.formatter;
  1623. return [f.number(this.width),
  1624. f.number(this.height)];
  1625. },
  1626. add: function() {
  1627. var size = Size.read(arguments);
  1628. return new Size(this.width + size.width, this.height + size.height);
  1629. },
  1630. subtract: function() {
  1631. var size = Size.read(arguments);
  1632. return new Size(this.width - size.width, this.height - size.height);
  1633. },
  1634. multiply: function() {
  1635. var size = Size.read(arguments);
  1636. return new Size(this.width * size.width, this.height * size.height);
  1637. },
  1638. divide: function() {
  1639. var size = Size.read(arguments);
  1640. return new Size(this.width / size.width, this.height / size.height);
  1641. },
  1642. modulo: function() {
  1643. var size = Size.read(arguments);
  1644. return new Size(this.width % size.width, this.height % size.height);
  1645. },
  1646. negate: function() {
  1647. return new Size(-this.width, -this.height);
  1648. },
  1649. isZero: function() {
  1650. var isZero = Numerical.isZero;
  1651. return isZero(this.width) && isZero(this.height);
  1652. },
  1653. isNaN: function() {
  1654. return isNaN(this.width) || isNaN(this.height);
  1655. },
  1656. statics: {
  1657. min: function(size1, size2) {
  1658. return new Size(
  1659. Math.min(size1.width, size2.width),
  1660. Math.min(size1.height, size2.height));
  1661. },
  1662. max: function(size1, size2) {
  1663. return new Size(
  1664. Math.max(size1.width, size2.width),
  1665. Math.max(size1.height, size2.height));
  1666. },
  1667. random: function() {
  1668. return new Size(Math.random(), Math.random());
  1669. }
  1670. }
  1671. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1672. var op = Math[key];
  1673. this[key] = function() {
  1674. return new Size(op(this.width), op(this.height));
  1675. };
  1676. }, {}));
  1677. var LinkedSize = Size.extend({
  1678. initialize: function Size(width, height, owner, setter) {
  1679. this._width = width;
  1680. this._height = height;
  1681. this._owner = owner;
  1682. this._setter = setter;
  1683. },
  1684. _set: function(width, height, _dontNotify) {
  1685. this._width = width;
  1686. this._height = height;
  1687. if (!_dontNotify)
  1688. this._owner[this._setter](this);
  1689. return this;
  1690. },
  1691. getWidth: function() {
  1692. return this._width;
  1693. },
  1694. setWidth: function(width) {
  1695. this._width = width;
  1696. this._owner[this._setter](this);
  1697. },
  1698. getHeight: function() {
  1699. return this._height;
  1700. },
  1701. setHeight: function(height) {
  1702. this._height = height;
  1703. this._owner[this._setter](this);
  1704. }
  1705. });
  1706. var Rectangle = Base.extend({
  1707. _class: 'Rectangle',
  1708. _readIndex: true,
  1709. beans: true,
  1710. initialize: function Rectangle(arg0, arg1, arg2, arg3) {
  1711. var args = arguments,
  1712. type = typeof arg0,
  1713. read;
  1714. if (type === 'number') {
  1715. this._set(arg0, arg1, arg2, arg3);
  1716. read = 4;
  1717. } else if (type === 'undefined' || arg0 === null) {
  1718. this._set(0, 0, 0, 0);
  1719. read = arg0 === null ? 1 : 0;
  1720. } else if (args.length === 1) {
  1721. if (Array.isArray(arg0)) {
  1722. this._set.apply(this, arg0);
  1723. read = 1;
  1724. } else if (arg0.x !== undefined || arg0.width !== undefined) {
  1725. this._set(arg0.x || 0, arg0.y || 0,
  1726. arg0.width || 0, arg0.height || 0);
  1727. read = 1;
  1728. } else if (arg0.from === undefined && arg0.to === undefined) {
  1729. this._set(0, 0, 0, 0);
  1730. if (Base.readSupported(args, this)) {
  1731. read = 1;
  1732. }
  1733. }
  1734. }
  1735. if (read === undefined) {
  1736. var frm = Point.readNamed(args, 'from'),
  1737. next = Base.peek(args),
  1738. x = frm.x,
  1739. y = frm.y,
  1740. width,
  1741. height;
  1742. if (next && next.x !== undefined || Base.hasNamed(args, 'to')) {
  1743. var to = Point.readNamed(args, 'to');
  1744. width = to.x - x;
  1745. height = to.y - y;
  1746. if (width < 0) {
  1747. x = to.x;
  1748. width = -width;
  1749. }
  1750. if (height < 0) {
  1751. y = to.y;
  1752. height = -height;
  1753. }
  1754. } else {
  1755. var size = Size.read(args);
  1756. width = size.width;
  1757. height = size.height;
  1758. }
  1759. this._set(x, y, width, height);
  1760. read = args.__index;
  1761. }
  1762. var filtered = args.__filtered;
  1763. if (filtered)
  1764. this.__filtered = filtered;
  1765. if (this.__read)
  1766. this.__read = read;
  1767. return this;
  1768. },
  1769. set: '#initialize',
  1770. _set: function(x, y, width, height) {
  1771. this.x = x;
  1772. this.y = y;
  1773. this.width = width;
  1774. this.height = height;
  1775. return this;
  1776. },
  1777. clone: function() {
  1778. return new Rectangle(this.x, this.y, this.width, this.height);
  1779. },
  1780. equals: function(rect) {
  1781. var rt = Base.isPlainValue(rect)
  1782. ? Rectangle.read(arguments)
  1783. : rect;
  1784. return rt === this
  1785. || rt && this.x === rt.x && this.y === rt.y
  1786. && this.width === rt.width && this.height === rt.height
  1787. || false;
  1788. },
  1789. toString: function() {
  1790. var f = Formatter.instance;
  1791. return '{ x: ' + f.number(this.x)
  1792. + ', y: ' + f.number(this.y)
  1793. + ', width: ' + f.number(this.width)
  1794. + ', height: ' + f.number(this.height)
  1795. + ' }';
  1796. },
  1797. _serialize: function(options) {
  1798. var f = options.formatter;
  1799. return [f.number(this.x),
  1800. f.number(this.y),
  1801. f.number(this.width),
  1802. f.number(this.height)];
  1803. },
  1804. getPoint: function(_dontLink) {
  1805. var ctor = _dontLink ? Point : LinkedPoint;
  1806. return new ctor(this.x, this.y, this, 'setPoint');
  1807. },
  1808. setPoint: function() {
  1809. var point = Point.read(arguments);
  1810. this.x = point.x;
  1811. this.y = point.y;
  1812. },
  1813. getSize: function(_dontLink) {
  1814. var ctor = _dontLink ? Size : LinkedSize;
  1815. return new ctor(this.width, this.height, this, 'setSize');
  1816. },
  1817. _fw: 1,
  1818. _fh: 1,
  1819. setSize: function() {
  1820. var size = Size.read(arguments),
  1821. sx = this._sx,
  1822. sy = this._sy,
  1823. w = size.width,
  1824. h = size.height;
  1825. if (sx) {
  1826. this.x += (this.width - w) * sx;
  1827. }
  1828. if (sy) {
  1829. this.y += (this.height - h) * sy;
  1830. }
  1831. this.width = w;
  1832. this.height = h;
  1833. this._fw = this._fh = 1;
  1834. },
  1835. getLeft: function() {
  1836. return this.x;
  1837. },
  1838. setLeft: function(left) {
  1839. if (!this._fw) {
  1840. var amount = left - this.x;
  1841. this.width -= this._sx === 0.5 ? amount * 2 : amount;
  1842. }
  1843. this.x = left;
  1844. this._sx = this._fw = 0;
  1845. },
  1846. getTop: function() {
  1847. return this.y;
  1848. },
  1849. setTop: function(top) {
  1850. if (!this._fh) {
  1851. var amount = top - this.y;
  1852. this.height -= this._sy === 0.5 ? amount * 2 : amount;
  1853. }
  1854. this.y = top;
  1855. this._sy = this._fh = 0;
  1856. },
  1857. getRight: function() {
  1858. return this.x + this.width;
  1859. },
  1860. setRight: function(right) {
  1861. if (!this._fw) {
  1862. var amount = right - this.x;
  1863. this.width = this._sx === 0.5 ? amount * 2 : amount;
  1864. }
  1865. this.x = right - this.width;
  1866. this._sx = 1;
  1867. this._fw = 0;
  1868. },
  1869. getBottom: function() {
  1870. return this.y + this.height;
  1871. },
  1872. setBottom: function(bottom) {
  1873. if (!this._fh) {
  1874. var amount = bottom - this.y;
  1875. this.height = this._sy === 0.5 ? amount * 2 : amount;
  1876. }
  1877. this.y = bottom - this.height;
  1878. this._sy = 1;
  1879. this._fh = 0;
  1880. },
  1881. getCenterX: function() {
  1882. return this.x + this.width / 2;
  1883. },
  1884. setCenterX: function(x) {
  1885. if (this._fw || this._sx === 0.5) {
  1886. this.x = x - this.width / 2;
  1887. } else {
  1888. if (this._sx) {
  1889. this.x += (x - this.x) * 2 * this._sx;
  1890. }
  1891. this.width = (x - this.x) * 2;
  1892. }
  1893. this._sx = 0.5;
  1894. this._fw = 0;
  1895. },
  1896. getCenterY: function() {
  1897. return this.y + this.height / 2;
  1898. },
  1899. setCenterY: function(y) {
  1900. if (this._fh || this._sy === 0.5) {
  1901. this.y = y - this.height / 2;
  1902. } else {
  1903. if (this._sy) {
  1904. this.y += (y - this.y) * 2 * this._sy;
  1905. }
  1906. this.height = (y - this.y) * 2;
  1907. }
  1908. this._sy = 0.5;
  1909. this._fh = 0;
  1910. },
  1911. getCenter: function(_dontLink) {
  1912. var ctor = _dontLink ? Point : LinkedPoint;
  1913. return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');
  1914. },
  1915. setCenter: function() {
  1916. var point = Point.read(arguments);
  1917. this.setCenterX(point.x);
  1918. this.setCenterY(point.y);
  1919. return this;
  1920. },
  1921. getArea: function() {
  1922. return this.width * this.height;
  1923. },
  1924. isEmpty: function() {
  1925. return this.width === 0 || this.height === 0;
  1926. },
  1927. contains: function(arg) {
  1928. return arg && arg.width !== undefined
  1929. || (Array.isArray(arg) ? arg : arguments).length === 4
  1930. ? this._containsRectangle(Rectangle.read(arguments))
  1931. : this._containsPoint(Point.read(arguments));
  1932. },
  1933. _containsPoint: function(point) {
  1934. var x = point.x,
  1935. y = point.y;
  1936. return x >= this.x && y >= this.y
  1937. && x <= this.x + this.width
  1938. && y <= this.y + this.height;
  1939. },
  1940. _containsRectangle: function(rect) {
  1941. var x = rect.x,
  1942. y = rect.y;
  1943. return x >= this.x && y >= this.y
  1944. && x + rect.width <= this.x + this.width
  1945. && y + rect.height <= this.y + this.height;
  1946. },
  1947. intersects: function() {
  1948. var rect = Rectangle.read(arguments),
  1949. epsilon = Base.read(arguments) || 0;
  1950. return rect.x + rect.width > this.x - epsilon
  1951. && rect.y + rect.height > this.y - epsilon
  1952. && rect.x < this.x + this.width + epsilon
  1953. && rect.y < this.y + this.height + epsilon;
  1954. },
  1955. intersect: function() {
  1956. var rect = Rectangle.read(arguments),
  1957. x1 = Math.max(this.x, rect.x),
  1958. y1 = Math.max(this.y, rect.y),
  1959. x2 = Math.min(this.x + this.width, rect.x + rect.width),
  1960. y2 = Math.min(this.y + this.height, rect.y + rect.height);
  1961. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1962. },
  1963. unite: function() {
  1964. var rect = Rectangle.read(arguments),
  1965. x1 = Math.min(this.x, rect.x),
  1966. y1 = Math.min(this.y, rect.y),
  1967. x2 = Math.max(this.x + this.width, rect.x + rect.width),
  1968. y2 = Math.max(this.y + this.height, rect.y + rect.height);
  1969. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1970. },
  1971. include: function() {
  1972. var point = Point.read(arguments);
  1973. var x1 = Math.min(this.x, point.x),
  1974. y1 = Math.min(this.y, point.y),
  1975. x2 = Math.max(this.x + this.width, point.x),
  1976. y2 = Math.max(this.y + this.height, point.y);
  1977. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1978. },
  1979. expand: function() {
  1980. var amount = Size.read(arguments),
  1981. hor = amount.width,
  1982. ver = amount.height;
  1983. return new Rectangle(this.x - hor / 2, this.y - ver / 2,
  1984. this.width + hor, this.height + ver);
  1985. },
  1986. scale: function(hor, ver) {
  1987. return this.expand(this.width * hor - this.width,
  1988. this.height * (ver === undefined ? hor : ver) - this.height);
  1989. }
  1990. }, Base.each([
  1991. ['Top', 'Left'], ['Top', 'Right'],
  1992. ['Bottom', 'Left'], ['Bottom', 'Right'],
  1993. ['Left', 'Center'], ['Top', 'Center'],
  1994. ['Right', 'Center'], ['Bottom', 'Center']
  1995. ],
  1996. function(parts, index) {
  1997. var part = parts.join(''),
  1998. xFirst = /^[RL]/.test(part);
  1999. if (index >= 4)
  2000. parts[1] += xFirst ? 'Y' : 'X';
  2001. var x = parts[xFirst ? 0 : 1],
  2002. y = parts[xFirst ? 1 : 0],
  2003. getX = 'get' + x,
  2004. getY = 'get' + y,
  2005. setX = 'set' + x,
  2006. setY = 'set' + y,
  2007. get = 'get' + part,
  2008. set = 'set' + part;
  2009. this[get] = function(_dontLink) {
  2010. var ctor = _dontLink ? Point : LinkedPoint;
  2011. return new ctor(this[getX](), this[getY](), this, set);
  2012. };
  2013. this[set] = function() {
  2014. var point = Point.read(arguments);
  2015. this[setX](point.x);
  2016. this[setY](point.y);
  2017. };
  2018. }, {
  2019. beans: true
  2020. }
  2021. ));
  2022. var LinkedRectangle = Rectangle.extend({
  2023. initialize: function Rectangle(x, y, width, height, owner, setter) {
  2024. this._set(x, y, width, height, true);
  2025. this._owner = owner;
  2026. this._setter = setter;
  2027. },
  2028. _set: function(x, y, width, height, _dontNotify) {
  2029. this._x = x;
  2030. this._y = y;
  2031. this._width = width;
  2032. this._height = height;
  2033. if (!_dontNotify)
  2034. this._owner[this._setter](this);
  2035. return this;
  2036. }
  2037. },
  2038. new function() {
  2039. var proto = Rectangle.prototype;
  2040. return Base.each(['x', 'y', 'width', 'height'], function(key) {
  2041. var part = Base.capitalize(key),
  2042. internal = '_' + key;
  2043. this['get' + part] = function() {
  2044. return this[internal];
  2045. };
  2046. this['set' + part] = function(value) {
  2047. this[internal] = value;
  2048. if (!this._dontNotify)
  2049. this._owner[this._setter](this);
  2050. };
  2051. }, Base.each(['Point', 'Size', 'Center',
  2052. 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
  2053. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  2054. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
  2055. function(key) {
  2056. var name = 'set' + key;
  2057. this[name] = function() {
  2058. this._dontNotify = true;
  2059. proto[name].apply(this, arguments);
  2060. this._dontNotify = false;
  2061. this._owner[this._setter](this);
  2062. };
  2063. }, {
  2064. isSelected: function() {
  2065. return !!(this._owner._selection & 2);
  2066. },
  2067. setSelected: function(selected) {
  2068. var owner = this._owner;
  2069. if (owner._changeSelection) {
  2070. owner._changeSelection(2, selected);
  2071. }
  2072. }
  2073. })
  2074. );
  2075. });
  2076. var Matrix = Base.extend({
  2077. _class: 'Matrix',
  2078. initialize: function Matrix(arg, _dontNotify) {
  2079. var args = arguments,
  2080. count = args.length,
  2081. ok = true;
  2082. if (count >= 6) {
  2083. this._set.apply(this, args);
  2084. } else if (count === 1 || count === 2) {
  2085. if (arg instanceof Matrix) {
  2086. this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty,
  2087. _dontNotify);
  2088. } else if (Array.isArray(arg)) {
  2089. this._set.apply(this,
  2090. _dontNotify ? arg.concat([_dontNotify]) : arg);
  2091. } else {
  2092. ok = false;
  2093. }
  2094. } else if (!count) {
  2095. this.reset();
  2096. } else {
  2097. ok = false;
  2098. }
  2099. if (!ok) {
  2100. throw new Error('Unsupported matrix parameters');
  2101. }
  2102. return this;
  2103. },
  2104. set: '#initialize',
  2105. _set: function(a, b, c, d, tx, ty, _dontNotify) {
  2106. this._a = a;
  2107. this._b = b;
  2108. this._c = c;
  2109. this._d = d;
  2110. this._tx = tx;
  2111. this._ty = ty;
  2112. if (!_dontNotify)
  2113. this._changed();
  2114. return this;
  2115. },
  2116. _serialize: function(options, dictionary) {
  2117. return Base.serialize(this.getValues(), options, true, dictionary);
  2118. },
  2119. _changed: function() {
  2120. var owner = this._owner;
  2121. if (owner) {
  2122. if (owner._applyMatrix) {
  2123. owner.transform(null, true);
  2124. } else {
  2125. owner._changed(25);
  2126. }
  2127. }
  2128. },
  2129. clone: function() {
  2130. return new Matrix(this._a, this._b, this._c, this._d,
  2131. this._tx, this._ty);
  2132. },
  2133. equals: function(mx) {
  2134. return mx === this || mx && this._a === mx._a && this._b === mx._b
  2135. && this._c === mx._c && this._d === mx._d
  2136. && this._tx === mx._tx && this._ty === mx._ty;
  2137. },
  2138. toString: function() {
  2139. var f = Formatter.instance;
  2140. return '[[' + [f.number(this._a), f.number(this._c),
  2141. f.number(this._tx)].join(', ') + '], ['
  2142. + [f.number(this._b), f.number(this._d),
  2143. f.number(this._ty)].join(', ') + ']]';
  2144. },
  2145. reset: function(_dontNotify) {
  2146. this._a = this._d = 1;
  2147. this._b = this._c = this._tx = this._ty = 0;
  2148. if (!_dontNotify)
  2149. this._changed();
  2150. return this;
  2151. },
  2152. apply: function(recursively, _setApplyMatrix) {
  2153. var owner = this._owner;
  2154. if (owner) {
  2155. owner.transform(null, Base.pick(recursively, true), _setApplyMatrix);
  2156. return this.isIdentity();
  2157. }
  2158. return false;
  2159. },
  2160. translate: function() {
  2161. var point = Point.read(arguments),
  2162. x = point.x,
  2163. y = point.y;
  2164. this._tx += x * this._a + y * this._c;
  2165. this._ty += x * this._b + y * this._d;
  2166. this._changed();
  2167. return this;
  2168. },
  2169. scale: function() {
  2170. var args = arguments,
  2171. scale = Point.read(args),
  2172. center = Point.read(args, 0, { readNull: true });
  2173. if (center)
  2174. this.translate(center);
  2175. this._a *= scale.x;
  2176. this._b *= scale.x;
  2177. this._c *= scale.y;
  2178. this._d *= scale.y;
  2179. if (center)
  2180. this.translate(center.negate());
  2181. this._changed();
  2182. return this;
  2183. },
  2184. rotate: function(angle ) {
  2185. angle *= Math.PI / 180;
  2186. var center = Point.read(arguments, 1),
  2187. x = center.x,
  2188. y = center.y,
  2189. cos = Math.cos(angle),
  2190. sin = Math.sin(angle),
  2191. tx = x - x * cos + y * sin,
  2192. ty = y - x * sin - y * cos,
  2193. a = this._a,
  2194. b = this._b,
  2195. c = this._c,
  2196. d = this._d;
  2197. this._a = cos * a + sin * c;
  2198. this._b = cos * b + sin * d;
  2199. this._c = -sin * a + cos * c;
  2200. this._d = -sin * b + cos * d;
  2201. this._tx += tx * a + ty * c;
  2202. this._ty += tx * b + ty * d;
  2203. this._changed();
  2204. return this;
  2205. },
  2206. shear: function() {
  2207. var args = arguments,
  2208. shear = Point.read(args),
  2209. center = Point.read(args, 0, { readNull: true });
  2210. if (center)
  2211. this.translate(center);
  2212. var a = this._a,
  2213. b = this._b;
  2214. this._a += shear.y * this._c;
  2215. this._b += shear.y * this._d;
  2216. this._c += shear.x * a;
  2217. this._d += shear.x * b;
  2218. if (center)
  2219. this.translate(center.negate());
  2220. this._changed();
  2221. return this;
  2222. },
  2223. skew: function() {
  2224. var args = arguments,
  2225. skew = Point.read(args),
  2226. center = Point.read(args, 0, { readNull: true }),
  2227. toRadians = Math.PI / 180,
  2228. shear = new Point(Math.tan(skew.x * toRadians),
  2229. Math.tan(skew.y * toRadians));
  2230. return this.shear(shear, center);
  2231. },
  2232. append: function(mx, _dontNotify) {
  2233. if (mx) {
  2234. var a1 = this._a,
  2235. b1 = this._b,
  2236. c1 = this._c,
  2237. d1 = this._d,
  2238. a2 = mx._a,
  2239. b2 = mx._c,
  2240. c2 = mx._b,
  2241. d2 = mx._d,
  2242. tx2 = mx._tx,
  2243. ty2 = mx._ty;
  2244. this._a = a2 * a1 + c2 * c1;
  2245. this._c = b2 * a1 + d2 * c1;
  2246. this._b = a2 * b1 + c2 * d1;
  2247. this._d = b2 * b1 + d2 * d1;
  2248. this._tx += tx2 * a1 + ty2 * c1;
  2249. this._ty += tx2 * b1 + ty2 * d1;
  2250. if (!_dontNotify)
  2251. this._changed();
  2252. }
  2253. return this;
  2254. },
  2255. prepend: function(mx, _dontNotify) {
  2256. if (mx) {
  2257. var a1 = this._a,
  2258. b1 = this._b,
  2259. c1 = this._c,
  2260. d1 = this._d,
  2261. tx1 = this._tx,
  2262. ty1 = this._ty,
  2263. a2 = mx._a,
  2264. b2 = mx._c,
  2265. c2 = mx._b,
  2266. d2 = mx._d,
  2267. tx2 = mx._tx,
  2268. ty2 = mx._ty;
  2269. this._a = a2 * a1 + b2 * b1;
  2270. this._c = a2 * c1 + b2 * d1;
  2271. this._b = c2 * a1 + d2 * b1;
  2272. this._d = c2 * c1 + d2 * d1;
  2273. this._tx = a2 * tx1 + b2 * ty1 + tx2;
  2274. this._ty = c2 * tx1 + d2 * ty1 + ty2;
  2275. if (!_dontNotify)
  2276. this._changed();
  2277. }
  2278. return this;
  2279. },
  2280. appended: function(mx) {
  2281. return this.clone().append(mx);
  2282. },
  2283. prepended: function(mx) {
  2284. return this.clone().prepend(mx);
  2285. },
  2286. invert: function() {
  2287. var a = this._a,
  2288. b = this._b,
  2289. c = this._c,
  2290. d = this._d,
  2291. tx = this._tx,
  2292. ty = this._ty,
  2293. det = a * d - b * c,
  2294. res = null;
  2295. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2296. this._a = d / det;
  2297. this._b = -b / det;
  2298. this._c = -c / det;
  2299. this._d = a / det;
  2300. this._tx = (c * ty - d * tx) / det;
  2301. this._ty = (b * tx - a * ty) / det;
  2302. res = this;
  2303. }
  2304. return res;
  2305. },
  2306. inverted: function() {
  2307. return this.clone().invert();
  2308. },
  2309. concatenate: '#append',
  2310. preConcatenate: '#prepend',
  2311. chain: '#appended',
  2312. _shiftless: function() {
  2313. return new Matrix(this._a, this._b, this._c, this._d, 0, 0);
  2314. },
  2315. _orNullIfIdentity: function() {
  2316. return this.isIdentity() ? null : this;
  2317. },
  2318. isIdentity: function() {
  2319. return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1
  2320. && this._tx === 0 && this._ty === 0;
  2321. },
  2322. isInvertible: function() {
  2323. var det = this._a * this._d - this._c * this._b;
  2324. return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty);
  2325. },
  2326. isSingular: function() {
  2327. return !this.isInvertible();
  2328. },
  2329. transform: function( src, dst, count) {
  2330. return arguments.length < 3
  2331. ? this._transformPoint(Point.read(arguments))
  2332. : this._transformCoordinates(src, dst, count);
  2333. },
  2334. _transformPoint: function(point, dest, _dontNotify) {
  2335. var x = point.x,
  2336. y = point.y;
  2337. if (!dest)
  2338. dest = new Point();
  2339. return dest._set(
  2340. x * this._a + y * this._c + this._tx,
  2341. x * this._b + y * this._d + this._ty,
  2342. _dontNotify);
  2343. },
  2344. _transformCoordinates: function(src, dst, count) {
  2345. for (var i = 0, max = 2 * count; i < max; i += 2) {
  2346. var x = src[i],
  2347. y = src[i + 1];
  2348. dst[i] = x * this._a + y * this._c + this._tx;
  2349. dst[i + 1] = x * this._b + y * this._d + this._ty;
  2350. }
  2351. return dst;
  2352. },
  2353. _transformCorners: function(rect) {
  2354. var x1 = rect.x,
  2355. y1 = rect.y,
  2356. x2 = x1 + rect.width,
  2357. y2 = y1 + rect.height,
  2358. coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
  2359. return this._transformCoordinates(coords, coords, 4);
  2360. },
  2361. _transformBounds: function(bounds, dest, _dontNotify) {
  2362. var coords = this._transformCorners(bounds),
  2363. min = coords.slice(0, 2),
  2364. max = min.slice();
  2365. for (var i = 2; i < 8; i++) {
  2366. var val = coords[i],
  2367. j = i & 1;
  2368. if (val < min[j]) {
  2369. min[j] = val;
  2370. } else if (val > max[j]) {
  2371. max[j] = val;
  2372. }
  2373. }
  2374. if (!dest)
  2375. dest = new Rectangle();
  2376. return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1],
  2377. _dontNotify);
  2378. },
  2379. inverseTransform: function() {
  2380. return this._inverseTransform(Point.read(arguments));
  2381. },
  2382. _inverseTransform: function(point, dest, _dontNotify) {
  2383. var a = this._a,
  2384. b = this._b,
  2385. c = this._c,
  2386. d = this._d,
  2387. tx = this._tx,
  2388. ty = this._ty,
  2389. det = a * d - b * c,
  2390. res = null;
  2391. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2392. var x = point.x - this._tx,
  2393. y = point.y - this._ty;
  2394. if (!dest)
  2395. dest = new Point();
  2396. res = dest._set(
  2397. (x * d - y * c) / det,
  2398. (y * a - x * b) / det,
  2399. _dontNotify);
  2400. }
  2401. return res;
  2402. },
  2403. decompose: function() {
  2404. var a = this._a,
  2405. b = this._b,
  2406. c = this._c,
  2407. d = this._d,
  2408. det = a * d - b * c,
  2409. sqrt = Math.sqrt,
  2410. atan2 = Math.atan2,
  2411. degrees = 180 / Math.PI,
  2412. rotate,
  2413. scale,
  2414. skew;
  2415. if (a !== 0 || b !== 0) {
  2416. var r = sqrt(a * a + b * b);
  2417. rotate = Math.acos(a / r) * (b > 0 ? 1 : -1);
  2418. scale = [r, det / r];
  2419. skew = [atan2(a * c + b * d, r * r), 0];
  2420. } else if (c !== 0 || d !== 0) {
  2421. var s = sqrt(c * c + d * d);
  2422. rotate = Math.asin(c / s) * (d > 0 ? 1 : -1);
  2423. scale = [det / s, s];
  2424. skew = [0, atan2(a * c + b * d, s * s)];
  2425. } else {
  2426. rotate = 0;
  2427. skew = scale = [0, 0];
  2428. }
  2429. return {
  2430. translation: this.getTranslation(),
  2431. rotation: rotate * degrees,
  2432. scaling: new Point(scale),
  2433. skewing: new Point(skew[0] * degrees, skew[1] * degrees)
  2434. };
  2435. },
  2436. getValues: function() {
  2437. return [ this._a, this._b, this._c, this._d, this._tx, this._ty ];
  2438. },
  2439. getTranslation: function() {
  2440. return new Point(this._tx, this._ty);
  2441. },
  2442. getScaling: function() {
  2443. return this.decompose().scaling;
  2444. },
  2445. getRotation: function() {
  2446. return this.decompose().rotation;
  2447. },
  2448. applyToContext: function(ctx) {
  2449. if (!this.isIdentity()) {
  2450. ctx.transform(this._a, this._b, this._c, this._d,
  2451. this._tx, this._ty);
  2452. }
  2453. }
  2454. }, Base.each(['a', 'b', 'c', 'd', 'tx', 'ty'], function(key) {
  2455. var part = Base.capitalize(key),
  2456. prop = '_' + key;
  2457. this['get' + part] = function() {
  2458. return this[prop];
  2459. };
  2460. this['set' + part] = function(value) {
  2461. this[prop] = value;
  2462. this._changed();
  2463. };
  2464. }, {}));
  2465. var Line = Base.extend({
  2466. _class: 'Line',
  2467. initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
  2468. var asVector = false;
  2469. if (arguments.length >= 4) {
  2470. this._px = arg0;
  2471. this._py = arg1;
  2472. this._vx = arg2;
  2473. this._vy = arg3;
  2474. asVector = arg4;
  2475. } else {
  2476. this._px = arg0.x;
  2477. this._py = arg0.y;
  2478. this._vx = arg1.x;
  2479. this._vy = arg1.y;
  2480. asVector = arg2;
  2481. }
  2482. if (!asVector) {
  2483. this._vx -= this._px;
  2484. this._vy -= this._py;
  2485. }
  2486. },
  2487. getPoint: function() {
  2488. return new Point(this._px, this._py);
  2489. },
  2490. getVector: function() {
  2491. return new Point(this._vx, this._vy);
  2492. },
  2493. getLength: function() {
  2494. return this.getVector().getLength();
  2495. },
  2496. intersect: function(line, isInfinite) {
  2497. return Line.intersect(
  2498. this._px, this._py, this._vx, this._vy,
  2499. line._px, line._py, line._vx, line._vy,
  2500. true, isInfinite);
  2501. },
  2502. getSide: function(point, isInfinite) {
  2503. return Line.getSide(
  2504. this._px, this._py, this._vx, this._vy,
  2505. point.x, point.y, true, isInfinite);
  2506. },
  2507. getDistance: function(point) {
  2508. return Math.abs(this.getSignedDistance(point));
  2509. },
  2510. getSignedDistance: function(point) {
  2511. return Line.getSignedDistance(this._px, this._py, this._vx, this._vy,
  2512. point.x, point.y, true);
  2513. },
  2514. isCollinear: function(line) {
  2515. return Point.isCollinear(this._vx, this._vy, line._vx, line._vy);
  2516. },
  2517. isOrthogonal: function(line) {
  2518. return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy);
  2519. },
  2520. statics: {
  2521. intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector,
  2522. isInfinite) {
  2523. if (!asVector) {
  2524. v1x -= p1x;
  2525. v1y -= p1y;
  2526. v2x -= p2x;
  2527. v2y -= p2y;
  2528. }
  2529. var cross = v1x * v2y - v1y * v2x;
  2530. if (!Numerical.isMachineZero(cross)) {
  2531. var dx = p1x - p2x,
  2532. dy = p1y - p2y,
  2533. u1 = (v2x * dy - v2y * dx) / cross,
  2534. u2 = (v1x * dy - v1y * dx) / cross,
  2535. epsilon = 1e-12,
  2536. uMin = -epsilon,
  2537. uMax = 1 + epsilon;
  2538. if (isInfinite
  2539. || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) {
  2540. if (!isInfinite) {
  2541. u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1;
  2542. }
  2543. return new Point(
  2544. p1x + u1 * v1x,
  2545. p1y + u1 * v1y);
  2546. }
  2547. }
  2548. },
  2549. getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) {
  2550. if (!asVector) {
  2551. vx -= px;
  2552. vy -= py;
  2553. }
  2554. var v2x = x - px,
  2555. v2y = y - py,
  2556. ccw = v2x * vy - v2y * vx;
  2557. if (!isInfinite && Numerical.isMachineZero(ccw)) {
  2558. ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy);
  2559. if (ccw >= 0 && ccw <= 1)
  2560. ccw = 0;
  2561. }
  2562. return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
  2563. },
  2564. getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
  2565. if (!asVector) {
  2566. vx -= px;
  2567. vy -= py;
  2568. }
  2569. return vx === 0 ? (vy > 0 ? x - px : px - x)
  2570. : vy === 0 ? (vx < 0 ? y - py : py - y)
  2571. : ((x - px) * vy - (y - py) * vx) / (
  2572. vy > vx
  2573. ? vy * Math.sqrt(1 + (vx * vx) / (vy * vy))
  2574. : vx * Math.sqrt(1 + (vy * vy) / (vx * vx))
  2575. );
  2576. },
  2577. getDistance: function(px, py, vx, vy, x, y, asVector) {
  2578. return Math.abs(
  2579. Line.getSignedDistance(px, py, vx, vy, x, y, asVector));
  2580. }
  2581. }
  2582. });
  2583. var Project = PaperScopeItem.extend({
  2584. _class: 'Project',
  2585. _list: 'projects',
  2586. _reference: 'project',
  2587. _compactSerialize: true,
  2588. initialize: function Project(element) {
  2589. PaperScopeItem.call(this, true);
  2590. this._children = [];
  2591. this._namedChildren = {};
  2592. this._activeLayer = null;
  2593. this._currentStyle = new Style(null, null, this);
  2594. this._view = View.create(this,
  2595. element || CanvasProvider.getCanvas(1, 1));
  2596. this._selectionItems = {};
  2597. this._selectionCount = 0;
  2598. this._updateVersion = 0;
  2599. },
  2600. _serialize: function(options, dictionary) {
  2601. return Base.serialize(this._children, options, true, dictionary);
  2602. },
  2603. _changed: function(flags, item) {
  2604. if (flags & 1) {
  2605. var view = this._view;
  2606. if (view) {
  2607. view._needsUpdate = true;
  2608. if (!view._requested && view._autoUpdate)
  2609. view.requestUpdate();
  2610. }
  2611. }
  2612. var changes = this._changes;
  2613. if (changes && item) {
  2614. var changesById = this._changesById,
  2615. id = item._id,
  2616. entry = changesById[id];
  2617. if (entry) {
  2618. entry.flags |= flags;
  2619. } else {
  2620. changes.push(changesById[id] = { item: item, flags: flags });
  2621. }
  2622. }
  2623. },
  2624. clear: function() {
  2625. var children = this._children;
  2626. for (var i = children.length - 1; i >= 0; i--)
  2627. children[i].remove();
  2628. },
  2629. isEmpty: function() {
  2630. return !this._children.length;
  2631. },
  2632. remove: function remove() {
  2633. if (!remove.base.call(this))
  2634. return false;
  2635. if (this._view)
  2636. this._view.remove();
  2637. return true;
  2638. },
  2639. getView: function() {
  2640. return this._view;
  2641. },
  2642. getCurrentStyle: function() {
  2643. return this._currentStyle;
  2644. },
  2645. setCurrentStyle: function(style) {
  2646. this._currentStyle.set(style);
  2647. },
  2648. getIndex: function() {
  2649. return this._index;
  2650. },
  2651. getOptions: function() {
  2652. return this._scope.settings;
  2653. },
  2654. getLayers: function() {
  2655. return this._children;
  2656. },
  2657. getActiveLayer: function() {
  2658. return this._activeLayer || new Layer({ project: this, insert: true });
  2659. },
  2660. getSymbolDefinitions: function() {
  2661. var definitions = [],
  2662. ids = {};
  2663. this.getItems({
  2664. class: SymbolItem,
  2665. match: function(item) {
  2666. var definition = item._definition,
  2667. id = definition._id;
  2668. if (!ids[id]) {
  2669. ids[id] = true;
  2670. definitions.push(definition);
  2671. }
  2672. return false;
  2673. }
  2674. });
  2675. return definitions;
  2676. },
  2677. getSymbols: 'getSymbolDefinitions',
  2678. getSelectedItems: function() {
  2679. var selectionItems = this._selectionItems,
  2680. items = [];
  2681. for (var id in selectionItems) {
  2682. var item = selectionItems[id],
  2683. selection = item._selection;
  2684. if ((selection & 1) && item.isInserted()) {
  2685. items.push(item);
  2686. } else if (!selection) {
  2687. this._updateSelection(item);
  2688. }
  2689. }
  2690. return items;
  2691. },
  2692. _updateSelection: function(item) {
  2693. var id = item._id,
  2694. selectionItems = this._selectionItems;
  2695. if (item._selection) {
  2696. if (selectionItems[id] !== item) {
  2697. this._selectionCount++;
  2698. selectionItems[id] = item;
  2699. }
  2700. } else if (selectionItems[id] === item) {
  2701. this._selectionCount--;
  2702. delete selectionItems[id];
  2703. }
  2704. },
  2705. selectAll: function() {
  2706. var children = this._children;
  2707. for (var i = 0, l = children.length; i < l; i++)
  2708. children[i].setFullySelected(true);
  2709. },
  2710. deselectAll: function() {
  2711. var selectionItems = this._selectionItems;
  2712. for (var i in selectionItems)
  2713. selectionItems[i].setFullySelected(false);
  2714. },
  2715. addLayer: function(layer) {
  2716. return this.insertLayer(undefined, layer);
  2717. },
  2718. insertLayer: function(index, layer) {
  2719. if (layer instanceof Layer) {
  2720. layer._remove(false, true);
  2721. Base.splice(this._children, [layer], index, 0);
  2722. layer._setProject(this, true);
  2723. var name = layer._name;
  2724. if (name)
  2725. layer.setName(name);
  2726. if (this._changes)
  2727. layer._changed(5);
  2728. if (!this._activeLayer)
  2729. this._activeLayer = layer;
  2730. } else {
  2731. layer = null;
  2732. }
  2733. return layer;
  2734. },
  2735. _insertItem: function(index, item, _created) {
  2736. item = this.insertLayer(index, item)
  2737. || (this._activeLayer || this._insertItem(undefined,
  2738. new Layer(Item.NO_INSERT), true))
  2739. .insertChild(index, item);
  2740. if (_created && item.activate)
  2741. item.activate();
  2742. return item;
  2743. },
  2744. getItems: function(options) {
  2745. return Item._getItems(this, options);
  2746. },
  2747. getItem: function(options) {
  2748. return Item._getItems(this, options, null, null, true)[0] || null;
  2749. },
  2750. importJSON: function(json) {
  2751. this.activate();
  2752. var layer = this._activeLayer;
  2753. return Base.importJSON(json, layer && layer.isEmpty() && layer);
  2754. },
  2755. removeOn: function(type) {
  2756. var sets = this._removeSets;
  2757. if (sets) {
  2758. if (type === 'mouseup')
  2759. sets.mousedrag = null;
  2760. var set = sets[type];
  2761. if (set) {
  2762. for (var id in set) {
  2763. var item = set[id];
  2764. for (var key in sets) {
  2765. var other = sets[key];
  2766. if (other && other != set)
  2767. delete other[item._id];
  2768. }
  2769. item.remove();
  2770. }
  2771. sets[type] = null;
  2772. }
  2773. }
  2774. },
  2775. draw: function(ctx, matrix, pixelRatio) {
  2776. this._updateVersion++;
  2777. ctx.save();
  2778. matrix.applyToContext(ctx);
  2779. var children = this._children,
  2780. param = new Base({
  2781. offset: new Point(0, 0),
  2782. pixelRatio: pixelRatio,
  2783. viewMatrix: matrix.isIdentity() ? null : matrix,
  2784. matrices: [new Matrix()],
  2785. updateMatrix: true
  2786. });
  2787. for (var i = 0, l = children.length; i < l; i++) {
  2788. children[i].draw(ctx, param);
  2789. }
  2790. ctx.restore();
  2791. if (this._selectionCount > 0) {
  2792. ctx.save();
  2793. ctx.strokeWidth = 1;
  2794. var items = this._selectionItems,
  2795. size = this._scope.settings.handleSize,
  2796. version = this._updateVersion;
  2797. for (var id in items) {
  2798. items[id]._drawSelection(ctx, matrix, size, items, version);
  2799. }
  2800. ctx.restore();
  2801. }
  2802. }
  2803. });
  2804. var Item = Base.extend(Emitter, {
  2805. statics: {
  2806. extend: function extend(src) {
  2807. if (src._serializeFields)
  2808. src._serializeFields = Base.set({},
  2809. this.prototype._serializeFields, src._serializeFields);
  2810. return extend.base.apply(this, arguments);
  2811. },
  2812. NO_INSERT: { insert: false }
  2813. },
  2814. _class: 'Item',
  2815. _name: null,
  2816. _applyMatrix: true,
  2817. _canApplyMatrix: true,
  2818. _canScaleStroke: false,
  2819. _pivot: null,
  2820. _visible: true,
  2821. _blendMode: 'normal',
  2822. _opacity: 1,
  2823. _locked: false,
  2824. _guide: false,
  2825. _clipMask: false,
  2826. _selection: 0,
  2827. _selectBounds: true,
  2828. _selectChildren: false,
  2829. _serializeFields: {
  2830. name: null,
  2831. applyMatrix: null,
  2832. matrix: new Matrix(),
  2833. pivot: null,
  2834. visible: true,
  2835. blendMode: 'normal',
  2836. opacity: 1,
  2837. locked: false,
  2838. guide: false,
  2839. clipMask: false,
  2840. selected: false,
  2841. data: {}
  2842. },
  2843. _prioritize: ['applyMatrix']
  2844. },
  2845. new function() {
  2846. var handlers = ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
  2847. 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'];
  2848. return Base.each(handlers,
  2849. function(name) {
  2850. this._events[name] = {
  2851. install: function(type) {
  2852. this.getView()._countItemEvent(type, 1);
  2853. },
  2854. uninstall: function(type) {
  2855. this.getView()._countItemEvent(type, -1);
  2856. }
  2857. };
  2858. }, {
  2859. _events: {
  2860. onFrame: {
  2861. install: function() {
  2862. this.getView()._animateItem(this, true);
  2863. },
  2864. uninstall: function() {
  2865. this.getView()._animateItem(this, false);
  2866. }
  2867. },
  2868. onLoad: {},
  2869. onError: {}
  2870. },
  2871. statics: {
  2872. _itemHandlers: handlers
  2873. }
  2874. }
  2875. );
  2876. }, {
  2877. initialize: function Item() {
  2878. },
  2879. _initialize: function(props, point) {
  2880. var hasProps = props && Base.isPlainObject(props),
  2881. internal = hasProps && props.internal === true,
  2882. matrix = this._matrix = new Matrix(),
  2883. project = hasProps && props.project || paper.project,
  2884. settings = paper.settings;
  2885. this._id = internal ? null : UID.get();
  2886. this._parent = this._index = null;
  2887. this._applyMatrix = this._canApplyMatrix && settings.applyMatrix;
  2888. if (point)
  2889. matrix.translate(point);
  2890. matrix._owner = this;
  2891. this._style = new Style(project._currentStyle, this, project);
  2892. if (internal || hasProps && props.insert == false
  2893. || !settings.insertItems && !(hasProps && props.insert === true)) {
  2894. this._setProject(project);
  2895. } else {
  2896. (hasProps && props.parent || project)
  2897. ._insertItem(undefined, this, true);
  2898. }
  2899. if (hasProps && props !== Item.NO_INSERT) {
  2900. this.set(props, {
  2901. internal: true, insert: true, project: true, parent: true
  2902. });
  2903. }
  2904. return hasProps;
  2905. },
  2906. _serialize: function(options, dictionary) {
  2907. var props = {},
  2908. that = this;
  2909. function serialize(fields) {
  2910. for (var key in fields) {
  2911. var value = that[key];
  2912. if (!Base.equals(value, key === 'leading'
  2913. ? fields.fontSize * 1.2 : fields[key])) {
  2914. props[key] = Base.serialize(value, options,
  2915. key !== 'data', dictionary);
  2916. }
  2917. }
  2918. }
  2919. serialize(this._serializeFields);
  2920. if (!(this instanceof Group))
  2921. serialize(this._style._defaults);
  2922. return [ this._class, props ];
  2923. },
  2924. _changed: function(flags) {
  2925. var symbol = this._symbol,
  2926. cacheParent = this._parent || symbol,
  2927. project = this._project;
  2928. if (flags & 8) {
  2929. this._bounds = this._position = this._decomposed = undefined;
  2930. }
  2931. if (flags & 16) {
  2932. this._globalMatrix = undefined;
  2933. }
  2934. if (cacheParent
  2935. && (flags & 72)) {
  2936. Item._clearBoundsCache(cacheParent);
  2937. }
  2938. if (flags & 2) {
  2939. Item._clearBoundsCache(this);
  2940. }
  2941. if (project)
  2942. project._changed(flags, this);
  2943. if (symbol)
  2944. symbol._changed(flags);
  2945. },
  2946. getId: function() {
  2947. return this._id;
  2948. },
  2949. getName: function() {
  2950. return this._name;
  2951. },
  2952. setName: function(name) {
  2953. if (this._name)
  2954. this._removeNamed();
  2955. if (name === (+name) + '')
  2956. throw new Error(
  2957. 'Names consisting only of numbers are not supported.');
  2958. var owner = this._getOwner();
  2959. if (name && owner) {
  2960. var children = owner._children,
  2961. namedChildren = owner._namedChildren;
  2962. (namedChildren[name] = namedChildren[name] || []).push(this);
  2963. if (!(name in children))
  2964. children[name] = this;
  2965. }
  2966. this._name = name || undefined;
  2967. this._changed(256);
  2968. },
  2969. getStyle: function() {
  2970. return this._style;
  2971. },
  2972. setStyle: function(style) {
  2973. this.getStyle().set(style);
  2974. }
  2975. }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
  2976. function(name) {
  2977. var part = Base.capitalize(name),
  2978. key = '_' + name,
  2979. flags = {
  2980. locked: 256,
  2981. visible: 265
  2982. };
  2983. this['get' + part] = function() {
  2984. return this[key];
  2985. };
  2986. this['set' + part] = function(value) {
  2987. if (value != this[key]) {
  2988. this[key] = value;
  2989. this._changed(flags[name] || 257);
  2990. }
  2991. };
  2992. },
  2993. {}), {
  2994. beans: true,
  2995. getSelection: function() {
  2996. return this._selection;
  2997. },
  2998. setSelection: function(selection) {
  2999. if (selection !== this._selection) {
  3000. this._selection = selection;
  3001. var project = this._project;
  3002. if (project) {
  3003. project._updateSelection(this);
  3004. this._changed(257);
  3005. }
  3006. }
  3007. },
  3008. _changeSelection: function(flag, selected) {
  3009. var selection = this._selection;
  3010. this.setSelection(selected ? selection | flag : selection & ~flag);
  3011. },
  3012. isSelected: function() {
  3013. if (this._selectChildren) {
  3014. var children = this._children;
  3015. for (var i = 0, l = children.length; i < l; i++)
  3016. if (children[i].isSelected())
  3017. return true;
  3018. }
  3019. return !!(this._selection & 1);
  3020. },
  3021. setSelected: function(selected) {
  3022. if (this._selectChildren) {
  3023. var children = this._children;
  3024. for (var i = 0, l = children.length; i < l; i++)
  3025. children[i].setSelected(selected);
  3026. }
  3027. this._changeSelection(1, selected);
  3028. },
  3029. isFullySelected: function() {
  3030. var children = this._children,
  3031. selected = !!(this._selection & 1);
  3032. if (children && selected) {
  3033. for (var i = 0, l = children.length; i < l; i++)
  3034. if (!children[i].isFullySelected())
  3035. return false;
  3036. return true;
  3037. }
  3038. return selected;
  3039. },
  3040. setFullySelected: function(selected) {
  3041. var children = this._children;
  3042. if (children) {
  3043. for (var i = 0, l = children.length; i < l; i++)
  3044. children[i].setFullySelected(selected);
  3045. }
  3046. this._changeSelection(1, selected);
  3047. },
  3048. isClipMask: function() {
  3049. return this._clipMask;
  3050. },
  3051. setClipMask: function(clipMask) {
  3052. if (this._clipMask != (clipMask = !!clipMask)) {
  3053. this._clipMask = clipMask;
  3054. if (clipMask) {
  3055. this.setFillColor(null);
  3056. this.setStrokeColor(null);
  3057. }
  3058. this._changed(257);
  3059. if (this._parent)
  3060. this._parent._changed(2048);
  3061. }
  3062. },
  3063. getData: function() {
  3064. if (!this._data)
  3065. this._data = {};
  3066. return this._data;
  3067. },
  3068. setData: function(data) {
  3069. this._data = data;
  3070. },
  3071. getPosition: function(_dontLink) {
  3072. var ctor = _dontLink ? Point : LinkedPoint;
  3073. var position = this._position ||
  3074. (this._position = this._getPositionFromBounds());
  3075. return new ctor(position.x, position.y, this, 'setPosition');
  3076. },
  3077. setPosition: function() {
  3078. this.translate(Point.read(arguments).subtract(this.getPosition(true)));
  3079. },
  3080. _getPositionFromBounds: function(bounds) {
  3081. return this._pivot
  3082. ? this._matrix._transformPoint(this._pivot)
  3083. : (bounds || this.getBounds()).getCenter(true);
  3084. },
  3085. getPivot: function() {
  3086. var pivot = this._pivot;
  3087. return pivot
  3088. ? new LinkedPoint(pivot.x, pivot.y, this, 'setPivot')
  3089. : null;
  3090. },
  3091. setPivot: function() {
  3092. this._pivot = Point.read(arguments, 0, { clone: true, readNull: true });
  3093. this._position = undefined;
  3094. }
  3095. }, Base.each({
  3096. getStrokeBounds: { stroke: true },
  3097. getHandleBounds: { handle: true },
  3098. getInternalBounds: { internal: true }
  3099. },
  3100. function(options, key) {
  3101. this[key] = function(matrix) {
  3102. return this.getBounds(matrix, options);
  3103. };
  3104. },
  3105. {
  3106. beans: true,
  3107. getBounds: function(matrix, options) {
  3108. var hasMatrix = options || matrix instanceof Matrix,
  3109. opts = Base.set({}, hasMatrix ? options : matrix,
  3110. this._boundsOptions);
  3111. if (!opts.stroke || this.getStrokeScaling())
  3112. opts.cacheItem = this;
  3113. var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect;
  3114. return !arguments.length
  3115. ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height,
  3116. this, 'setBounds')
  3117. : rect;
  3118. },
  3119. setBounds: function() {
  3120. var rect = Rectangle.read(arguments),
  3121. bounds = this.getBounds(),
  3122. _matrix = this._matrix,
  3123. matrix = new Matrix(),
  3124. center = rect.getCenter();
  3125. matrix.translate(center);
  3126. if (rect.width != bounds.width || rect.height != bounds.height) {
  3127. if (!_matrix.isInvertible()) {
  3128. _matrix.set(_matrix._backup
  3129. || new Matrix().translate(_matrix.getTranslation()));
  3130. bounds = this.getBounds();
  3131. }
  3132. matrix.scale(
  3133. bounds.width !== 0 ? rect.width / bounds.width : 0,
  3134. bounds.height !== 0 ? rect.height / bounds.height : 0);
  3135. }
  3136. center = bounds.getCenter();
  3137. matrix.translate(-center.x, -center.y);
  3138. this.transform(matrix);
  3139. },
  3140. _getBounds: function(matrix, options) {
  3141. var children = this._children;
  3142. if (!children || !children.length)
  3143. return new Rectangle();
  3144. Item._updateBoundsCache(this, options.cacheItem);
  3145. return Item._getBounds(children, matrix, options);
  3146. },
  3147. _getBoundsCacheKey: function(options, internal) {
  3148. return [
  3149. options.stroke ? 1 : 0,
  3150. options.handle ? 1 : 0,
  3151. internal ? 1 : 0
  3152. ].join('');
  3153. },
  3154. _getCachedBounds: function(matrix, options, noInternal) {
  3155. matrix = matrix && matrix._orNullIfIdentity();
  3156. var internal = options.internal && !noInternal,
  3157. cacheItem = options.cacheItem,
  3158. _matrix = internal ? null : this._matrix._orNullIfIdentity(),
  3159. cacheKey = cacheItem && (!matrix || matrix.equals(_matrix))
  3160. && this._getBoundsCacheKey(options, internal),
  3161. bounds = this._bounds;
  3162. Item._updateBoundsCache(this._parent || this._symbol, cacheItem);
  3163. if (cacheKey && bounds && cacheKey in bounds) {
  3164. var cached = bounds[cacheKey];
  3165. return {
  3166. rect: cached.rect.clone(),
  3167. nonscaling: cached.nonscaling
  3168. };
  3169. }
  3170. var res = this._getBounds(matrix || _matrix, options),
  3171. rect = res.rect || res,
  3172. style = this._style,
  3173. nonscaling = res.nonscaling || style.hasStroke()
  3174. && !style.getStrokeScaling();
  3175. if (cacheKey) {
  3176. if (!bounds) {
  3177. this._bounds = bounds = {};
  3178. }
  3179. var cached = bounds[cacheKey] = {
  3180. rect: rect.clone(),
  3181. nonscaling: nonscaling,
  3182. internal: internal
  3183. };
  3184. }
  3185. return {
  3186. rect: rect,
  3187. nonscaling: nonscaling
  3188. };
  3189. },
  3190. _getStrokeMatrix: function(matrix, options) {
  3191. var parent = this.getStrokeScaling() ? null
  3192. : options && options.internal ? this
  3193. : this._parent || this._symbol && this._symbol._item,
  3194. mx = parent ? parent.getViewMatrix().invert() : matrix;
  3195. return mx && mx._shiftless();
  3196. },
  3197. statics: {
  3198. _updateBoundsCache: function(parent, item) {
  3199. if (parent && item) {
  3200. var id = item._id,
  3201. ref = parent._boundsCache = parent._boundsCache || {
  3202. ids: {},
  3203. list: []
  3204. };
  3205. if (!ref.ids[id]) {
  3206. ref.list.push(item);
  3207. ref.ids[id] = item;
  3208. }
  3209. }
  3210. },
  3211. _clearBoundsCache: function(item) {
  3212. var cache = item._boundsCache;
  3213. if (cache) {
  3214. item._bounds = item._position = item._boundsCache = undefined;
  3215. for (var i = 0, list = cache.list, l = list.length; i < l; i++){
  3216. var other = list[i];
  3217. if (other !== item) {
  3218. other._bounds = other._position = undefined;
  3219. if (other._boundsCache)
  3220. Item._clearBoundsCache(other);
  3221. }
  3222. }
  3223. }
  3224. },
  3225. _getBounds: function(items, matrix, options) {
  3226. var x1 = Infinity,
  3227. x2 = -x1,
  3228. y1 = x1,
  3229. y2 = x2,
  3230. nonscaling = false;
  3231. options = options || {};
  3232. for (var i = 0, l = items.length; i < l; i++) {
  3233. var item = items[i];
  3234. if (item._visible && !item.isEmpty(true)) {
  3235. var bounds = item._getCachedBounds(
  3236. matrix && matrix.appended(item._matrix), options, true),
  3237. rect = bounds.rect;
  3238. x1 = Math.min(rect.x, x1);
  3239. y1 = Math.min(rect.y, y1);
  3240. x2 = Math.max(rect.x + rect.width, x2);
  3241. y2 = Math.max(rect.y + rect.height, y2);
  3242. if (bounds.nonscaling)
  3243. nonscaling = true;
  3244. }
  3245. }
  3246. return {
  3247. rect: isFinite(x1)
  3248. ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
  3249. : new Rectangle(),
  3250. nonscaling: nonscaling
  3251. };
  3252. }
  3253. }
  3254. }), {
  3255. beans: true,
  3256. _decompose: function() {
  3257. return this._applyMatrix
  3258. ? null
  3259. : this._decomposed || (this._decomposed = this._matrix.decompose());
  3260. },
  3261. getRotation: function() {
  3262. var decomposed = this._decompose();
  3263. return decomposed ? decomposed.rotation : 0;
  3264. },
  3265. setRotation: function(rotation) {
  3266. var current = this.getRotation();
  3267. if (current != null && rotation != null) {
  3268. var decomposed = this._decomposed;
  3269. this.rotate(rotation - current);
  3270. if (decomposed) {
  3271. decomposed.rotation = rotation;
  3272. this._decomposed = decomposed;
  3273. }
  3274. }
  3275. },
  3276. getScaling: function() {
  3277. var decomposed = this._decompose(),
  3278. s = decomposed && decomposed.scaling;
  3279. return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, 'setScaling');
  3280. },
  3281. setScaling: function() {
  3282. var current = this.getScaling(),
  3283. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  3284. if (current && scaling && !current.equals(scaling)) {
  3285. var rotation = this.getRotation(),
  3286. decomposed = this._decomposed,
  3287. matrix = new Matrix(),
  3288. isZero = Numerical.isZero;
  3289. if (isZero(current.x) || isZero(current.y)) {
  3290. matrix.translate(decomposed.translation);
  3291. if (rotation) {
  3292. matrix.rotate(rotation);
  3293. }
  3294. matrix.scale(scaling.x, scaling.y);
  3295. this._matrix.set(matrix);
  3296. } else {
  3297. var center = this.getPosition(true);
  3298. matrix.translate(center);
  3299. if (rotation)
  3300. matrix.rotate(rotation);
  3301. matrix.scale(scaling.x / current.x, scaling.y / current.y);
  3302. if (rotation)
  3303. matrix.rotate(-rotation);
  3304. matrix.translate(center.negate());
  3305. this.transform(matrix);
  3306. }
  3307. if (decomposed) {
  3308. decomposed.scaling = scaling;
  3309. this._decomposed = decomposed;
  3310. }
  3311. }
  3312. },
  3313. getMatrix: function() {
  3314. return this._matrix;
  3315. },
  3316. setMatrix: function() {
  3317. var matrix = this._matrix;
  3318. matrix.set.apply(matrix, arguments);
  3319. },
  3320. getGlobalMatrix: function(_dontClone) {
  3321. var matrix = this._globalMatrix;
  3322. if (matrix) {
  3323. var parent = this._parent;
  3324. var parents = [];
  3325. while (parent) {
  3326. if (!parent._globalMatrix) {
  3327. matrix = null;
  3328. for (var i = 0, l = parents.length; i < l; i++) {
  3329. parents[i]._globalMatrix = null;
  3330. }
  3331. break;
  3332. }
  3333. parents.push(parent);
  3334. parent = parent._parent;
  3335. }
  3336. }
  3337. if (!matrix) {
  3338. matrix = this._globalMatrix = this._matrix.clone();
  3339. var parent = this._parent;
  3340. if (parent)
  3341. matrix.prepend(parent.getGlobalMatrix(true));
  3342. }
  3343. return _dontClone ? matrix : matrix.clone();
  3344. },
  3345. getViewMatrix: function() {
  3346. return this.getGlobalMatrix().prepend(this.getView()._matrix);
  3347. },
  3348. getApplyMatrix: function() {
  3349. return this._applyMatrix;
  3350. },
  3351. setApplyMatrix: function(apply) {
  3352. if (this._applyMatrix = this._canApplyMatrix && !!apply)
  3353. this.transform(null, true);
  3354. },
  3355. getTransformContent: '#getApplyMatrix',
  3356. setTransformContent: '#setApplyMatrix',
  3357. }, {
  3358. getProject: function() {
  3359. return this._project;
  3360. },
  3361. _setProject: function(project, installEvents) {
  3362. if (this._project !== project) {
  3363. if (this._project)
  3364. this._installEvents(false);
  3365. this._project = project;
  3366. var children = this._children;
  3367. for (var i = 0, l = children && children.length; i < l; i++)
  3368. children[i]._setProject(project);
  3369. installEvents = true;
  3370. }
  3371. if (installEvents)
  3372. this._installEvents(true);
  3373. },
  3374. getView: function() {
  3375. return this._project._view;
  3376. },
  3377. _installEvents: function _installEvents(install) {
  3378. _installEvents.base.call(this, install);
  3379. var children = this._children;
  3380. for (var i = 0, l = children && children.length; i < l; i++)
  3381. children[i]._installEvents(install);
  3382. },
  3383. getLayer: function() {
  3384. var parent = this;
  3385. while (parent = parent._parent) {
  3386. if (parent instanceof Layer)
  3387. return parent;
  3388. }
  3389. return null;
  3390. },
  3391. getParent: function() {
  3392. return this._parent;
  3393. },
  3394. setParent: function(item) {
  3395. return item.addChild(this);
  3396. },
  3397. _getOwner: '#getParent',
  3398. getChildren: function() {
  3399. return this._children;
  3400. },
  3401. setChildren: function(items) {
  3402. this.removeChildren();
  3403. this.addChildren(items);
  3404. },
  3405. getFirstChild: function() {
  3406. return this._children && this._children[0] || null;
  3407. },
  3408. getLastChild: function() {
  3409. return this._children && this._children[this._children.length - 1]
  3410. || null;
  3411. },
  3412. getNextSibling: function() {
  3413. var owner = this._getOwner();
  3414. return owner && owner._children[this._index + 1] || null;
  3415. },
  3416. getPreviousSibling: function() {
  3417. var owner = this._getOwner();
  3418. return owner && owner._children[this._index - 1] || null;
  3419. },
  3420. getIndex: function() {
  3421. return this._index;
  3422. },
  3423. equals: function(item) {
  3424. return item === this || item && this._class === item._class
  3425. && this._style.equals(item._style)
  3426. && this._matrix.equals(item._matrix)
  3427. && this._locked === item._locked
  3428. && this._visible === item._visible
  3429. && this._blendMode === item._blendMode
  3430. && this._opacity === item._opacity
  3431. && this._clipMask === item._clipMask
  3432. && this._guide === item._guide
  3433. && this._equals(item)
  3434. || false;
  3435. },
  3436. _equals: function(item) {
  3437. return Base.equals(this._children, item._children);
  3438. },
  3439. clone: function(options) {
  3440. var copy = new this.constructor(Item.NO_INSERT),
  3441. children = this._children,
  3442. insert = Base.pick(options ? options.insert : undefined,
  3443. options === undefined || options === true),
  3444. deep = Base.pick(options ? options.deep : undefined, true);
  3445. if (children)
  3446. copy.copyAttributes(this);
  3447. if (!children || deep)
  3448. copy.copyContent(this);
  3449. if (!children)
  3450. copy.copyAttributes(this);
  3451. if (insert)
  3452. copy.insertAbove(this);
  3453. var name = this._name,
  3454. parent = this._parent;
  3455. if (name && parent) {
  3456. var children = parent._children,
  3457. orig = name,
  3458. i = 1;
  3459. while (children[name])
  3460. name = orig + ' ' + (i++);
  3461. if (name !== orig)
  3462. copy.setName(name);
  3463. }
  3464. return copy;
  3465. },
  3466. copyContent: function(source) {
  3467. var children = source._children;
  3468. for (var i = 0, l = children && children.length; i < l; i++) {
  3469. this.addChild(children[i].clone(false), true);
  3470. }
  3471. },
  3472. copyAttributes: function(source, excludeMatrix) {
  3473. this.setStyle(source._style);
  3474. var keys = ['_locked', '_visible', '_blendMode', '_opacity',
  3475. '_clipMask', '_guide'];
  3476. for (var i = 0, l = keys.length; i < l; i++) {
  3477. var key = keys[i];
  3478. if (source.hasOwnProperty(key))
  3479. this[key] = source[key];
  3480. }
  3481. if (!excludeMatrix)
  3482. this._matrix.set(source._matrix, true);
  3483. this.setApplyMatrix(source._applyMatrix);
  3484. this.setPivot(source._pivot);
  3485. this.setSelection(source._selection);
  3486. var data = source._data,
  3487. name = source._name;
  3488. this._data = data ? Base.clone(data) : null;
  3489. if (name)
  3490. this.setName(name);
  3491. },
  3492. rasterize: function(arg0, arg1) {
  3493. var resolution,
  3494. insert,
  3495. raster;
  3496. if (Base.isPlainObject(arg0)) {
  3497. resolution = arg0.resolution;
  3498. insert = arg0.insert;
  3499. raster = arg0.raster;
  3500. } else {
  3501. resolution = arg0;
  3502. insert = arg1;
  3503. }
  3504. if (raster) {
  3505. raster.matrix.reset(true);
  3506. } else {
  3507. raster = new Raster(Item.NO_INSERT);
  3508. }
  3509. var bounds = this.getStrokeBounds(),
  3510. scale = (resolution || this.getView().getResolution()) / 72,
  3511. topLeft = bounds.getTopLeft().floor(),
  3512. bottomRight = bounds.getBottomRight().ceil(),
  3513. boundsSize = new Size(bottomRight.subtract(topLeft)),
  3514. rasterSize = boundsSize.multiply(scale);
  3515. raster.setSize(rasterSize, true);
  3516. if (!rasterSize.isZero()) {
  3517. var ctx = raster.getContext(true),
  3518. matrix = new Matrix().scale(scale).translate(topLeft.negate());
  3519. ctx.save();
  3520. matrix.applyToContext(ctx);
  3521. this.draw(ctx, new Base({ matrices: [matrix] }));
  3522. ctx.restore();
  3523. }
  3524. raster.transform(
  3525. new Matrix()
  3526. .translate(topLeft.add(boundsSize.divide(2)))
  3527. .scale(1 / scale)
  3528. );
  3529. if (insert === undefined || insert) {
  3530. raster.insertAbove(this);
  3531. }
  3532. return raster;
  3533. },
  3534. contains: function() {
  3535. var matrix = this._matrix;
  3536. return (
  3537. matrix.isInvertible() &&
  3538. !!this._contains(matrix._inverseTransform(Point.read(arguments)))
  3539. );
  3540. },
  3541. _contains: function(point) {
  3542. var children = this._children;
  3543. if (children) {
  3544. for (var i = children.length - 1; i >= 0; i--) {
  3545. if (children[i].contains(point))
  3546. return true;
  3547. }
  3548. return false;
  3549. }
  3550. return point.isInside(this.getInternalBounds());
  3551. },
  3552. isInside: function() {
  3553. return Rectangle.read(arguments).contains(this.getBounds());
  3554. },
  3555. _asPathItem: function() {
  3556. return new Path.Rectangle({
  3557. rectangle: this.getInternalBounds(),
  3558. matrix: this._matrix,
  3559. insert: false,
  3560. });
  3561. },
  3562. intersects: function(item, _matrix) {
  3563. if (!(item instanceof Item))
  3564. return false;
  3565. return this._asPathItem().getIntersections(item._asPathItem(), null,
  3566. _matrix, true).length > 0;
  3567. }
  3568. },
  3569. new function() {
  3570. function hitTest() {
  3571. var args = arguments;
  3572. return this._hitTest(
  3573. Point.read(args),
  3574. HitResult.getOptions(args));
  3575. }
  3576. function hitTestAll() {
  3577. var args = arguments,
  3578. point = Point.read(args),
  3579. options = HitResult.getOptions(args),
  3580. all = [];
  3581. this._hitTest(point, new Base({ all: all }, options));
  3582. return all;
  3583. }
  3584. function hitTestChildren(point, options, viewMatrix, _exclude) {
  3585. var children = this._children;
  3586. if (children) {
  3587. for (var i = children.length - 1; i >= 0; i--) {
  3588. var child = children[i];
  3589. var res = child !== _exclude && child._hitTest(point, options,
  3590. viewMatrix);
  3591. if (res && !options.all)
  3592. return res;
  3593. }
  3594. }
  3595. return null;
  3596. }
  3597. Project.inject({
  3598. hitTest: hitTest,
  3599. hitTestAll: hitTestAll,
  3600. _hitTest: hitTestChildren
  3601. });
  3602. return {
  3603. hitTest: hitTest,
  3604. hitTestAll: hitTestAll,
  3605. _hitTestChildren: hitTestChildren,
  3606. };
  3607. }, {
  3608. _hitTest: function(point, options, parentViewMatrix) {
  3609. if (this._locked || !this._visible || this._guide && !options.guides
  3610. || this.isEmpty()) {
  3611. return null;
  3612. }
  3613. var matrix = this._matrix,
  3614. viewMatrix = parentViewMatrix
  3615. ? parentViewMatrix.appended(matrix)
  3616. : this.getGlobalMatrix().prepend(this.getView()._matrix),
  3617. tolerance = Math.max(options.tolerance, 1e-12),
  3618. tolerancePadding = options._tolerancePadding = new Size(
  3619. Path._getStrokePadding(tolerance,
  3620. matrix._shiftless().invert()));
  3621. point = matrix._inverseTransform(point);
  3622. if (!point || !this._children &&
  3623. !this.getBounds({ internal: true, stroke: true, handle: true })
  3624. .expand(tolerancePadding.multiply(2))._containsPoint(point)) {
  3625. return null;
  3626. }
  3627. var checkSelf = !(options.guides && !this._guide
  3628. || options.selected && !this.isSelected()
  3629. || options.type && options.type !== Base.hyphenate(this._class)
  3630. || options.class && !(this instanceof options.class)),
  3631. match = options.match,
  3632. that = this,
  3633. bounds,
  3634. res;
  3635. function filter(hit) {
  3636. if (hit && match && !match(hit))
  3637. hit = null;
  3638. if (hit && options.all)
  3639. options.all.push(hit);
  3640. return hit;
  3641. }
  3642. function checkPoint(type, part) {
  3643. var pt = part ? bounds['get' + part]() : that.getPosition();
  3644. if (point.subtract(pt).divide(tolerancePadding).length <= 1) {
  3645. return new HitResult(type, that, {
  3646. name: part ? Base.hyphenate(part) : type,
  3647. point: pt
  3648. });
  3649. }
  3650. }
  3651. var checkPosition = options.position,
  3652. checkCenter = options.center,
  3653. checkBounds = options.bounds;
  3654. if (checkSelf && this._parent
  3655. && (checkPosition || checkCenter || checkBounds)) {
  3656. if (checkCenter || checkBounds) {
  3657. bounds = this.getInternalBounds();
  3658. }
  3659. res = checkPosition && checkPoint('position') ||
  3660. checkCenter && checkPoint('center', 'Center');
  3661. if (!res && checkBounds) {
  3662. var points = [
  3663. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  3664. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
  3665. ];
  3666. for (var i = 0; i < 8 && !res; i++) {
  3667. res = checkPoint('bounds', points[i]);
  3668. }
  3669. }
  3670. res = filter(res);
  3671. }
  3672. if (!res) {
  3673. res = this._hitTestChildren(point, options, viewMatrix)
  3674. || checkSelf
  3675. && filter(this._hitTestSelf(point, options, viewMatrix,
  3676. this.getStrokeScaling() ? null
  3677. : viewMatrix._shiftless().invert()))
  3678. || null;
  3679. }
  3680. if (res && res.point) {
  3681. res.point = matrix.transform(res.point);
  3682. }
  3683. return res;
  3684. },
  3685. _hitTestSelf: function(point, options) {
  3686. if (options.fill && this.hasFill() && this._contains(point))
  3687. return new HitResult('fill', this);
  3688. },
  3689. matches: function(name, compare) {
  3690. function matchObject(obj1, obj2) {
  3691. for (var i in obj1) {
  3692. if (obj1.hasOwnProperty(i)) {
  3693. var val1 = obj1[i],
  3694. val2 = obj2[i];
  3695. if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
  3696. if (!matchObject(val1, val2))
  3697. return false;
  3698. } else if (!Base.equals(val1, val2)) {
  3699. return false;
  3700. }
  3701. }
  3702. }
  3703. return true;
  3704. }
  3705. var type = typeof name;
  3706. if (type === 'object') {
  3707. for (var key in name) {
  3708. if (name.hasOwnProperty(key) && !this.matches(key, name[key]))
  3709. return false;
  3710. }
  3711. return true;
  3712. } else if (type === 'function') {
  3713. return name(this);
  3714. } else if (name === 'match') {
  3715. return compare(this);
  3716. } else {
  3717. var value = /^(empty|editable)$/.test(name)
  3718. ? this['is' + Base.capitalize(name)]()
  3719. : name === 'type'
  3720. ? Base.hyphenate(this._class)
  3721. : this[name];
  3722. if (name === 'class') {
  3723. if (typeof compare === 'function')
  3724. return this instanceof compare;
  3725. value = this._class;
  3726. }
  3727. if (typeof compare === 'function') {
  3728. return !!compare(value);
  3729. } else if (compare) {
  3730. if (compare.test) {
  3731. return compare.test(value);
  3732. } else if (Base.isPlainObject(compare)) {
  3733. return matchObject(compare, value);
  3734. }
  3735. }
  3736. return Base.equals(value, compare);
  3737. }
  3738. },
  3739. getItems: function(options) {
  3740. return Item._getItems(this, options, this._matrix);
  3741. },
  3742. getItem: function(options) {
  3743. return Item._getItems(this, options, this._matrix, null, true)[0]
  3744. || null;
  3745. },
  3746. statics: {
  3747. _getItems: function _getItems(item, options, matrix, param, firstOnly) {
  3748. if (!param) {
  3749. var obj = typeof options === 'object' && options,
  3750. overlapping = obj && obj.overlapping,
  3751. inside = obj && obj.inside,
  3752. bounds = overlapping || inside,
  3753. rect = bounds && Rectangle.read([bounds]);
  3754. param = {
  3755. items: [],
  3756. recursive: obj && obj.recursive !== false,
  3757. inside: !!inside,
  3758. overlapping: !!overlapping,
  3759. rect: rect,
  3760. path: overlapping && new Path.Rectangle({
  3761. rectangle: rect,
  3762. insert: false
  3763. })
  3764. };
  3765. if (obj) {
  3766. options = Base.filter({}, options, {
  3767. recursive: true, inside: true, overlapping: true
  3768. });
  3769. }
  3770. }
  3771. var children = item._children,
  3772. items = param.items,
  3773. rect = param.rect;
  3774. matrix = rect && (matrix || new Matrix());
  3775. for (var i = 0, l = children && children.length; i < l; i++) {
  3776. var child = children[i],
  3777. childMatrix = matrix && matrix.appended(child._matrix),
  3778. add = true;
  3779. if (rect) {
  3780. var bounds = child.getBounds(childMatrix);
  3781. if (!rect.intersects(bounds))
  3782. continue;
  3783. if (!(rect.contains(bounds)
  3784. || param.overlapping && (bounds.contains(rect)
  3785. || param.path.intersects(child, childMatrix))))
  3786. add = false;
  3787. }
  3788. if (add && child.matches(options)) {
  3789. items.push(child);
  3790. if (firstOnly)
  3791. break;
  3792. }
  3793. if (param.recursive !== false) {
  3794. _getItems(child, options, childMatrix, param, firstOnly);
  3795. }
  3796. if (firstOnly && items.length > 0)
  3797. break;
  3798. }
  3799. return items;
  3800. }
  3801. }
  3802. }, {
  3803. importJSON: function(json) {
  3804. var res = Base.importJSON(json, this);
  3805. return res !== this ? this.addChild(res) : res;
  3806. },
  3807. addChild: function(item) {
  3808. return this.insertChild(undefined, item);
  3809. },
  3810. insertChild: function(index, item) {
  3811. var res = item ? this.insertChildren(index, [item]) : null;
  3812. return res && res[0];
  3813. },
  3814. addChildren: function(items) {
  3815. return this.insertChildren(this._children.length, items);
  3816. },
  3817. insertChildren: function(index, items) {
  3818. var children = this._children;
  3819. if (children && items && items.length > 0) {
  3820. items = Base.slice(items);
  3821. var inserted = {};
  3822. for (var i = items.length - 1; i >= 0; i--) {
  3823. var item = items[i],
  3824. id = item && item._id;
  3825. if (!item || inserted[id]) {
  3826. items.splice(i, 1);
  3827. } else {
  3828. item._remove(false, true);
  3829. inserted[id] = true;
  3830. }
  3831. }
  3832. Base.splice(children, items, index, 0);
  3833. var project = this._project,
  3834. notifySelf = project._changes;
  3835. for (var i = 0, l = items.length; i < l; i++) {
  3836. var item = items[i],
  3837. name = item._name;
  3838. item._parent = this;
  3839. item._setProject(project, true);
  3840. if (name)
  3841. item.setName(name);
  3842. if (notifySelf)
  3843. item._changed(5);
  3844. }
  3845. this._changed(11);
  3846. } else {
  3847. items = null;
  3848. }
  3849. return items;
  3850. },
  3851. _insertItem: '#insertChild',
  3852. _insertAt: function(item, offset) {
  3853. var owner = item && item._getOwner(),
  3854. res = item !== this && owner ? this : null;
  3855. if (res) {
  3856. res._remove(false, true);
  3857. owner._insertItem(item._index + offset, res);
  3858. }
  3859. return res;
  3860. },
  3861. insertAbove: function(item) {
  3862. return this._insertAt(item, 1);
  3863. },
  3864. insertBelow: function(item) {
  3865. return this._insertAt(item, 0);
  3866. },
  3867. sendToBack: function() {
  3868. var owner = this._getOwner();
  3869. return owner ? owner._insertItem(0, this) : null;
  3870. },
  3871. bringToFront: function() {
  3872. var owner = this._getOwner();
  3873. return owner ? owner._insertItem(undefined, this) : null;
  3874. },
  3875. appendTop: '#addChild',
  3876. appendBottom: function(item) {
  3877. return this.insertChild(0, item);
  3878. },
  3879. moveAbove: '#insertAbove',
  3880. moveBelow: '#insertBelow',
  3881. addTo: function(owner) {
  3882. return owner._insertItem(undefined, this);
  3883. },
  3884. copyTo: function(owner) {
  3885. return this.clone(false).addTo(owner);
  3886. },
  3887. reduce: function(options) {
  3888. var children = this._children;
  3889. if (children && children.length === 1) {
  3890. var child = children[0].reduce(options);
  3891. if (this._parent) {
  3892. child.insertAbove(this);
  3893. this.remove();
  3894. } else {
  3895. child.remove();
  3896. }
  3897. return child;
  3898. }
  3899. return this;
  3900. },
  3901. _removeNamed: function() {
  3902. var owner = this._getOwner();
  3903. if (owner) {
  3904. var children = owner._children,
  3905. namedChildren = owner._namedChildren,
  3906. name = this._name,
  3907. namedArray = namedChildren[name],
  3908. index = namedArray ? namedArray.indexOf(this) : -1;
  3909. if (index !== -1) {
  3910. if (children[name] == this)
  3911. delete children[name];
  3912. namedArray.splice(index, 1);
  3913. if (namedArray.length) {
  3914. children[name] = namedArray[0];
  3915. } else {
  3916. delete namedChildren[name];
  3917. }
  3918. }
  3919. }
  3920. },
  3921. _remove: function(notifySelf, notifyParent) {
  3922. var owner = this._getOwner(),
  3923. project = this._project,
  3924. index = this._index;
  3925. if (this._style)
  3926. this._style._dispose();
  3927. if (owner) {
  3928. if (this._name)
  3929. this._removeNamed();
  3930. if (index != null) {
  3931. if (project._activeLayer === this)
  3932. project._activeLayer = this.getNextSibling()
  3933. || this.getPreviousSibling();
  3934. Base.splice(owner._children, null, index, 1);
  3935. }
  3936. this._installEvents(false);
  3937. if (notifySelf && project._changes)
  3938. this._changed(5);
  3939. if (notifyParent)
  3940. owner._changed(11, this);
  3941. this._parent = null;
  3942. return true;
  3943. }
  3944. return false;
  3945. },
  3946. remove: function() {
  3947. return this._remove(true, true);
  3948. },
  3949. replaceWith: function(item) {
  3950. var ok = item && item.insertBelow(this);
  3951. if (ok)
  3952. this.remove();
  3953. return ok;
  3954. },
  3955. removeChildren: function(start, end) {
  3956. if (!this._children)
  3957. return null;
  3958. start = start || 0;
  3959. end = Base.pick(end, this._children.length);
  3960. var removed = Base.splice(this._children, null, start, end - start);
  3961. for (var i = removed.length - 1; i >= 0; i--) {
  3962. removed[i]._remove(true, false);
  3963. }
  3964. if (removed.length > 0)
  3965. this._changed(11);
  3966. return removed;
  3967. },
  3968. clear: '#removeChildren',
  3969. reverseChildren: function() {
  3970. if (this._children) {
  3971. this._children.reverse();
  3972. for (var i = 0, l = this._children.length; i < l; i++)
  3973. this._children[i]._index = i;
  3974. this._changed(11);
  3975. }
  3976. },
  3977. isEmpty: function(recursively) {
  3978. var children = this._children;
  3979. var numChildren = children ? children.length : 0;
  3980. if (recursively) {
  3981. for (var i = 0; i < numChildren; i++) {
  3982. if (!children[i].isEmpty(recursively)) {
  3983. return false;
  3984. }
  3985. }
  3986. return true;
  3987. }
  3988. return !numChildren;
  3989. },
  3990. isEditable: function() {
  3991. var item = this;
  3992. while (item) {
  3993. if (!item._visible || item._locked)
  3994. return false;
  3995. item = item._parent;
  3996. }
  3997. return true;
  3998. },
  3999. hasFill: function() {
  4000. return this.getStyle().hasFill();
  4001. },
  4002. hasStroke: function() {
  4003. return this.getStyle().hasStroke();
  4004. },
  4005. hasShadow: function() {
  4006. return this.getStyle().hasShadow();
  4007. },
  4008. _getOrder: function(item) {
  4009. function getList(item) {
  4010. var list = [];
  4011. do {
  4012. list.unshift(item);
  4013. } while (item = item._parent);
  4014. return list;
  4015. }
  4016. var list1 = getList(this),
  4017. list2 = getList(item);
  4018. for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
  4019. if (list1[i] != list2[i]) {
  4020. return list1[i]._index < list2[i]._index ? 1 : -1;
  4021. }
  4022. }
  4023. return 0;
  4024. },
  4025. hasChildren: function() {
  4026. return this._children && this._children.length > 0;
  4027. },
  4028. isInserted: function() {
  4029. return this._parent ? this._parent.isInserted() : false;
  4030. },
  4031. isAbove: function(item) {
  4032. return this._getOrder(item) === -1;
  4033. },
  4034. isBelow: function(item) {
  4035. return this._getOrder(item) === 1;
  4036. },
  4037. isParent: function(item) {
  4038. return this._parent === item;
  4039. },
  4040. isChild: function(item) {
  4041. return item && item._parent === this;
  4042. },
  4043. isDescendant: function(item) {
  4044. var parent = this;
  4045. while (parent = parent._parent) {
  4046. if (parent === item)
  4047. return true;
  4048. }
  4049. return false;
  4050. },
  4051. isAncestor: function(item) {
  4052. return item ? item.isDescendant(this) : false;
  4053. },
  4054. isSibling: function(item) {
  4055. return this._parent === item._parent;
  4056. },
  4057. isGroupedWith: function(item) {
  4058. var parent = this._parent;
  4059. while (parent) {
  4060. if (parent._parent
  4061. && /^(Group|Layer|CompoundPath)$/.test(parent._class)
  4062. && item.isDescendant(parent))
  4063. return true;
  4064. parent = parent._parent;
  4065. }
  4066. return false;
  4067. },
  4068. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  4069. var rotate = key === 'rotate';
  4070. this[key] = function() {
  4071. var args = arguments,
  4072. value = (rotate ? Base : Point).read(args),
  4073. center = Point.read(args, 0, { readNull: true });
  4074. return this.transform(new Matrix()[key](value,
  4075. center || this.getPosition(true)));
  4076. };
  4077. }, {
  4078. translate: function() {
  4079. var mx = new Matrix();
  4080. return this.transform(mx.translate.apply(mx, arguments));
  4081. },
  4082. transform: function(matrix, _applyRecursively, _setApplyMatrix) {
  4083. var _matrix = this._matrix,
  4084. transformMatrix = matrix && !matrix.isIdentity(),
  4085. applyMatrix = (
  4086. _setApplyMatrix && this._canApplyMatrix ||
  4087. this._applyMatrix && (
  4088. transformMatrix || !_matrix.isIdentity() ||
  4089. _applyRecursively && this._children
  4090. )
  4091. );
  4092. if (!transformMatrix && !applyMatrix)
  4093. return this;
  4094. if (transformMatrix) {
  4095. if (!matrix.isInvertible() && _matrix.isInvertible())
  4096. _matrix._backup = _matrix.getValues();
  4097. _matrix.prepend(matrix, true);
  4098. var style = this._style,
  4099. fillColor = style.getFillColor(true),
  4100. strokeColor = style.getStrokeColor(true);
  4101. if (fillColor)
  4102. fillColor.transform(matrix);
  4103. if (strokeColor)
  4104. strokeColor.transform(matrix);
  4105. }
  4106. if (applyMatrix && (applyMatrix = this._transformContent(
  4107. _matrix, _applyRecursively, _setApplyMatrix))) {
  4108. var pivot = this._pivot;
  4109. if (pivot)
  4110. _matrix._transformPoint(pivot, pivot, true);
  4111. _matrix.reset(true);
  4112. if (_setApplyMatrix && this._canApplyMatrix)
  4113. this._applyMatrix = true;
  4114. }
  4115. var bounds = this._bounds,
  4116. position = this._position;
  4117. if (transformMatrix || applyMatrix) {
  4118. this._changed(25);
  4119. }
  4120. var decomp = transformMatrix && bounds && matrix.decompose();
  4121. if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) {
  4122. for (var key in bounds) {
  4123. var cache = bounds[key];
  4124. if (cache.nonscaling) {
  4125. delete bounds[key];
  4126. } else if (applyMatrix || !cache.internal) {
  4127. var rect = cache.rect;
  4128. matrix._transformBounds(rect, rect);
  4129. }
  4130. }
  4131. this._bounds = bounds;
  4132. var cached = bounds[this._getBoundsCacheKey(
  4133. this._boundsOptions || {})];
  4134. if (cached) {
  4135. this._position = this._getPositionFromBounds(cached.rect);
  4136. }
  4137. } else if (transformMatrix && position && this._pivot) {
  4138. this._position = matrix._transformPoint(position, position);
  4139. }
  4140. return this;
  4141. },
  4142. _transformContent: function(matrix, applyRecursively, setApplyMatrix) {
  4143. var children = this._children;
  4144. if (children) {
  4145. for (var i = 0, l = children.length; i < l; i++) {
  4146. children[i].transform(matrix, applyRecursively, setApplyMatrix);
  4147. }
  4148. return true;
  4149. }
  4150. },
  4151. globalToLocal: function() {
  4152. return this.getGlobalMatrix(true)._inverseTransform(
  4153. Point.read(arguments));
  4154. },
  4155. localToGlobal: function() {
  4156. return this.getGlobalMatrix(true)._transformPoint(
  4157. Point.read(arguments));
  4158. },
  4159. parentToLocal: function() {
  4160. return this._matrix._inverseTransform(Point.read(arguments));
  4161. },
  4162. localToParent: function() {
  4163. return this._matrix._transformPoint(Point.read(arguments));
  4164. },
  4165. fitBounds: function(rectangle, fill) {
  4166. rectangle = Rectangle.read(arguments);
  4167. var bounds = this.getBounds(),
  4168. itemRatio = bounds.height / bounds.width,
  4169. rectRatio = rectangle.height / rectangle.width,
  4170. scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
  4171. ? rectangle.width / bounds.width
  4172. : rectangle.height / bounds.height,
  4173. newBounds = new Rectangle(new Point(),
  4174. new Size(bounds.width * scale, bounds.height * scale));
  4175. newBounds.setCenter(rectangle.getCenter());
  4176. this.setBounds(newBounds);
  4177. }
  4178. }), {
  4179. _setStyles: function(ctx, param, viewMatrix) {
  4180. var style = this._style,
  4181. matrix = this._matrix;
  4182. if (style.hasFill()) {
  4183. ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix);
  4184. }
  4185. if (style.hasStroke()) {
  4186. ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix);
  4187. ctx.lineWidth = style.getStrokeWidth();
  4188. var strokeJoin = style.getStrokeJoin(),
  4189. strokeCap = style.getStrokeCap(),
  4190. miterLimit = style.getMiterLimit();
  4191. if (strokeJoin)
  4192. ctx.lineJoin = strokeJoin;
  4193. if (strokeCap)
  4194. ctx.lineCap = strokeCap;
  4195. if (miterLimit)
  4196. ctx.miterLimit = miterLimit;
  4197. if (paper.support.nativeDash) {
  4198. var dashArray = style.getDashArray(),
  4199. dashOffset = style.getDashOffset();
  4200. if (dashArray && dashArray.length) {
  4201. if ('setLineDash' in ctx) {
  4202. ctx.setLineDash(dashArray);
  4203. ctx.lineDashOffset = dashOffset;
  4204. } else {
  4205. ctx.mozDash = dashArray;
  4206. ctx.mozDashOffset = dashOffset;
  4207. }
  4208. }
  4209. }
  4210. }
  4211. if (style.hasShadow()) {
  4212. var pixelRatio = param.pixelRatio || 1,
  4213. mx = viewMatrix._shiftless().prepend(
  4214. new Matrix().scale(pixelRatio, pixelRatio)),
  4215. blur = mx.transform(new Point(style.getShadowBlur(), 0)),
  4216. offset = mx.transform(this.getShadowOffset());
  4217. ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx);
  4218. ctx.shadowBlur = blur.getLength();
  4219. ctx.shadowOffsetX = offset.x;
  4220. ctx.shadowOffsetY = offset.y;
  4221. }
  4222. },
  4223. draw: function(ctx, param, parentStrokeMatrix) {
  4224. var updateVersion = this._updateVersion = this._project._updateVersion;
  4225. if (!this._visible || this._opacity === 0)
  4226. return;
  4227. var matrices = param.matrices,
  4228. viewMatrix = param.viewMatrix,
  4229. matrix = this._matrix,
  4230. globalMatrix = matrices[matrices.length - 1].appended(matrix);
  4231. if (!globalMatrix.isInvertible())
  4232. return;
  4233. viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix)
  4234. : globalMatrix;
  4235. matrices.push(globalMatrix);
  4236. if (param.updateMatrix) {
  4237. this._globalMatrix = globalMatrix;
  4238. }
  4239. var blendMode = this._blendMode,
  4240. opacity = Numerical.clamp(this._opacity, 0, 1),
  4241. normalBlend = blendMode === 'normal',
  4242. nativeBlend = BlendMode.nativeModes[blendMode],
  4243. direct = normalBlend && opacity === 1
  4244. || param.dontStart
  4245. || param.clip
  4246. || (nativeBlend || normalBlend && opacity < 1)
  4247. && this._canComposite(),
  4248. pixelRatio = param.pixelRatio || 1,
  4249. mainCtx, itemOffset, prevOffset;
  4250. if (!direct) {
  4251. var bounds = this.getStrokeBounds(viewMatrix);
  4252. if (!bounds.width || !bounds.height) {
  4253. matrices.pop();
  4254. return;
  4255. }
  4256. prevOffset = param.offset;
  4257. itemOffset = param.offset = bounds.getTopLeft().floor();
  4258. mainCtx = ctx;
  4259. ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1)
  4260. .multiply(pixelRatio));
  4261. if (pixelRatio !== 1)
  4262. ctx.scale(pixelRatio, pixelRatio);
  4263. }
  4264. ctx.save();
  4265. var strokeMatrix = parentStrokeMatrix
  4266. ? parentStrokeMatrix.appended(matrix)
  4267. : this._canScaleStroke && !this.getStrokeScaling(true)
  4268. && viewMatrix,
  4269. clip = !direct && param.clipItem,
  4270. transform = !strokeMatrix || clip;
  4271. if (direct) {
  4272. ctx.globalAlpha = opacity;
  4273. if (nativeBlend)
  4274. ctx.globalCompositeOperation = blendMode;
  4275. } else if (transform) {
  4276. ctx.translate(-itemOffset.x, -itemOffset.y);
  4277. }
  4278. if (transform) {
  4279. (direct ? matrix : viewMatrix).applyToContext(ctx);
  4280. }
  4281. if (clip) {
  4282. param.clipItem.draw(ctx, param.extend({ clip: true }));
  4283. }
  4284. if (strokeMatrix) {
  4285. ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  4286. var offset = param.offset;
  4287. if (offset)
  4288. ctx.translate(-offset.x, -offset.y);
  4289. }
  4290. this._draw(ctx, param, viewMatrix, strokeMatrix);
  4291. ctx.restore();
  4292. matrices.pop();
  4293. if (param.clip && !param.dontFinish) {
  4294. ctx.clip(this.getFillRule());
  4295. }
  4296. if (!direct) {
  4297. BlendMode.process(blendMode, ctx, mainCtx, opacity,
  4298. itemOffset.subtract(prevOffset).multiply(pixelRatio));
  4299. CanvasProvider.release(ctx);
  4300. param.offset = prevOffset;
  4301. }
  4302. },
  4303. _isUpdated: function(updateVersion) {
  4304. var parent = this._parent;
  4305. if (parent instanceof CompoundPath)
  4306. return parent._isUpdated(updateVersion);
  4307. var updated = this._updateVersion === updateVersion;
  4308. if (!updated && parent && parent._visible
  4309. && parent._isUpdated(updateVersion)) {
  4310. this._updateVersion = updateVersion;
  4311. updated = true;
  4312. }
  4313. return updated;
  4314. },
  4315. _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) {
  4316. var selection = this._selection,
  4317. itemSelected = selection & 1,
  4318. boundsSelected = selection & 2
  4319. || itemSelected && this._selectBounds,
  4320. positionSelected = selection & 4;
  4321. if (!this._drawSelected)
  4322. itemSelected = false;
  4323. if ((itemSelected || boundsSelected || positionSelected)
  4324. && this._isUpdated(updateVersion)) {
  4325. var layer,
  4326. color = this.getSelectedColor(true) || (layer = this.getLayer())
  4327. && layer.getSelectedColor(true),
  4328. mx = matrix.appended(this.getGlobalMatrix(true)),
  4329. half = size / 2;
  4330. ctx.strokeStyle = ctx.fillStyle = color
  4331. ? color.toCanvasStyle(ctx) : '#009dec';
  4332. if (itemSelected)
  4333. this._drawSelected(ctx, mx, selectionItems);
  4334. if (positionSelected) {
  4335. var pos = this.getPosition(true),
  4336. parent = this._parent,
  4337. point = parent ? parent.localToGlobal(pos) : pos,
  4338. x = point.x,
  4339. y = point.y;
  4340. ctx.beginPath();
  4341. ctx.arc(x, y, half, 0, Math.PI * 2, true);
  4342. ctx.stroke();
  4343. var deltas = [[0, -1], [1, 0], [0, 1], [-1, 0]],
  4344. start = half,
  4345. end = size + 1;
  4346. for (var i = 0; i < 4; i++) {
  4347. var delta = deltas[i],
  4348. dx = delta[0],
  4349. dy = delta[1];
  4350. ctx.moveTo(x + dx * start, y + dy * start);
  4351. ctx.lineTo(x + dx * end, y + dy * end);
  4352. ctx.stroke();
  4353. }
  4354. }
  4355. if (boundsSelected) {
  4356. var coords = mx._transformCorners(this.getInternalBounds());
  4357. ctx.beginPath();
  4358. for (var i = 0; i < 8; i++) {
  4359. ctx[!i ? 'moveTo' : 'lineTo'](coords[i], coords[++i]);
  4360. }
  4361. ctx.closePath();
  4362. ctx.stroke();
  4363. for (var i = 0; i < 8; i++) {
  4364. ctx.fillRect(coords[i] - half, coords[++i] - half,
  4365. size, size);
  4366. }
  4367. }
  4368. }
  4369. },
  4370. _canComposite: function() {
  4371. return false;
  4372. }
  4373. }, Base.each(['down', 'drag', 'up', 'move'], function(key) {
  4374. this['removeOn' + Base.capitalize(key)] = function() {
  4375. var hash = {};
  4376. hash[key] = true;
  4377. return this.removeOn(hash);
  4378. };
  4379. }, {
  4380. removeOn: function(obj) {
  4381. for (var name in obj) {
  4382. if (obj[name]) {
  4383. var key = 'mouse' + name,
  4384. project = this._project,
  4385. sets = project._removeSets = project._removeSets || {};
  4386. sets[key] = sets[key] || {};
  4387. sets[key][this._id] = this;
  4388. }
  4389. }
  4390. return this;
  4391. }
  4392. }), {
  4393. tween: function(from, to, options) {
  4394. if (!options) {
  4395. options = to;
  4396. to = from;
  4397. from = null;
  4398. if (!options) {
  4399. options = to;
  4400. to = null;
  4401. }
  4402. }
  4403. var easing = options && options.easing,
  4404. start = options && options.start,
  4405. duration = options != null && (
  4406. typeof options === 'number' ? options : options.duration
  4407. ),
  4408. tween = new Tween(this, from, to, duration, easing, start);
  4409. function onFrame(event) {
  4410. tween._handleFrame(event.time * 1000);
  4411. if (!tween.running) {
  4412. this.off('frame', onFrame);
  4413. }
  4414. }
  4415. if (duration) {
  4416. this.on('frame', onFrame);
  4417. }
  4418. return tween;
  4419. },
  4420. tweenTo: function(to, options) {
  4421. return this.tween(null, to, options);
  4422. },
  4423. tweenFrom: function(from, options) {
  4424. return this.tween(from, null, options);
  4425. }
  4426. });
  4427. var Group = Item.extend({
  4428. _class: 'Group',
  4429. _selectBounds: false,
  4430. _selectChildren: true,
  4431. _serializeFields: {
  4432. children: []
  4433. },
  4434. initialize: function Group(arg) {
  4435. this._children = [];
  4436. this._namedChildren = {};
  4437. if (!this._initialize(arg))
  4438. this.addChildren(Array.isArray(arg) ? arg : arguments);
  4439. },
  4440. _changed: function _changed(flags) {
  4441. _changed.base.call(this, flags);
  4442. if (flags & 2050) {
  4443. this._clipItem = undefined;
  4444. }
  4445. },
  4446. _getClipItem: function() {
  4447. var clipItem = this._clipItem;
  4448. if (clipItem === undefined) {
  4449. clipItem = null;
  4450. var children = this._children;
  4451. for (var i = 0, l = children.length; i < l; i++) {
  4452. if (children[i]._clipMask) {
  4453. clipItem = children[i];
  4454. break;
  4455. }
  4456. }
  4457. this._clipItem = clipItem;
  4458. }
  4459. return clipItem;
  4460. },
  4461. isClipped: function() {
  4462. return !!this._getClipItem();
  4463. },
  4464. setClipped: function(clipped) {
  4465. var child = this.getFirstChild();
  4466. if (child)
  4467. child.setClipMask(clipped);
  4468. },
  4469. _getBounds: function _getBounds(matrix, options) {
  4470. var clipItem = this._getClipItem();
  4471. return clipItem
  4472. ? clipItem._getCachedBounds(clipItem._matrix.prepended(matrix),
  4473. Base.set({}, options, { stroke: false }))
  4474. : _getBounds.base.call(this, matrix, options);
  4475. },
  4476. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  4477. var clipItem = this._getClipItem();
  4478. return (!clipItem || clipItem.contains(point))
  4479. && _hitTestChildren.base.call(this, point, options, viewMatrix,
  4480. clipItem);
  4481. },
  4482. _draw: function(ctx, param) {
  4483. var clip = param.clip,
  4484. clipItem = !clip && this._getClipItem();
  4485. param = param.extend({ clipItem: clipItem, clip: false });
  4486. if (clip) {
  4487. ctx.beginPath();
  4488. param.dontStart = param.dontFinish = true;
  4489. } else if (clipItem) {
  4490. clipItem.draw(ctx, param.extend({ clip: true }));
  4491. }
  4492. var children = this._children;
  4493. for (var i = 0, l = children.length; i < l; i++) {
  4494. var item = children[i];
  4495. if (item !== clipItem)
  4496. item.draw(ctx, param);
  4497. }
  4498. }
  4499. });
  4500. var Layer = Group.extend({
  4501. _class: 'Layer',
  4502. initialize: function Layer() {
  4503. Group.apply(this, arguments);
  4504. },
  4505. _getOwner: function() {
  4506. return this._parent || this._index != null && this._project;
  4507. },
  4508. isInserted: function isInserted() {
  4509. return this._parent ? isInserted.base.call(this) : this._index != null;
  4510. },
  4511. activate: function() {
  4512. this._project._activeLayer = this;
  4513. },
  4514. _hitTestSelf: function() {
  4515. }
  4516. });
  4517. var Shape = Item.extend({
  4518. _class: 'Shape',
  4519. _applyMatrix: false,
  4520. _canApplyMatrix: false,
  4521. _canScaleStroke: true,
  4522. _serializeFields: {
  4523. type: null,
  4524. size: null,
  4525. radius: null
  4526. },
  4527. initialize: function Shape(props, point) {
  4528. this._initialize(props, point);
  4529. },
  4530. _equals: function(item) {
  4531. return this._type === item._type
  4532. && this._size.equals(item._size)
  4533. && Base.equals(this._radius, item._radius);
  4534. },
  4535. copyContent: function(source) {
  4536. this.setType(source._type);
  4537. this.setSize(source._size);
  4538. this.setRadius(source._radius);
  4539. },
  4540. getType: function() {
  4541. return this._type;
  4542. },
  4543. setType: function(type) {
  4544. this._type = type;
  4545. },
  4546. getShape: '#getType',
  4547. setShape: '#setType',
  4548. getSize: function() {
  4549. var size = this._size;
  4550. return new LinkedSize(size.width, size.height, this, 'setSize');
  4551. },
  4552. setSize: function() {
  4553. var size = Size.read(arguments);
  4554. if (!this._size) {
  4555. this._size = size.clone();
  4556. } else if (!this._size.equals(size)) {
  4557. var type = this._type,
  4558. width = size.width,
  4559. height = size.height;
  4560. if (type === 'rectangle') {
  4561. this._radius.set(Size.min(this._radius, size.divide(2).abs()));
  4562. } else if (type === 'circle') {
  4563. width = height = (width + height) / 2;
  4564. this._radius = width / 2;
  4565. } else if (type === 'ellipse') {
  4566. this._radius._set(width / 2, height / 2);
  4567. }
  4568. this._size._set(width, height);
  4569. this._changed(9);
  4570. }
  4571. },
  4572. getRadius: function() {
  4573. var rad = this._radius;
  4574. return this._type === 'circle'
  4575. ? rad
  4576. : new LinkedSize(rad.width, rad.height, this, 'setRadius');
  4577. },
  4578. setRadius: function(radius) {
  4579. var type = this._type;
  4580. if (type === 'circle') {
  4581. if (radius === this._radius)
  4582. return;
  4583. var size = radius * 2;
  4584. this._radius = radius;
  4585. this._size._set(size, size);
  4586. } else {
  4587. radius = Size.read(arguments);
  4588. if (!this._radius) {
  4589. this._radius = radius.clone();
  4590. } else {
  4591. if (this._radius.equals(radius))
  4592. return;
  4593. this._radius.set(radius);
  4594. if (type === 'rectangle') {
  4595. var size = Size.max(this._size, radius.multiply(2));
  4596. this._size.set(size);
  4597. } else if (type === 'ellipse') {
  4598. this._size._set(radius.width * 2, radius.height * 2);
  4599. }
  4600. }
  4601. }
  4602. this._changed(9);
  4603. },
  4604. isEmpty: function() {
  4605. return false;
  4606. },
  4607. toPath: function(insert) {
  4608. var path = new Path[Base.capitalize(this._type)]({
  4609. center: new Point(),
  4610. size: this._size,
  4611. radius: this._radius,
  4612. insert: false
  4613. });
  4614. path.copyAttributes(this);
  4615. if (paper.settings.applyMatrix)
  4616. path.setApplyMatrix(true);
  4617. if (insert === undefined || insert)
  4618. path.insertAbove(this);
  4619. return path;
  4620. },
  4621. toShape: '#clone',
  4622. _asPathItem: function() {
  4623. return this.toPath(false);
  4624. },
  4625. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  4626. var style = this._style,
  4627. hasFill = style.hasFill(),
  4628. hasStroke = style.hasStroke(),
  4629. dontPaint = param.dontFinish || param.clip,
  4630. untransformed = !strokeMatrix;
  4631. if (hasFill || hasStroke || dontPaint) {
  4632. var type = this._type,
  4633. radius = this._radius,
  4634. isCircle = type === 'circle';
  4635. if (!param.dontStart)
  4636. ctx.beginPath();
  4637. if (untransformed && isCircle) {
  4638. ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
  4639. } else {
  4640. var rx = isCircle ? radius : radius.width,
  4641. ry = isCircle ? radius : radius.height,
  4642. size = this._size,
  4643. width = size.width,
  4644. height = size.height;
  4645. if (untransformed && type === 'rectangle' && rx === 0 && ry === 0) {
  4646. ctx.rect(-width / 2, -height / 2, width, height);
  4647. } else {
  4648. var x = width / 2,
  4649. y = height / 2,
  4650. kappa = 1 - 0.5522847498307936,
  4651. cx = rx * kappa,
  4652. cy = ry * kappa,
  4653. c = [
  4654. -x, -y + ry,
  4655. -x, -y + cy,
  4656. -x + cx, -y,
  4657. -x + rx, -y,
  4658. x - rx, -y,
  4659. x - cx, -y,
  4660. x, -y + cy,
  4661. x, -y + ry,
  4662. x, y - ry,
  4663. x, y - cy,
  4664. x - cx, y,
  4665. x - rx, y,
  4666. -x + rx, y,
  4667. -x + cx, y,
  4668. -x, y - cy,
  4669. -x, y - ry
  4670. ];
  4671. if (strokeMatrix)
  4672. strokeMatrix.transform(c, c, 32);
  4673. ctx.moveTo(c[0], c[1]);
  4674. ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]);
  4675. if (x !== rx)
  4676. ctx.lineTo(c[8], c[9]);
  4677. ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]);
  4678. if (y !== ry)
  4679. ctx.lineTo(c[16], c[17]);
  4680. ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]);
  4681. if (x !== rx)
  4682. ctx.lineTo(c[24], c[25]);
  4683. ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]);
  4684. }
  4685. }
  4686. ctx.closePath();
  4687. }
  4688. if (!dontPaint && (hasFill || hasStroke)) {
  4689. this._setStyles(ctx, param, viewMatrix);
  4690. if (hasFill) {
  4691. ctx.fill(style.getFillRule());
  4692. ctx.shadowColor = 'rgba(0,0,0,0)';
  4693. }
  4694. if (hasStroke)
  4695. ctx.stroke();
  4696. }
  4697. },
  4698. _canComposite: function() {
  4699. return !(this.hasFill() && this.hasStroke());
  4700. },
  4701. _getBounds: function(matrix, options) {
  4702. var rect = new Rectangle(this._size).setCenter(0, 0),
  4703. style = this._style,
  4704. strokeWidth = options.stroke && style.hasStroke()
  4705. && style.getStrokeWidth();
  4706. if (matrix)
  4707. rect = matrix._transformBounds(rect);
  4708. return strokeWidth
  4709. ? rect.expand(Path._getStrokePadding(strokeWidth,
  4710. this._getStrokeMatrix(matrix, options)))
  4711. : rect;
  4712. }
  4713. },
  4714. new function() {
  4715. function getCornerCenter(that, point, expand) {
  4716. var radius = that._radius;
  4717. if (!radius.isZero()) {
  4718. var halfSize = that._size.divide(2);
  4719. for (var q = 1; q <= 4; q++) {
  4720. var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1),
  4721. corner = dir.multiply(halfSize),
  4722. center = corner.subtract(dir.multiply(radius)),
  4723. rect = new Rectangle(
  4724. expand ? corner.add(dir.multiply(expand)) : corner,
  4725. center);
  4726. if (rect.contains(point))
  4727. return { point: center, quadrant: q };
  4728. }
  4729. }
  4730. }
  4731. function isOnEllipseStroke(point, radius, padding, quadrant) {
  4732. var vector = point.divide(radius);
  4733. return (!quadrant || vector.isInQuadrant(quadrant)) &&
  4734. vector.subtract(vector.normalize()).multiply(radius)
  4735. .divide(padding).length <= 1;
  4736. }
  4737. return {
  4738. _contains: function _contains(point) {
  4739. if (this._type === 'rectangle') {
  4740. var center = getCornerCenter(this, point);
  4741. return center
  4742. ? point.subtract(center.point).divide(this._radius)
  4743. .getLength() <= 1
  4744. : _contains.base.call(this, point);
  4745. } else {
  4746. return point.divide(this.size).getLength() <= 0.5;
  4747. }
  4748. },
  4749. _hitTestSelf: function _hitTestSelf(point, options, viewMatrix,
  4750. strokeMatrix) {
  4751. var hit = false,
  4752. style = this._style,
  4753. hitStroke = options.stroke && style.hasStroke(),
  4754. hitFill = options.fill && style.hasFill();
  4755. if (hitStroke || hitFill) {
  4756. var type = this._type,
  4757. radius = this._radius,
  4758. strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0,
  4759. strokePadding = options._tolerancePadding.add(
  4760. Path._getStrokePadding(strokeRadius,
  4761. !style.getStrokeScaling() && strokeMatrix));
  4762. if (type === 'rectangle') {
  4763. var padding = strokePadding.multiply(2),
  4764. center = getCornerCenter(this, point, padding);
  4765. if (center) {
  4766. hit = isOnEllipseStroke(point.subtract(center.point),
  4767. radius, strokePadding, center.quadrant);
  4768. } else {
  4769. var rect = new Rectangle(this._size).setCenter(0, 0),
  4770. outer = rect.expand(padding),
  4771. inner = rect.expand(padding.negate());
  4772. hit = outer._containsPoint(point)
  4773. && !inner._containsPoint(point);
  4774. }
  4775. } else {
  4776. hit = isOnEllipseStroke(point, radius, strokePadding);
  4777. }
  4778. }
  4779. return hit ? new HitResult(hitStroke ? 'stroke' : 'fill', this)
  4780. : _hitTestSelf.base.apply(this, arguments);
  4781. }
  4782. };
  4783. }, {
  4784. statics: new function() {
  4785. function createShape(type, point, size, radius, args) {
  4786. var item = Base.create(Shape.prototype);
  4787. item._type = type;
  4788. item._size = size;
  4789. item._radius = radius;
  4790. item._initialize(Base.getNamed(args), point);
  4791. return item;
  4792. }
  4793. return {
  4794. Circle: function() {
  4795. var args = arguments,
  4796. center = Point.readNamed(args, 'center'),
  4797. radius = Base.readNamed(args, 'radius');
  4798. return createShape('circle', center, new Size(radius * 2), radius,
  4799. args);
  4800. },
  4801. Rectangle: function() {
  4802. var args = arguments,
  4803. rect = Rectangle.readNamed(args, 'rectangle'),
  4804. radius = Size.min(Size.readNamed(args, 'radius'),
  4805. rect.getSize(true).divide(2));
  4806. return createShape('rectangle', rect.getCenter(true),
  4807. rect.getSize(true), radius, args);
  4808. },
  4809. Ellipse: function() {
  4810. var args = arguments,
  4811. ellipse = Shape._readEllipse(args),
  4812. radius = ellipse.radius;
  4813. return createShape('ellipse', ellipse.center, radius.multiply(2),
  4814. radius, args);
  4815. },
  4816. _readEllipse: function(args) {
  4817. var center,
  4818. radius;
  4819. if (Base.hasNamed(args, 'radius')) {
  4820. center = Point.readNamed(args, 'center');
  4821. radius = Size.readNamed(args, 'radius');
  4822. } else {
  4823. var rect = Rectangle.readNamed(args, 'rectangle');
  4824. center = rect.getCenter(true);
  4825. radius = rect.getSize(true).divide(2);
  4826. }
  4827. return { center: center, radius: radius };
  4828. }
  4829. };
  4830. }});
  4831. var Raster = Item.extend({
  4832. _class: 'Raster',
  4833. _applyMatrix: false,
  4834. _canApplyMatrix: false,
  4835. _boundsOptions: { stroke: false, handle: false },
  4836. _serializeFields: {
  4837. crossOrigin: null,
  4838. source: null
  4839. },
  4840. _prioritize: ['crossOrigin'],
  4841. _smoothing: 'low',
  4842. beans: true,
  4843. initialize: function Raster(source, position) {
  4844. if (!this._initialize(source,
  4845. position !== undefined && Point.read(arguments))) {
  4846. var image,
  4847. type = typeof source,
  4848. object = type === 'string'
  4849. ? document.getElementById(source)
  4850. : type === 'object'
  4851. ? source
  4852. : null;
  4853. if (object && object !== Item.NO_INSERT) {
  4854. if (object.getContext || object.naturalHeight != null) {
  4855. image = object;
  4856. } else if (object) {
  4857. var size = Size.read(arguments);
  4858. if (!size.isZero()) {
  4859. image = CanvasProvider.getCanvas(size);
  4860. }
  4861. }
  4862. }
  4863. if (image) {
  4864. this.setImage(image);
  4865. } else {
  4866. this.setSource(source);
  4867. }
  4868. }
  4869. if (!this._size) {
  4870. this._size = new Size();
  4871. this._loaded = false;
  4872. }
  4873. },
  4874. _equals: function(item) {
  4875. return this.getSource() === item.getSource();
  4876. },
  4877. copyContent: function(source) {
  4878. var image = source._image,
  4879. canvas = source._canvas;
  4880. if (image) {
  4881. this._setImage(image);
  4882. } else if (canvas) {
  4883. var copyCanvas = CanvasProvider.getCanvas(source._size);
  4884. copyCanvas.getContext('2d').drawImage(canvas, 0, 0);
  4885. this._setImage(copyCanvas);
  4886. }
  4887. this._crossOrigin = source._crossOrigin;
  4888. },
  4889. getSize: function() {
  4890. var size = this._size;
  4891. return new LinkedSize(size ? size.width : 0, size ? size.height : 0,
  4892. this, 'setSize');
  4893. },
  4894. setSize: function(_size, _clear) {
  4895. var size = Size.read(arguments);
  4896. if (!size.equals(this._size)) {
  4897. if (size.width > 0 && size.height > 0) {
  4898. var element = !_clear && this.getElement();
  4899. this._setImage(CanvasProvider.getCanvas(size));
  4900. if (element) {
  4901. this.getContext(true).drawImage(element, 0, 0,
  4902. size.width, size.height);
  4903. }
  4904. } else {
  4905. if (this._canvas)
  4906. CanvasProvider.release(this._canvas);
  4907. this._size = size.clone();
  4908. }
  4909. } else if (_clear) {
  4910. this.clear();
  4911. }
  4912. },
  4913. getWidth: function() {
  4914. return this._size ? this._size.width : 0;
  4915. },
  4916. setWidth: function(width) {
  4917. this.setSize(width, this.getHeight());
  4918. },
  4919. getHeight: function() {
  4920. return this._size ? this._size.height : 0;
  4921. },
  4922. setHeight: function(height) {
  4923. this.setSize(this.getWidth(), height);
  4924. },
  4925. getLoaded: function() {
  4926. return this._loaded;
  4927. },
  4928. isEmpty: function() {
  4929. var size = this._size;
  4930. return !size || size.width === 0 && size.height === 0;
  4931. },
  4932. getResolution: function() {
  4933. var matrix = this._matrix,
  4934. orig = new Point(0, 0).transform(matrix),
  4935. u = new Point(1, 0).transform(matrix).subtract(orig),
  4936. v = new Point(0, 1).transform(matrix).subtract(orig);
  4937. return new Size(
  4938. 72 / u.getLength(),
  4939. 72 / v.getLength()
  4940. );
  4941. },
  4942. getPpi: '#getResolution',
  4943. getImage: function() {
  4944. return this._image;
  4945. },
  4946. setImage: function(image) {
  4947. var that = this;
  4948. function emit(event) {
  4949. var view = that.getView(),
  4950. type = event && event.type || 'load';
  4951. if (view && that.responds(type)) {
  4952. paper = view._scope;
  4953. that.emit(type, new Event(event));
  4954. }
  4955. }
  4956. this._setImage(image);
  4957. if (this._loaded) {
  4958. setTimeout(emit, 0);
  4959. } else if (image) {
  4960. DomEvent.add(image, {
  4961. load: function(event) {
  4962. that._setImage(image);
  4963. emit(event);
  4964. },
  4965. error: emit
  4966. });
  4967. }
  4968. },
  4969. _setImage: function(image) {
  4970. if (this._canvas)
  4971. CanvasProvider.release(this._canvas);
  4972. if (image && image.getContext) {
  4973. this._image = null;
  4974. this._canvas = image;
  4975. this._loaded = true;
  4976. } else {
  4977. this._image = image;
  4978. this._canvas = null;
  4979. this._loaded = !!(image && image.src && image.complete);
  4980. }
  4981. this._size = new Size(
  4982. image ? image.naturalWidth || image.width : 0,
  4983. image ? image.naturalHeight || image.height : 0);
  4984. this._context = null;
  4985. this._changed(1033);
  4986. },
  4987. getCanvas: function() {
  4988. if (!this._canvas) {
  4989. var ctx = CanvasProvider.getContext(this._size);
  4990. try {
  4991. if (this._image)
  4992. ctx.drawImage(this._image, 0, 0);
  4993. this._canvas = ctx.canvas;
  4994. } catch (e) {
  4995. CanvasProvider.release(ctx);
  4996. }
  4997. }
  4998. return this._canvas;
  4999. },
  5000. setCanvas: '#setImage',
  5001. getContext: function(_change) {
  5002. if (!this._context)
  5003. this._context = this.getCanvas().getContext('2d');
  5004. if (_change) {
  5005. this._image = null;
  5006. this._changed(1025);
  5007. }
  5008. return this._context;
  5009. },
  5010. setContext: function(context) {
  5011. this._context = context;
  5012. },
  5013. getSource: function() {
  5014. var image = this._image;
  5015. return image && image.src || this.toDataURL();
  5016. },
  5017. setSource: function(src) {
  5018. var image = new self.Image(),
  5019. crossOrigin = this._crossOrigin;
  5020. if (crossOrigin)
  5021. image.crossOrigin = crossOrigin;
  5022. if (src)
  5023. image.src = src;
  5024. this.setImage(image);
  5025. },
  5026. getCrossOrigin: function() {
  5027. var image = this._image;
  5028. return image && image.crossOrigin || this._crossOrigin || '';
  5029. },
  5030. setCrossOrigin: function(crossOrigin) {
  5031. this._crossOrigin = crossOrigin;
  5032. var image = this._image;
  5033. if (image)
  5034. image.crossOrigin = crossOrigin;
  5035. },
  5036. getSmoothing: function() {
  5037. return this._smoothing;
  5038. },
  5039. setSmoothing: function(smoothing) {
  5040. this._smoothing = typeof smoothing === 'string'
  5041. ? smoothing
  5042. : smoothing ? 'low' : 'off';
  5043. this._changed(257);
  5044. },
  5045. getElement: function() {
  5046. return this._canvas || this._loaded && this._image;
  5047. }
  5048. }, {
  5049. beans: false,
  5050. getSubCanvas: function() {
  5051. var rect = Rectangle.read(arguments),
  5052. ctx = CanvasProvider.getContext(rect.getSize());
  5053. ctx.drawImage(this.getCanvas(), rect.x, rect.y,
  5054. rect.width, rect.height, 0, 0, rect.width, rect.height);
  5055. return ctx.canvas;
  5056. },
  5057. getSubRaster: function() {
  5058. var rect = Rectangle.read(arguments),
  5059. raster = new Raster(Item.NO_INSERT);
  5060. raster._setImage(this.getSubCanvas(rect));
  5061. raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
  5062. raster._matrix.prepend(this._matrix);
  5063. raster.insertAbove(this);
  5064. return raster;
  5065. },
  5066. toDataURL: function() {
  5067. var image = this._image,
  5068. src = image && image.src;
  5069. if (/^data:/.test(src))
  5070. return src;
  5071. var canvas = this.getCanvas();
  5072. return canvas ? canvas.toDataURL.apply(canvas, arguments) : null;
  5073. },
  5074. drawImage: function(image ) {
  5075. var point = Point.read(arguments, 1);
  5076. this.getContext(true).drawImage(image, point.x, point.y);
  5077. },
  5078. getAverageColor: function(object) {
  5079. var bounds, path;
  5080. if (!object) {
  5081. bounds = this.getBounds();
  5082. } else if (object instanceof PathItem) {
  5083. path = object;
  5084. bounds = object.getBounds();
  5085. } else if (typeof object === 'object') {
  5086. if ('width' in object) {
  5087. bounds = new Rectangle(object);
  5088. } else if ('x' in object) {
  5089. bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
  5090. }
  5091. }
  5092. if (!bounds)
  5093. return null;
  5094. var sampleSize = 32,
  5095. width = Math.min(bounds.width, sampleSize),
  5096. height = Math.min(bounds.height, sampleSize);
  5097. var ctx = Raster._sampleContext;
  5098. if (!ctx) {
  5099. ctx = Raster._sampleContext = CanvasProvider.getContext(
  5100. new Size(sampleSize));
  5101. } else {
  5102. ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
  5103. }
  5104. ctx.save();
  5105. var matrix = new Matrix()
  5106. .scale(width / bounds.width, height / bounds.height)
  5107. .translate(-bounds.x, -bounds.y);
  5108. matrix.applyToContext(ctx);
  5109. if (path)
  5110. path.draw(ctx, new Base({ clip: true, matrices: [matrix] }));
  5111. this._matrix.applyToContext(ctx);
  5112. var element = this.getElement(),
  5113. size = this._size;
  5114. if (element)
  5115. ctx.drawImage(element, -size.width / 2, -size.height / 2);
  5116. ctx.restore();
  5117. var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
  5118. Math.ceil(height)).data,
  5119. channels = [0, 0, 0],
  5120. total = 0;
  5121. for (var i = 0, l = pixels.length; i < l; i += 4) {
  5122. var alpha = pixels[i + 3];
  5123. total += alpha;
  5124. alpha /= 255;
  5125. channels[0] += pixels[i] * alpha;
  5126. channels[1] += pixels[i + 1] * alpha;
  5127. channels[2] += pixels[i + 2] * alpha;
  5128. }
  5129. for (var i = 0; i < 3; i++)
  5130. channels[i] /= total;
  5131. return total ? Color.read(channels) : null;
  5132. },
  5133. getPixel: function() {
  5134. var point = Point.read(arguments);
  5135. var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
  5136. return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
  5137. data[3] / 255);
  5138. },
  5139. setPixel: function() {
  5140. var args = arguments,
  5141. point = Point.read(args),
  5142. color = Color.read(args),
  5143. components = color._convert('rgb'),
  5144. alpha = color._alpha,
  5145. ctx = this.getContext(true),
  5146. imageData = ctx.createImageData(1, 1),
  5147. data = imageData.data;
  5148. data[0] = components[0] * 255;
  5149. data[1] = components[1] * 255;
  5150. data[2] = components[2] * 255;
  5151. data[3] = alpha != null ? alpha * 255 : 255;
  5152. ctx.putImageData(imageData, point.x, point.y);
  5153. },
  5154. clear: function() {
  5155. var size = this._size;
  5156. this.getContext(true).clearRect(0, 0, size.width + 1, size.height + 1);
  5157. },
  5158. createImageData: function() {
  5159. var size = Size.read(arguments);
  5160. return this.getContext().createImageData(size.width, size.height);
  5161. },
  5162. getImageData: function() {
  5163. var rect = Rectangle.read(arguments);
  5164. if (rect.isEmpty())
  5165. rect = new Rectangle(this._size);
  5166. return this.getContext().getImageData(rect.x, rect.y,
  5167. rect.width, rect.height);
  5168. },
  5169. setImageData: function(data ) {
  5170. var point = Point.read(arguments, 1);
  5171. this.getContext(true).putImageData(data, point.x, point.y);
  5172. },
  5173. _getBounds: function(matrix, options) {
  5174. var rect = new Rectangle(this._size).setCenter(0, 0);
  5175. return matrix ? matrix._transformBounds(rect) : rect;
  5176. },
  5177. _hitTestSelf: function(point) {
  5178. if (this._contains(point)) {
  5179. var that = this;
  5180. return new HitResult('pixel', that, {
  5181. offset: point.add(that._size.divide(2)).round(),
  5182. color: {
  5183. get: function() {
  5184. return that.getPixel(this.offset);
  5185. }
  5186. }
  5187. });
  5188. }
  5189. },
  5190. _draw: function(ctx, param, viewMatrix) {
  5191. var element = this.getElement();
  5192. if (element && element.width > 0 && element.height > 0) {
  5193. ctx.globalAlpha = Numerical.clamp(this._opacity, 0, 1);
  5194. this._setStyles(ctx, param, viewMatrix);
  5195. var smoothing = this._smoothing,
  5196. disabled = smoothing === 'off';
  5197. DomElement.setPrefixed(
  5198. ctx,
  5199. disabled ? 'imageSmoothingEnabled' : 'imageSmoothingQuality',
  5200. disabled ? false : smoothing
  5201. );
  5202. ctx.drawImage(element,
  5203. -this._size.width / 2, -this._size.height / 2);
  5204. }
  5205. },
  5206. _canComposite: function() {
  5207. return true;
  5208. }
  5209. });
  5210. var SymbolItem = Item.extend({
  5211. _class: 'SymbolItem',
  5212. _applyMatrix: false,
  5213. _canApplyMatrix: false,
  5214. _boundsOptions: { stroke: true },
  5215. _serializeFields: {
  5216. symbol: null
  5217. },
  5218. initialize: function SymbolItem(arg0, arg1) {
  5219. if (!this._initialize(arg0,
  5220. arg1 !== undefined && Point.read(arguments, 1)))
  5221. this.setDefinition(arg0 instanceof SymbolDefinition ?
  5222. arg0 : new SymbolDefinition(arg0));
  5223. },
  5224. _equals: function(item) {
  5225. return this._definition === item._definition;
  5226. },
  5227. copyContent: function(source) {
  5228. this.setDefinition(source._definition);
  5229. },
  5230. getDefinition: function() {
  5231. return this._definition;
  5232. },
  5233. setDefinition: function(definition) {
  5234. this._definition = definition;
  5235. this._changed(9);
  5236. },
  5237. getSymbol: '#getDefinition',
  5238. setSymbol: '#setDefinition',
  5239. isEmpty: function() {
  5240. return this._definition._item.isEmpty();
  5241. },
  5242. _getBounds: function(matrix, options) {
  5243. var item = this._definition._item;
  5244. return item._getCachedBounds(item._matrix.prepended(matrix), options);
  5245. },
  5246. _hitTestSelf: function(point, options, viewMatrix) {
  5247. var opts = options.extend({ all: false });
  5248. var res = this._definition._item._hitTest(point, opts, viewMatrix);
  5249. if (res)
  5250. res.item = this;
  5251. return res;
  5252. },
  5253. _draw: function(ctx, param) {
  5254. this._definition._item.draw(ctx, param);
  5255. }
  5256. });
  5257. var SymbolDefinition = Base.extend({
  5258. _class: 'SymbolDefinition',
  5259. initialize: function SymbolDefinition(item, dontCenter) {
  5260. this._id = UID.get();
  5261. this.project = paper.project;
  5262. if (item)
  5263. this.setItem(item, dontCenter);
  5264. },
  5265. _serialize: function(options, dictionary) {
  5266. return dictionary.add(this, function() {
  5267. return Base.serialize([this._class, this._item],
  5268. options, false, dictionary);
  5269. });
  5270. },
  5271. _changed: function(flags) {
  5272. if (flags & 8)
  5273. Item._clearBoundsCache(this);
  5274. if (flags & 1)
  5275. this.project._changed(flags);
  5276. },
  5277. getItem: function() {
  5278. return this._item;
  5279. },
  5280. setItem: function(item, _dontCenter) {
  5281. if (item._symbol)
  5282. item = item.clone();
  5283. if (this._item)
  5284. this._item._symbol = null;
  5285. this._item = item;
  5286. item.remove();
  5287. item.setSelected(false);
  5288. if (!_dontCenter)
  5289. item.setPosition(new Point());
  5290. item._symbol = this;
  5291. this._changed(9);
  5292. },
  5293. getDefinition: '#getItem',
  5294. setDefinition: '#setItem',
  5295. place: function(position) {
  5296. return new SymbolItem(this, position);
  5297. },
  5298. clone: function() {
  5299. return new SymbolDefinition(this._item.clone(false));
  5300. },
  5301. equals: function(symbol) {
  5302. return symbol === this
  5303. || symbol && this._item.equals(symbol._item)
  5304. || false;
  5305. }
  5306. });
  5307. var HitResult = Base.extend({
  5308. _class: 'HitResult',
  5309. initialize: function HitResult(type, item, values) {
  5310. this.type = type;
  5311. this.item = item;
  5312. if (values)
  5313. this.inject(values);
  5314. },
  5315. statics: {
  5316. getOptions: function(args) {
  5317. var options = args && Base.read(args);
  5318. return new Base({
  5319. type: null,
  5320. tolerance: paper.settings.hitTolerance,
  5321. fill: !options,
  5322. stroke: !options,
  5323. segments: !options,
  5324. handles: false,
  5325. ends: false,
  5326. position: false,
  5327. center: false,
  5328. bounds: false,
  5329. guides: false,
  5330. selected: false
  5331. }, options);
  5332. }
  5333. }
  5334. });
  5335. var Segment = Base.extend({
  5336. _class: 'Segment',
  5337. beans: true,
  5338. _selection: 0,
  5339. initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
  5340. var count = arguments.length,
  5341. point, handleIn, handleOut, selection;
  5342. if (count > 0) {
  5343. if (arg0 == null || typeof arg0 === 'object') {
  5344. if (count === 1 && arg0 && 'point' in arg0) {
  5345. point = arg0.point;
  5346. handleIn = arg0.handleIn;
  5347. handleOut = arg0.handleOut;
  5348. selection = arg0.selection;
  5349. } else {
  5350. point = arg0;
  5351. handleIn = arg1;
  5352. handleOut = arg2;
  5353. selection = arg3;
  5354. }
  5355. } else {
  5356. point = [ arg0, arg1 ];
  5357. handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
  5358. handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
  5359. }
  5360. }
  5361. new SegmentPoint(point, this, '_point');
  5362. new SegmentPoint(handleIn, this, '_handleIn');
  5363. new SegmentPoint(handleOut, this, '_handleOut');
  5364. if (selection)
  5365. this.setSelection(selection);
  5366. },
  5367. _serialize: function(options, dictionary) {
  5368. var point = this._point,
  5369. selection = this._selection,
  5370. obj = selection || this.hasHandles()
  5371. ? [point, this._handleIn, this._handleOut]
  5372. : point;
  5373. if (selection)
  5374. obj.push(selection);
  5375. return Base.serialize(obj, options, true, dictionary);
  5376. },
  5377. _changed: function(point) {
  5378. var path = this._path;
  5379. if (!path)
  5380. return;
  5381. var curves = path._curves,
  5382. index = this._index,
  5383. curve;
  5384. if (curves) {
  5385. if ((!point || point === this._point || point === this._handleIn)
  5386. && (curve = index > 0 ? curves[index - 1] : path._closed
  5387. ? curves[curves.length - 1] : null))
  5388. curve._changed();
  5389. if ((!point || point === this._point || point === this._handleOut)
  5390. && (curve = curves[index]))
  5391. curve._changed();
  5392. }
  5393. path._changed(41);
  5394. },
  5395. getPoint: function() {
  5396. return this._point;
  5397. },
  5398. setPoint: function() {
  5399. this._point.set(Point.read(arguments));
  5400. },
  5401. getHandleIn: function() {
  5402. return this._handleIn;
  5403. },
  5404. setHandleIn: function() {
  5405. this._handleIn.set(Point.read(arguments));
  5406. },
  5407. getHandleOut: function() {
  5408. return this._handleOut;
  5409. },
  5410. setHandleOut: function() {
  5411. this._handleOut.set(Point.read(arguments));
  5412. },
  5413. hasHandles: function() {
  5414. return !this._handleIn.isZero() || !this._handleOut.isZero();
  5415. },
  5416. isSmooth: function() {
  5417. var handleIn = this._handleIn,
  5418. handleOut = this._handleOut;
  5419. return !handleIn.isZero() && !handleOut.isZero()
  5420. && handleIn.isCollinear(handleOut);
  5421. },
  5422. clearHandles: function() {
  5423. this._handleIn._set(0, 0);
  5424. this._handleOut._set(0, 0);
  5425. },
  5426. getSelection: function() {
  5427. return this._selection;
  5428. },
  5429. setSelection: function(selection) {
  5430. var oldSelection = this._selection,
  5431. path = this._path;
  5432. this._selection = selection = selection || 0;
  5433. if (path && selection !== oldSelection) {
  5434. path._updateSelection(this, oldSelection, selection);
  5435. path._changed(257);
  5436. }
  5437. },
  5438. _changeSelection: function(flag, selected) {
  5439. var selection = this._selection;
  5440. this.setSelection(selected ? selection | flag : selection & ~flag);
  5441. },
  5442. isSelected: function() {
  5443. return !!(this._selection & 7);
  5444. },
  5445. setSelected: function(selected) {
  5446. this._changeSelection(7, selected);
  5447. },
  5448. getIndex: function() {
  5449. return this._index !== undefined ? this._index : null;
  5450. },
  5451. getPath: function() {
  5452. return this._path || null;
  5453. },
  5454. getCurve: function() {
  5455. var path = this._path,
  5456. index = this._index;
  5457. if (path) {
  5458. if (index > 0 && !path._closed
  5459. && index === path._segments.length - 1)
  5460. index--;
  5461. return path.getCurves()[index] || null;
  5462. }
  5463. return null;
  5464. },
  5465. getLocation: function() {
  5466. var curve = this.getCurve();
  5467. return curve
  5468. ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)
  5469. : null;
  5470. },
  5471. getNext: function() {
  5472. var segments = this._path && this._path._segments;
  5473. return segments && (segments[this._index + 1]
  5474. || this._path._closed && segments[0]) || null;
  5475. },
  5476. smooth: function(options, _first, _last) {
  5477. var opts = options || {},
  5478. type = opts.type,
  5479. factor = opts.factor,
  5480. prev = this.getPrevious(),
  5481. next = this.getNext(),
  5482. p0 = (prev || this)._point,
  5483. p1 = this._point,
  5484. p2 = (next || this)._point,
  5485. d1 = p0.getDistance(p1),
  5486. d2 = p1.getDistance(p2);
  5487. if (!type || type === 'catmull-rom') {
  5488. var a = factor === undefined ? 0.5 : factor,
  5489. d1_a = Math.pow(d1, a),
  5490. d1_2a = d1_a * d1_a,
  5491. d2_a = Math.pow(d2, a),
  5492. d2_2a = d2_a * d2_a;
  5493. if (!_first && prev) {
  5494. var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a,
  5495. N = 3 * d2_a * (d2_a + d1_a);
  5496. this.setHandleIn(N !== 0
  5497. ? new Point(
  5498. (d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x,
  5499. (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y)
  5500. : new Point());
  5501. }
  5502. if (!_last && next) {
  5503. var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a,
  5504. N = 3 * d1_a * (d1_a + d2_a);
  5505. this.setHandleOut(N !== 0
  5506. ? new Point(
  5507. (d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x,
  5508. (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y)
  5509. : new Point());
  5510. }
  5511. } else if (type === 'geometric') {
  5512. if (prev && next) {
  5513. var vector = p0.subtract(p2),
  5514. t = factor === undefined ? 0.4 : factor,
  5515. k = t * d1 / (d1 + d2);
  5516. if (!_first)
  5517. this.setHandleIn(vector.multiply(k));
  5518. if (!_last)
  5519. this.setHandleOut(vector.multiply(k - t));
  5520. }
  5521. } else {
  5522. throw new Error('Smoothing method \'' + type + '\' not supported.');
  5523. }
  5524. },
  5525. getPrevious: function() {
  5526. var segments = this._path && this._path._segments;
  5527. return segments && (segments[this._index - 1]
  5528. || this._path._closed && segments[segments.length - 1]) || null;
  5529. },
  5530. isFirst: function() {
  5531. return !this._index;
  5532. },
  5533. isLast: function() {
  5534. var path = this._path;
  5535. return path && this._index === path._segments.length - 1 || false;
  5536. },
  5537. reverse: function() {
  5538. var handleIn = this._handleIn,
  5539. handleOut = this._handleOut,
  5540. tmp = handleIn.clone();
  5541. handleIn.set(handleOut);
  5542. handleOut.set(tmp);
  5543. },
  5544. reversed: function() {
  5545. return new Segment(this._point, this._handleOut, this._handleIn);
  5546. },
  5547. remove: function() {
  5548. return this._path ? !!this._path.removeSegment(this._index) : false;
  5549. },
  5550. clone: function() {
  5551. return new Segment(this._point, this._handleIn, this._handleOut);
  5552. },
  5553. equals: function(segment) {
  5554. return segment === this || segment && this._class === segment._class
  5555. && this._point.equals(segment._point)
  5556. && this._handleIn.equals(segment._handleIn)
  5557. && this._handleOut.equals(segment._handleOut)
  5558. || false;
  5559. },
  5560. toString: function() {
  5561. var parts = [ 'point: ' + this._point ];
  5562. if (!this._handleIn.isZero())
  5563. parts.push('handleIn: ' + this._handleIn);
  5564. if (!this._handleOut.isZero())
  5565. parts.push('handleOut: ' + this._handleOut);
  5566. return '{ ' + parts.join(', ') + ' }';
  5567. },
  5568. transform: function(matrix) {
  5569. this._transformCoordinates(matrix, new Array(6), true);
  5570. this._changed();
  5571. },
  5572. interpolate: function(from, to, factor) {
  5573. var u = 1 - factor,
  5574. v = factor,
  5575. point1 = from._point,
  5576. point2 = to._point,
  5577. handleIn1 = from._handleIn,
  5578. handleIn2 = to._handleIn,
  5579. handleOut2 = to._handleOut,
  5580. handleOut1 = from._handleOut;
  5581. this._point._set(
  5582. u * point1._x + v * point2._x,
  5583. u * point1._y + v * point2._y, true);
  5584. this._handleIn._set(
  5585. u * handleIn1._x + v * handleIn2._x,
  5586. u * handleIn1._y + v * handleIn2._y, true);
  5587. this._handleOut._set(
  5588. u * handleOut1._x + v * handleOut2._x,
  5589. u * handleOut1._y + v * handleOut2._y, true);
  5590. this._changed();
  5591. },
  5592. _transformCoordinates: function(matrix, coords, change) {
  5593. var point = this._point,
  5594. handleIn = !change || !this._handleIn.isZero()
  5595. ? this._handleIn : null,
  5596. handleOut = !change || !this._handleOut.isZero()
  5597. ? this._handleOut : null,
  5598. x = point._x,
  5599. y = point._y,
  5600. i = 2;
  5601. coords[0] = x;
  5602. coords[1] = y;
  5603. if (handleIn) {
  5604. coords[i++] = handleIn._x + x;
  5605. coords[i++] = handleIn._y + y;
  5606. }
  5607. if (handleOut) {
  5608. coords[i++] = handleOut._x + x;
  5609. coords[i++] = handleOut._y + y;
  5610. }
  5611. if (matrix) {
  5612. matrix._transformCoordinates(coords, coords, i / 2);
  5613. x = coords[0];
  5614. y = coords[1];
  5615. if (change) {
  5616. point._x = x;
  5617. point._y = y;
  5618. i = 2;
  5619. if (handleIn) {
  5620. handleIn._x = coords[i++] - x;
  5621. handleIn._y = coords[i++] - y;
  5622. }
  5623. if (handleOut) {
  5624. handleOut._x = coords[i++] - x;
  5625. handleOut._y = coords[i++] - y;
  5626. }
  5627. } else {
  5628. if (!handleIn) {
  5629. coords[i++] = x;
  5630. coords[i++] = y;
  5631. }
  5632. if (!handleOut) {
  5633. coords[i++] = x;
  5634. coords[i++] = y;
  5635. }
  5636. }
  5637. }
  5638. return coords;
  5639. }
  5640. });
  5641. var SegmentPoint = Point.extend({
  5642. initialize: function SegmentPoint(point, owner, key) {
  5643. var x, y,
  5644. selected;
  5645. if (!point) {
  5646. x = y = 0;
  5647. } else if ((x = point[0]) !== undefined) {
  5648. y = point[1];
  5649. } else {
  5650. var pt = point;
  5651. if ((x = pt.x) === undefined) {
  5652. pt = Point.read(arguments);
  5653. x = pt.x;
  5654. }
  5655. y = pt.y;
  5656. selected = pt.selected;
  5657. }
  5658. this._x = x;
  5659. this._y = y;
  5660. this._owner = owner;
  5661. owner[key] = this;
  5662. if (selected)
  5663. this.setSelected(true);
  5664. },
  5665. _set: function(x, y) {
  5666. this._x = x;
  5667. this._y = y;
  5668. this._owner._changed(this);
  5669. return this;
  5670. },
  5671. getX: function() {
  5672. return this._x;
  5673. },
  5674. setX: function(x) {
  5675. this._x = x;
  5676. this._owner._changed(this);
  5677. },
  5678. getY: function() {
  5679. return this._y;
  5680. },
  5681. setY: function(y) {
  5682. this._y = y;
  5683. this._owner._changed(this);
  5684. },
  5685. isZero: function() {
  5686. var isZero = Numerical.isZero;
  5687. return isZero(this._x) && isZero(this._y);
  5688. },
  5689. isSelected: function() {
  5690. return !!(this._owner._selection & this._getSelection());
  5691. },
  5692. setSelected: function(selected) {
  5693. this._owner._changeSelection(this._getSelection(), selected);
  5694. },
  5695. _getSelection: function() {
  5696. var owner = this._owner;
  5697. return this === owner._point ? 1
  5698. : this === owner._handleIn ? 2
  5699. : this === owner._handleOut ? 4
  5700. : 0;
  5701. }
  5702. });
  5703. var Curve = Base.extend({
  5704. _class: 'Curve',
  5705. beans: true,
  5706. initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
  5707. var count = arguments.length,
  5708. seg1, seg2,
  5709. point1, point2,
  5710. handle1, handle2;
  5711. if (count === 3) {
  5712. this._path = arg0;
  5713. seg1 = arg1;
  5714. seg2 = arg2;
  5715. } else if (!count) {
  5716. seg1 = new Segment();
  5717. seg2 = new Segment();
  5718. } else if (count === 1) {
  5719. if ('segment1' in arg0) {
  5720. seg1 = new Segment(arg0.segment1);
  5721. seg2 = new Segment(arg0.segment2);
  5722. } else if ('point1' in arg0) {
  5723. point1 = arg0.point1;
  5724. handle1 = arg0.handle1;
  5725. handle2 = arg0.handle2;
  5726. point2 = arg0.point2;
  5727. } else if (Array.isArray(arg0)) {
  5728. point1 = [arg0[0], arg0[1]];
  5729. point2 = [arg0[6], arg0[7]];
  5730. handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]];
  5731. handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]];
  5732. }
  5733. } else if (count === 2) {
  5734. seg1 = new Segment(arg0);
  5735. seg2 = new Segment(arg1);
  5736. } else if (count === 4) {
  5737. point1 = arg0;
  5738. handle1 = arg1;
  5739. handle2 = arg2;
  5740. point2 = arg3;
  5741. } else if (count === 8) {
  5742. point1 = [arg0, arg1];
  5743. point2 = [arg6, arg7];
  5744. handle1 = [arg2 - arg0, arg3 - arg1];
  5745. handle2 = [arg4 - arg6, arg5 - arg7];
  5746. }
  5747. this._segment1 = seg1 || new Segment(point1, null, handle1);
  5748. this._segment2 = seg2 || new Segment(point2, handle2, null);
  5749. },
  5750. _serialize: function(options, dictionary) {
  5751. return Base.serialize(this.hasHandles()
  5752. ? [this.getPoint1(), this.getHandle1(), this.getHandle2(),
  5753. this.getPoint2()]
  5754. : [this.getPoint1(), this.getPoint2()],
  5755. options, true, dictionary);
  5756. },
  5757. _changed: function() {
  5758. this._length = this._bounds = undefined;
  5759. },
  5760. clone: function() {
  5761. return new Curve(this._segment1, this._segment2);
  5762. },
  5763. toString: function() {
  5764. var parts = [ 'point1: ' + this._segment1._point ];
  5765. if (!this._segment1._handleOut.isZero())
  5766. parts.push('handle1: ' + this._segment1._handleOut);
  5767. if (!this._segment2._handleIn.isZero())
  5768. parts.push('handle2: ' + this._segment2._handleIn);
  5769. parts.push('point2: ' + this._segment2._point);
  5770. return '{ ' + parts.join(', ') + ' }';
  5771. },
  5772. classify: function() {
  5773. return Curve.classify(this.getValues());
  5774. },
  5775. remove: function() {
  5776. var removed = false;
  5777. if (this._path) {
  5778. var segment2 = this._segment2,
  5779. handleOut = segment2._handleOut;
  5780. removed = segment2.remove();
  5781. if (removed)
  5782. this._segment1._handleOut.set(handleOut);
  5783. }
  5784. return removed;
  5785. },
  5786. getPoint1: function() {
  5787. return this._segment1._point;
  5788. },
  5789. setPoint1: function() {
  5790. this._segment1._point.set(Point.read(arguments));
  5791. },
  5792. getPoint2: function() {
  5793. return this._segment2._point;
  5794. },
  5795. setPoint2: function() {
  5796. this._segment2._point.set(Point.read(arguments));
  5797. },
  5798. getHandle1: function() {
  5799. return this._segment1._handleOut;
  5800. },
  5801. setHandle1: function() {
  5802. this._segment1._handleOut.set(Point.read(arguments));
  5803. },
  5804. getHandle2: function() {
  5805. return this._segment2._handleIn;
  5806. },
  5807. setHandle2: function() {
  5808. this._segment2._handleIn.set(Point.read(arguments));
  5809. },
  5810. getSegment1: function() {
  5811. return this._segment1;
  5812. },
  5813. getSegment2: function() {
  5814. return this._segment2;
  5815. },
  5816. getPath: function() {
  5817. return this._path;
  5818. },
  5819. getIndex: function() {
  5820. return this._segment1._index;
  5821. },
  5822. getNext: function() {
  5823. var curves = this._path && this._path._curves;
  5824. return curves && (curves[this._segment1._index + 1]
  5825. || this._path._closed && curves[0]) || null;
  5826. },
  5827. getPrevious: function() {
  5828. var curves = this._path && this._path._curves;
  5829. return curves && (curves[this._segment1._index - 1]
  5830. || this._path._closed && curves[curves.length - 1]) || null;
  5831. },
  5832. isFirst: function() {
  5833. return !this._segment1._index;
  5834. },
  5835. isLast: function() {
  5836. var path = this._path;
  5837. return path && this._segment1._index === path._curves.length - 1
  5838. || false;
  5839. },
  5840. isSelected: function() {
  5841. return this.getPoint1().isSelected()
  5842. && this.getHandle1().isSelected()
  5843. && this.getHandle2().isSelected()
  5844. && this.getPoint2().isSelected();
  5845. },
  5846. setSelected: function(selected) {
  5847. this.getPoint1().setSelected(selected);
  5848. this.getHandle1().setSelected(selected);
  5849. this.getHandle2().setSelected(selected);
  5850. this.getPoint2().setSelected(selected);
  5851. },
  5852. getValues: function(matrix) {
  5853. return Curve.getValues(this._segment1, this._segment2, matrix);
  5854. },
  5855. getPoints: function() {
  5856. var coords = this.getValues(),
  5857. points = [];
  5858. for (var i = 0; i < 8; i += 2)
  5859. points.push(new Point(coords[i], coords[i + 1]));
  5860. return points;
  5861. }
  5862. }, {
  5863. getLength: function() {
  5864. if (this._length == null)
  5865. this._length = Curve.getLength(this.getValues(), 0, 1);
  5866. return this._length;
  5867. },
  5868. getArea: function() {
  5869. return Curve.getArea(this.getValues());
  5870. },
  5871. getLine: function() {
  5872. return new Line(this._segment1._point, this._segment2._point);
  5873. },
  5874. getPart: function(from, to) {
  5875. return new Curve(Curve.getPart(this.getValues(), from, to));
  5876. },
  5877. getPartLength: function(from, to) {
  5878. return Curve.getLength(this.getValues(), from, to);
  5879. },
  5880. divideAt: function(location) {
  5881. return this.divideAtTime(location && location.curve === this
  5882. ? location.time : this.getTimeAt(location));
  5883. },
  5884. divideAtTime: function(time, _setHandles) {
  5885. var tMin = 1e-8,
  5886. tMax = 1 - tMin,
  5887. res = null;
  5888. if (time >= tMin && time <= tMax) {
  5889. var parts = Curve.subdivide(this.getValues(), time),
  5890. left = parts[0],
  5891. right = parts[1],
  5892. setHandles = _setHandles || this.hasHandles(),
  5893. seg1 = this._segment1,
  5894. seg2 = this._segment2,
  5895. path = this._path;
  5896. if (setHandles) {
  5897. seg1._handleOut._set(left[2] - left[0], left[3] - left[1]);
  5898. seg2._handleIn._set(right[4] - right[6],right[5] - right[7]);
  5899. }
  5900. var x = left[6], y = left[7],
  5901. segment = new Segment(new Point(x, y),
  5902. setHandles && new Point(left[4] - x, left[5] - y),
  5903. setHandles && new Point(right[2] - x, right[3] - y));
  5904. if (path) {
  5905. path.insert(seg1._index + 1, segment);
  5906. res = this.getNext();
  5907. } else {
  5908. this._segment2 = segment;
  5909. this._changed();
  5910. res = new Curve(segment, seg2);
  5911. }
  5912. }
  5913. return res;
  5914. },
  5915. splitAt: function(location) {
  5916. var path = this._path;
  5917. return path ? path.splitAt(location) : null;
  5918. },
  5919. splitAtTime: function(time) {
  5920. return this.splitAt(this.getLocationAtTime(time));
  5921. },
  5922. divide: function(offset, isTime) {
  5923. return this.divideAtTime(offset === undefined ? 0.5 : isTime ? offset
  5924. : this.getTimeAt(offset));
  5925. },
  5926. split: function(offset, isTime) {
  5927. return this.splitAtTime(offset === undefined ? 0.5 : isTime ? offset
  5928. : this.getTimeAt(offset));
  5929. },
  5930. reversed: function() {
  5931. return new Curve(this._segment2.reversed(), this._segment1.reversed());
  5932. },
  5933. clearHandles: function() {
  5934. this._segment1._handleOut._set(0, 0);
  5935. this._segment2._handleIn._set(0, 0);
  5936. },
  5937. statics: {
  5938. getValues: function(segment1, segment2, matrix, straight) {
  5939. var p1 = segment1._point,
  5940. h1 = segment1._handleOut,
  5941. h2 = segment2._handleIn,
  5942. p2 = segment2._point,
  5943. x1 = p1.x, y1 = p1.y,
  5944. x2 = p2.x, y2 = p2.y,
  5945. values = straight
  5946. ? [ x1, y1, x1, y1, x2, y2, x2, y2 ]
  5947. : [
  5948. x1, y1,
  5949. x1 + h1._x, y1 + h1._y,
  5950. x2 + h2._x, y2 + h2._y,
  5951. x2, y2
  5952. ];
  5953. if (matrix)
  5954. matrix._transformCoordinates(values, values, 4);
  5955. return values;
  5956. },
  5957. subdivide: function(v, t) {
  5958. var x0 = v[0], y0 = v[1],
  5959. x1 = v[2], y1 = v[3],
  5960. x2 = v[4], y2 = v[5],
  5961. x3 = v[6], y3 = v[7];
  5962. if (t === undefined)
  5963. t = 0.5;
  5964. var u = 1 - t,
  5965. x4 = u * x0 + t * x1, y4 = u * y0 + t * y1,
  5966. x5 = u * x1 + t * x2, y5 = u * y1 + t * y2,
  5967. x6 = u * x2 + t * x3, y6 = u * y2 + t * y3,
  5968. x7 = u * x4 + t * x5, y7 = u * y4 + t * y5,
  5969. x8 = u * x5 + t * x6, y8 = u * y5 + t * y6,
  5970. x9 = u * x7 + t * x8, y9 = u * y7 + t * y8;
  5971. return [
  5972. [x0, y0, x4, y4, x7, y7, x9, y9],
  5973. [x9, y9, x8, y8, x6, y6, x3, y3]
  5974. ];
  5975. },
  5976. getMonoCurves: function(v, dir) {
  5977. var curves = [],
  5978. io = dir ? 0 : 1,
  5979. o0 = v[io + 0],
  5980. o1 = v[io + 2],
  5981. o2 = v[io + 4],
  5982. o3 = v[io + 6];
  5983. if ((o0 >= o1) === (o1 >= o2) && (o1 >= o2) === (o2 >= o3)
  5984. || Curve.isStraight(v)) {
  5985. curves.push(v);
  5986. } else {
  5987. var a = 3 * (o1 - o2) - o0 + o3,
  5988. b = 2 * (o0 + o2) - 4 * o1,
  5989. c = o1 - o0,
  5990. tMin = 1e-8,
  5991. tMax = 1 - tMin,
  5992. roots = [],
  5993. n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax);
  5994. if (!n) {
  5995. curves.push(v);
  5996. } else {
  5997. roots.sort();
  5998. var t = roots[0],
  5999. parts = Curve.subdivide(v, t);
  6000. curves.push(parts[0]);
  6001. if (n > 1) {
  6002. t = (roots[1] - t) / (1 - t);
  6003. parts = Curve.subdivide(parts[1], t);
  6004. curves.push(parts[0]);
  6005. }
  6006. curves.push(parts[1]);
  6007. }
  6008. }
  6009. return curves;
  6010. },
  6011. solveCubic: function (v, coord, val, roots, min, max) {
  6012. var v0 = v[coord],
  6013. v1 = v[coord + 2],
  6014. v2 = v[coord + 4],
  6015. v3 = v[coord + 6],
  6016. res = 0;
  6017. if ( !(v0 < val && v3 < val && v1 < val && v2 < val ||
  6018. v0 > val && v3 > val && v1 > val && v2 > val)) {
  6019. var c = 3 * (v1 - v0),
  6020. b = 3 * (v2 - v1) - c,
  6021. a = v3 - v0 - c - b;
  6022. res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max);
  6023. }
  6024. return res;
  6025. },
  6026. getTimeOf: function(v, point) {
  6027. var p0 = new Point(v[0], v[1]),
  6028. p3 = new Point(v[6], v[7]),
  6029. epsilon = 1e-12,
  6030. geomEpsilon = 1e-7,
  6031. t = point.isClose(p0, epsilon) ? 0
  6032. : point.isClose(p3, epsilon) ? 1
  6033. : null;
  6034. if (t === null) {
  6035. var coords = [point.x, point.y],
  6036. roots = [];
  6037. for (var c = 0; c < 2; c++) {
  6038. var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1);
  6039. for (var i = 0; i < count; i++) {
  6040. var u = roots[i];
  6041. if (point.isClose(Curve.getPoint(v, u), geomEpsilon))
  6042. return u;
  6043. }
  6044. }
  6045. }
  6046. return point.isClose(p0, geomEpsilon) ? 0
  6047. : point.isClose(p3, geomEpsilon) ? 1
  6048. : null;
  6049. },
  6050. getNearestTime: function(v, point) {
  6051. if (Curve.isStraight(v)) {
  6052. var x0 = v[0], y0 = v[1],
  6053. x3 = v[6], y3 = v[7],
  6054. vx = x3 - x0, vy = y3 - y0,
  6055. det = vx * vx + vy * vy;
  6056. if (det === 0)
  6057. return 0;
  6058. var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det;
  6059. return u < 1e-12 ? 0
  6060. : u > 0.999999999999 ? 1
  6061. : Curve.getTimeOf(v,
  6062. new Point(x0 + u * vx, y0 + u * vy));
  6063. }
  6064. var count = 100,
  6065. minDist = Infinity,
  6066. minT = 0;
  6067. function refine(t) {
  6068. if (t >= 0 && t <= 1) {
  6069. var dist = point.getDistance(Curve.getPoint(v, t), true);
  6070. if (dist < minDist) {
  6071. minDist = dist;
  6072. minT = t;
  6073. return true;
  6074. }
  6075. }
  6076. }
  6077. for (var i = 0; i <= count; i++)
  6078. refine(i / count);
  6079. var step = 1 / (count * 2);
  6080. while (step > 1e-8) {
  6081. if (!refine(minT - step) && !refine(minT + step))
  6082. step /= 2;
  6083. }
  6084. return minT;
  6085. },
  6086. getPart: function(v, from, to) {
  6087. var flip = from > to;
  6088. if (flip) {
  6089. var tmp = from;
  6090. from = to;
  6091. to = tmp;
  6092. }
  6093. if (from > 0)
  6094. v = Curve.subdivide(v, from)[1];
  6095. if (to < 1)
  6096. v = Curve.subdivide(v, (to - from) / (1 - from))[0];
  6097. return flip
  6098. ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]]
  6099. : v;
  6100. },
  6101. isFlatEnough: function(v, flatness) {
  6102. var x0 = v[0], y0 = v[1],
  6103. x1 = v[2], y1 = v[3],
  6104. x2 = v[4], y2 = v[5],
  6105. x3 = v[6], y3 = v[7],
  6106. ux = 3 * x1 - 2 * x0 - x3,
  6107. uy = 3 * y1 - 2 * y0 - y3,
  6108. vx = 3 * x2 - 2 * x3 - x0,
  6109. vy = 3 * y2 - 2 * y3 - y0;
  6110. return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
  6111. <= 16 * flatness * flatness;
  6112. },
  6113. getArea: function(v) {
  6114. var x0 = v[0], y0 = v[1],
  6115. x1 = v[2], y1 = v[3],
  6116. x2 = v[4], y2 = v[5],
  6117. x3 = v[6], y3 = v[7];
  6118. return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2)
  6119. + y1 * (x0 - x2) - x1 * (y0 - y2)
  6120. + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20;
  6121. },
  6122. getBounds: function(v) {
  6123. var min = v.slice(0, 2),
  6124. max = min.slice(),
  6125. roots = [0, 0];
  6126. for (var i = 0; i < 2; i++)
  6127. Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
  6128. i, 0, min, max, roots);
  6129. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  6130. },
  6131. _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
  6132. function add(value, padding) {
  6133. var left = value - padding,
  6134. right = value + padding;
  6135. if (left < min[coord])
  6136. min[coord] = left;
  6137. if (right > max[coord])
  6138. max[coord] = right;
  6139. }
  6140. padding /= 2;
  6141. var minPad = min[coord] + padding,
  6142. maxPad = max[coord] - padding;
  6143. if ( v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad ||
  6144. v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) {
  6145. if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) {
  6146. add(v0, 0);
  6147. add(v3, 0);
  6148. } else {
  6149. var a = 3 * (v1 - v2) - v0 + v3,
  6150. b = 2 * (v0 + v2) - 4 * v1,
  6151. c = v1 - v0,
  6152. count = Numerical.solveQuadratic(a, b, c, roots),
  6153. tMin = 1e-8,
  6154. tMax = 1 - tMin;
  6155. add(v3, 0);
  6156. for (var i = 0; i < count; i++) {
  6157. var t = roots[i],
  6158. u = 1 - t;
  6159. if (tMin <= t && t <= tMax)
  6160. add(u * u * u * v0
  6161. + 3 * u * u * t * v1
  6162. + 3 * u * t * t * v2
  6163. + t * t * t * v3,
  6164. padding);
  6165. }
  6166. }
  6167. }
  6168. }
  6169. }}, Base.each(
  6170. ['getBounds', 'getStrokeBounds', 'getHandleBounds'],
  6171. function(name) {
  6172. this[name] = function() {
  6173. if (!this._bounds)
  6174. this._bounds = {};
  6175. var bounds = this._bounds[name];
  6176. if (!bounds) {
  6177. bounds = this._bounds[name] = Path[name](
  6178. [this._segment1, this._segment2], false, this._path);
  6179. }
  6180. return bounds.clone();
  6181. };
  6182. },
  6183. {
  6184. }), Base.each({
  6185. isStraight: function(p1, h1, h2, p2) {
  6186. if (h1.isZero() && h2.isZero()) {
  6187. return true;
  6188. } else {
  6189. var v = p2.subtract(p1);
  6190. if (v.isZero()) {
  6191. return false;
  6192. } else if (v.isCollinear(h1) && v.isCollinear(h2)) {
  6193. var l = new Line(p1, p2),
  6194. epsilon = 1e-7;
  6195. if (l.getDistance(p1.add(h1)) < epsilon &&
  6196. l.getDistance(p2.add(h2)) < epsilon) {
  6197. var div = v.dot(v),
  6198. s1 = v.dot(h1) / div,
  6199. s2 = v.dot(h2) / div;
  6200. return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1;
  6201. }
  6202. }
  6203. }
  6204. return false;
  6205. },
  6206. isLinear: function(p1, h1, h2, p2) {
  6207. var third = p2.subtract(p1).divide(3);
  6208. return h1.equals(third) && h2.negate().equals(third);
  6209. }
  6210. }, function(test, name) {
  6211. this[name] = function(epsilon) {
  6212. var seg1 = this._segment1,
  6213. seg2 = this._segment2;
  6214. return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point,
  6215. epsilon);
  6216. };
  6217. this.statics[name] = function(v, epsilon) {
  6218. var x0 = v[0], y0 = v[1],
  6219. x3 = v[6], y3 = v[7];
  6220. return test(
  6221. new Point(x0, y0),
  6222. new Point(v[2] - x0, v[3] - y0),
  6223. new Point(v[4] - x3, v[5] - y3),
  6224. new Point(x3, y3), epsilon);
  6225. };
  6226. }, {
  6227. statics: {},
  6228. hasHandles: function() {
  6229. return !this._segment1._handleOut.isZero()
  6230. || !this._segment2._handleIn.isZero();
  6231. },
  6232. hasLength: function(epsilon) {
  6233. return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles())
  6234. && this.getLength() > (epsilon || 0);
  6235. },
  6236. isCollinear: function(curve) {
  6237. return curve && this.isStraight() && curve.isStraight()
  6238. && this.getLine().isCollinear(curve.getLine());
  6239. },
  6240. isHorizontal: function() {
  6241. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).y)
  6242. < 1e-8;
  6243. },
  6244. isVertical: function() {
  6245. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).x)
  6246. < 1e-8;
  6247. }
  6248. }), {
  6249. beans: false,
  6250. getLocationAt: function(offset, _isTime) {
  6251. return this.getLocationAtTime(
  6252. _isTime ? offset : this.getTimeAt(offset));
  6253. },
  6254. getLocationAtTime: function(t) {
  6255. return t != null && t >= 0 && t <= 1
  6256. ? new CurveLocation(this, t)
  6257. : null;
  6258. },
  6259. getTimeAt: function(offset, start) {
  6260. return Curve.getTimeAt(this.getValues(), offset, start);
  6261. },
  6262. getParameterAt: '#getTimeAt',
  6263. getTimesWithTangent: function () {
  6264. var tangent = Point.read(arguments);
  6265. return tangent.isZero()
  6266. ? []
  6267. : Curve.getTimesWithTangent(this.getValues(), tangent);
  6268. },
  6269. getOffsetAtTime: function(t) {
  6270. return this.getPartLength(0, t);
  6271. },
  6272. getLocationOf: function() {
  6273. return this.getLocationAtTime(this.getTimeOf(Point.read(arguments)));
  6274. },
  6275. getOffsetOf: function() {
  6276. var loc = this.getLocationOf.apply(this, arguments);
  6277. return loc ? loc.getOffset() : null;
  6278. },
  6279. getTimeOf: function() {
  6280. return Curve.getTimeOf(this.getValues(), Point.read(arguments));
  6281. },
  6282. getParameterOf: '#getTimeOf',
  6283. getNearestLocation: function() {
  6284. var point = Point.read(arguments),
  6285. values = this.getValues(),
  6286. t = Curve.getNearestTime(values, point),
  6287. pt = Curve.getPoint(values, t);
  6288. return new CurveLocation(this, t, pt, null, point.getDistance(pt));
  6289. },
  6290. getNearestPoint: function() {
  6291. var loc = this.getNearestLocation.apply(this, arguments);
  6292. return loc ? loc.getPoint() : loc;
  6293. }
  6294. },
  6295. new function() {
  6296. var methods = ['getPoint', 'getTangent', 'getNormal', 'getWeightedTangent',
  6297. 'getWeightedNormal', 'getCurvature'];
  6298. return Base.each(methods,
  6299. function(name) {
  6300. this[name + 'At'] = function(location, _isTime) {
  6301. var values = this.getValues();
  6302. return Curve[name](values, _isTime ? location
  6303. : Curve.getTimeAt(values, location));
  6304. };
  6305. this[name + 'AtTime'] = function(time) {
  6306. return Curve[name](this.getValues(), time);
  6307. };
  6308. }, {
  6309. statics: {
  6310. _evaluateMethods: methods
  6311. }
  6312. }
  6313. );
  6314. },
  6315. new function() {
  6316. function getLengthIntegrand(v) {
  6317. var x0 = v[0], y0 = v[1],
  6318. x1 = v[2], y1 = v[3],
  6319. x2 = v[4], y2 = v[5],
  6320. x3 = v[6], y3 = v[7],
  6321. ax = 9 * (x1 - x2) + 3 * (x3 - x0),
  6322. bx = 6 * (x0 + x2) - 12 * x1,
  6323. cx = 3 * (x1 - x0),
  6324. ay = 9 * (y1 - y2) + 3 * (y3 - y0),
  6325. by = 6 * (y0 + y2) - 12 * y1,
  6326. cy = 3 * (y1 - y0);
  6327. return function(t) {
  6328. var dx = (ax * t + bx) * t + cx,
  6329. dy = (ay * t + by) * t + cy;
  6330. return Math.sqrt(dx * dx + dy * dy);
  6331. };
  6332. }
  6333. function getIterations(a, b) {
  6334. return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
  6335. }
  6336. function evaluate(v, t, type, normalized) {
  6337. if (t == null || t < 0 || t > 1)
  6338. return null;
  6339. var x0 = v[0], y0 = v[1],
  6340. x1 = v[2], y1 = v[3],
  6341. x2 = v[4], y2 = v[5],
  6342. x3 = v[6], y3 = v[7],
  6343. isZero = Numerical.isZero;
  6344. if (isZero(x1 - x0) && isZero(y1 - y0)) {
  6345. x1 = x0;
  6346. y1 = y0;
  6347. }
  6348. if (isZero(x2 - x3) && isZero(y2 - y3)) {
  6349. x2 = x3;
  6350. y2 = y3;
  6351. }
  6352. var cx = 3 * (x1 - x0),
  6353. bx = 3 * (x2 - x1) - cx,
  6354. ax = x3 - x0 - cx - bx,
  6355. cy = 3 * (y1 - y0),
  6356. by = 3 * (y2 - y1) - cy,
  6357. ay = y3 - y0 - cy - by,
  6358. x, y;
  6359. if (type === 0) {
  6360. x = t === 0 ? x0 : t === 1 ? x3
  6361. : ((ax * t + bx) * t + cx) * t + x0;
  6362. y = t === 0 ? y0 : t === 1 ? y3
  6363. : ((ay * t + by) * t + cy) * t + y0;
  6364. } else {
  6365. var tMin = 1e-8,
  6366. tMax = 1 - tMin;
  6367. if (t < tMin) {
  6368. x = cx;
  6369. y = cy;
  6370. } else if (t > tMax) {
  6371. x = 3 * (x3 - x2);
  6372. y = 3 * (y3 - y2);
  6373. } else {
  6374. x = (3 * ax * t + 2 * bx) * t + cx;
  6375. y = (3 * ay * t + 2 * by) * t + cy;
  6376. }
  6377. if (normalized) {
  6378. if (x === 0 && y === 0 && (t < tMin || t > tMax)) {
  6379. x = x2 - x1;
  6380. y = y2 - y1;
  6381. }
  6382. var len = Math.sqrt(x * x + y * y);
  6383. if (len) {
  6384. x /= len;
  6385. y /= len;
  6386. }
  6387. }
  6388. if (type === 3) {
  6389. var x2 = 6 * ax * t + 2 * bx,
  6390. y2 = 6 * ay * t + 2 * by,
  6391. d = Math.pow(x * x + y * y, 3 / 2);
  6392. x = d !== 0 ? (x * y2 - y * x2) / d : 0;
  6393. y = 0;
  6394. }
  6395. }
  6396. return type === 2 ? new Point(y, -x) : new Point(x, y);
  6397. }
  6398. return { statics: {
  6399. classify: function(v) {
  6400. var x0 = v[0], y0 = v[1],
  6401. x1 = v[2], y1 = v[3],
  6402. x2 = v[4], y2 = v[5],
  6403. x3 = v[6], y3 = v[7],
  6404. a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2,
  6405. a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3,
  6406. a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0,
  6407. d3 = 3 * a3,
  6408. d2 = d3 - a2,
  6409. d1 = d2 - a2 + a1,
  6410. l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3),
  6411. s = l !== 0 ? 1 / l : 0,
  6412. isZero = Numerical.isZero,
  6413. serpentine = 'serpentine';
  6414. d1 *= s;
  6415. d2 *= s;
  6416. d3 *= s;
  6417. function type(type, t1, t2) {
  6418. var hasRoots = t1 !== undefined,
  6419. t1Ok = hasRoots && t1 > 0 && t1 < 1,
  6420. t2Ok = hasRoots && t2 > 0 && t2 < 1;
  6421. if (hasRoots && (!(t1Ok || t2Ok)
  6422. || type === 'loop' && !(t1Ok && t2Ok))) {
  6423. type = 'arch';
  6424. t1Ok = t2Ok = false;
  6425. }
  6426. return {
  6427. type: type,
  6428. roots: t1Ok || t2Ok
  6429. ? t1Ok && t2Ok
  6430. ? t1 < t2 ? [t1, t2] : [t2, t1]
  6431. : [t1Ok ? t1 : t2]
  6432. : null
  6433. };
  6434. }
  6435. if (isZero(d1)) {
  6436. return isZero(d2)
  6437. ? type(isZero(d3) ? 'line' : 'quadratic')
  6438. : type(serpentine, d3 / (3 * d2));
  6439. }
  6440. var d = 3 * d2 * d2 - 4 * d1 * d3;
  6441. if (isZero(d)) {
  6442. return type('cusp', d2 / (2 * d1));
  6443. }
  6444. var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d),
  6445. f2 = 2 * d1;
  6446. return type(d > 0 ? serpentine : 'loop',
  6447. (d2 + f1) / f2,
  6448. (d2 - f1) / f2);
  6449. },
  6450. getLength: function(v, a, b, ds) {
  6451. if (a === undefined)
  6452. a = 0;
  6453. if (b === undefined)
  6454. b = 1;
  6455. if (Curve.isStraight(v)) {
  6456. var c = v;
  6457. if (b < 1) {
  6458. c = Curve.subdivide(c, b)[0];
  6459. a /= b;
  6460. }
  6461. if (a > 0) {
  6462. c = Curve.subdivide(c, a)[1];
  6463. }
  6464. var dx = c[6] - c[0],
  6465. dy = c[7] - c[1];
  6466. return Math.sqrt(dx * dx + dy * dy);
  6467. }
  6468. return Numerical.integrate(ds || getLengthIntegrand(v), a, b,
  6469. getIterations(a, b));
  6470. },
  6471. getTimeAt: function(v, offset, start) {
  6472. if (start === undefined)
  6473. start = offset < 0 ? 1 : 0;
  6474. if (offset === 0)
  6475. return start;
  6476. var abs = Math.abs,
  6477. epsilon = 1e-12,
  6478. forward = offset > 0,
  6479. a = forward ? start : 0,
  6480. b = forward ? 1 : start,
  6481. ds = getLengthIntegrand(v),
  6482. rangeLength = Curve.getLength(v, a, b, ds),
  6483. diff = abs(offset) - rangeLength;
  6484. if (abs(diff) < epsilon) {
  6485. return forward ? b : a;
  6486. } else if (diff > epsilon) {
  6487. return null;
  6488. }
  6489. var guess = offset / rangeLength,
  6490. length = 0;
  6491. function f(t) {
  6492. length += Numerical.integrate(ds, start, t,
  6493. getIterations(start, t));
  6494. start = t;
  6495. return length - offset;
  6496. }
  6497. return Numerical.findRoot(f, ds, start + guess, a, b, 32,
  6498. 1e-12);
  6499. },
  6500. getPoint: function(v, t) {
  6501. return evaluate(v, t, 0, false);
  6502. },
  6503. getTangent: function(v, t) {
  6504. return evaluate(v, t, 1, true);
  6505. },
  6506. getWeightedTangent: function(v, t) {
  6507. return evaluate(v, t, 1, false);
  6508. },
  6509. getNormal: function(v, t) {
  6510. return evaluate(v, t, 2, true);
  6511. },
  6512. getWeightedNormal: function(v, t) {
  6513. return evaluate(v, t, 2, false);
  6514. },
  6515. getCurvature: function(v, t) {
  6516. return evaluate(v, t, 3, false).x;
  6517. },
  6518. getPeaks: function(v) {
  6519. var x0 = v[0], y0 = v[1],
  6520. x1 = v[2], y1 = v[3],
  6521. x2 = v[4], y2 = v[5],
  6522. x3 = v[6], y3 = v[7],
  6523. ax = -x0 + 3 * x1 - 3 * x2 + x3,
  6524. bx = 3 * x0 - 6 * x1 + 3 * x2,
  6525. cx = -3 * x0 + 3 * x1,
  6526. ay = -y0 + 3 * y1 - 3 * y2 + y3,
  6527. by = 3 * y0 - 6 * y1 + 3 * y2,
  6528. cy = -3 * y0 + 3 * y1,
  6529. tMin = 1e-8,
  6530. tMax = 1 - tMin,
  6531. roots = [];
  6532. Numerical.solveCubic(
  6533. 9 * (ax * ax + ay * ay),
  6534. 9 * (ax * bx + by * ay),
  6535. 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay),
  6536. (cx * bx + by * cy),
  6537. roots, tMin, tMax);
  6538. return roots.sort();
  6539. }
  6540. }};
  6541. },
  6542. new function() {
  6543. function addLocation(locations, include, c1, t1, c2, t2, overlap) {
  6544. var excludeStart = !overlap && c1.getPrevious() === c2,
  6545. excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2,
  6546. tMin = 1e-8,
  6547. tMax = 1 - tMin;
  6548. if (t1 !== null && t1 >= (excludeStart ? tMin : 0) &&
  6549. t1 <= (excludeEnd ? tMax : 1)) {
  6550. if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) &&
  6551. t2 <= (excludeStart ? tMax : 1)) {
  6552. var loc1 = new CurveLocation(c1, t1, null, overlap),
  6553. loc2 = new CurveLocation(c2, t2, null, overlap);
  6554. loc1._intersection = loc2;
  6555. loc2._intersection = loc1;
  6556. if (!include || include(loc1)) {
  6557. CurveLocation.insert(locations, loc1, true);
  6558. }
  6559. }
  6560. }
  6561. }
  6562. function addCurveIntersections(v1, v2, c1, c2, locations, include, flip,
  6563. recursion, calls, tMin, tMax, uMin, uMax) {
  6564. if (++calls >= 4096 || ++recursion >= 40)
  6565. return calls;
  6566. var fatLineEpsilon = 1e-9,
  6567. q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],
  6568. getSignedDistance = Line.getSignedDistance,
  6569. d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]),
  6570. d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]),
  6571. factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
  6572. dMin = factor * Math.min(0, d1, d2),
  6573. dMax = factor * Math.max(0, d1, d2),
  6574. dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),
  6575. dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),
  6576. dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),
  6577. dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),
  6578. hull = getConvexHull(dp0, dp1, dp2, dp3),
  6579. top = hull[0],
  6580. bottom = hull[1],
  6581. tMinClip,
  6582. tMaxClip;
  6583. if (d1 === 0 && d2 === 0
  6584. && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0
  6585. || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null
  6586. || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(),
  6587. dMin, dMax)) == null)
  6588. return calls;
  6589. var tMinNew = tMin + (tMax - tMin) * tMinClip,
  6590. tMaxNew = tMin + (tMax - tMin) * tMaxClip;
  6591. if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) {
  6592. var t = (tMinNew + tMaxNew) / 2,
  6593. u = (uMin + uMax) / 2;
  6594. addLocation(locations, include,
  6595. flip ? c2 : c1, flip ? u : t,
  6596. flip ? c1 : c2, flip ? t : u);
  6597. } else {
  6598. v1 = Curve.getPart(v1, tMinClip, tMaxClip);
  6599. var uDiff = uMax - uMin;
  6600. if (tMaxClip - tMinClip > 0.8) {
  6601. if (tMaxNew - tMinNew > uDiff) {
  6602. var parts = Curve.subdivide(v1, 0.5),
  6603. t = (tMinNew + tMaxNew) / 2;
  6604. calls = addCurveIntersections(
  6605. v2, parts[0], c2, c1, locations, include, !flip,
  6606. recursion, calls, uMin, uMax, tMinNew, t);
  6607. calls = addCurveIntersections(
  6608. v2, parts[1], c2, c1, locations, include, !flip,
  6609. recursion, calls, uMin, uMax, t, tMaxNew);
  6610. } else {
  6611. var parts = Curve.subdivide(v2, 0.5),
  6612. u = (uMin + uMax) / 2;
  6613. calls = addCurveIntersections(
  6614. parts[0], v1, c2, c1, locations, include, !flip,
  6615. recursion, calls, uMin, u, tMinNew, tMaxNew);
  6616. calls = addCurveIntersections(
  6617. parts[1], v1, c2, c1, locations, include, !flip,
  6618. recursion, calls, u, uMax, tMinNew, tMaxNew);
  6619. }
  6620. } else {
  6621. if (uDiff === 0 || uDiff >= fatLineEpsilon) {
  6622. calls = addCurveIntersections(
  6623. v2, v1, c2, c1, locations, include, !flip,
  6624. recursion, calls, uMin, uMax, tMinNew, tMaxNew);
  6625. } else {
  6626. calls = addCurveIntersections(
  6627. v1, v2, c1, c2, locations, include, flip,
  6628. recursion, calls, tMinNew, tMaxNew, uMin, uMax);
  6629. }
  6630. }
  6631. }
  6632. return calls;
  6633. }
  6634. function getConvexHull(dq0, dq1, dq2, dq3) {
  6635. var p0 = [ 0, dq0 ],
  6636. p1 = [ 1 / 3, dq1 ],
  6637. p2 = [ 2 / 3, dq2 ],
  6638. p3 = [ 1, dq3 ],
  6639. dist1 = dq1 - (2 * dq0 + dq3) / 3,
  6640. dist2 = dq2 - (dq0 + 2 * dq3) / 3,
  6641. hull;
  6642. if (dist1 * dist2 < 0) {
  6643. hull = [[p0, p1, p3], [p0, p2, p3]];
  6644. } else {
  6645. var distRatio = dist1 / dist2;
  6646. hull = [
  6647. distRatio >= 2 ? [p0, p1, p3]
  6648. : distRatio <= 0.5 ? [p0, p2, p3]
  6649. : [p0, p1, p2, p3],
  6650. [p0, p3]
  6651. ];
  6652. }
  6653. return (dist1 || dist2) < 0 ? hull.reverse() : hull;
  6654. }
  6655. function clipConvexHull(hullTop, hullBottom, dMin, dMax) {
  6656. if (hullTop[0][1] < dMin) {
  6657. return clipConvexHullPart(hullTop, true, dMin);
  6658. } else if (hullBottom[0][1] > dMax) {
  6659. return clipConvexHullPart(hullBottom, false, dMax);
  6660. } else {
  6661. return hullTop[0][0];
  6662. }
  6663. }
  6664. function clipConvexHullPart(part, top, threshold) {
  6665. var px = part[0][0],
  6666. py = part[0][1];
  6667. for (var i = 1, l = part.length; i < l; i++) {
  6668. var qx = part[i][0],
  6669. qy = part[i][1];
  6670. if (top ? qy >= threshold : qy <= threshold) {
  6671. return qy === threshold ? qx
  6672. : px + (threshold - py) * (qx - px) / (qy - py);
  6673. }
  6674. px = qx;
  6675. py = qy;
  6676. }
  6677. return null;
  6678. }
  6679. function getCurveLineIntersections(v, px, py, vx, vy) {
  6680. var isZero = Numerical.isZero;
  6681. if (isZero(vx) && isZero(vy)) {
  6682. var t = Curve.getTimeOf(v, new Point(px, py));
  6683. return t === null ? [] : [t];
  6684. }
  6685. var angle = Math.atan2(-vy, vx),
  6686. sin = Math.sin(angle),
  6687. cos = Math.cos(angle),
  6688. rv = [],
  6689. roots = [];
  6690. for (var i = 0; i < 8; i += 2) {
  6691. var x = v[i] - px,
  6692. y = v[i + 1] - py;
  6693. rv.push(
  6694. x * cos - y * sin,
  6695. x * sin + y * cos);
  6696. }
  6697. Curve.solveCubic(rv, 1, 0, roots, 0, 1);
  6698. return roots;
  6699. }
  6700. function addCurveLineIntersections(v1, v2, c1, c2, locations, include,
  6701. flip) {
  6702. var x1 = v2[0], y1 = v2[1],
  6703. x2 = v2[6], y2 = v2[7],
  6704. roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1);
  6705. for (var i = 0, l = roots.length; i < l; i++) {
  6706. var t1 = roots[i],
  6707. p1 = Curve.getPoint(v1, t1),
  6708. t2 = Curve.getTimeOf(v2, p1);
  6709. if (t2 !== null) {
  6710. addLocation(locations, include,
  6711. flip ? c2 : c1, flip ? t2 : t1,
  6712. flip ? c1 : c2, flip ? t1 : t2);
  6713. }
  6714. }
  6715. }
  6716. function addLineIntersection(v1, v2, c1, c2, locations, include) {
  6717. var pt = Line.intersect(
  6718. v1[0], v1[1], v1[6], v1[7],
  6719. v2[0], v2[1], v2[6], v2[7]);
  6720. if (pt) {
  6721. addLocation(locations, include,
  6722. c1, Curve.getTimeOf(v1, pt),
  6723. c2, Curve.getTimeOf(v2, pt));
  6724. }
  6725. }
  6726. function getCurveIntersections(v1, v2, c1, c2, locations, include) {
  6727. var epsilon = 1e-12,
  6728. min = Math.min,
  6729. max = Math.max;
  6730. if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon >
  6731. min(v2[0], v2[2], v2[4], v2[6]) &&
  6732. min(v1[0], v1[2], v1[4], v1[6]) - epsilon <
  6733. max(v2[0], v2[2], v2[4], v2[6]) &&
  6734. max(v1[1], v1[3], v1[5], v1[7]) + epsilon >
  6735. min(v2[1], v2[3], v2[5], v2[7]) &&
  6736. min(v1[1], v1[3], v1[5], v1[7]) - epsilon <
  6737. max(v2[1], v2[3], v2[5], v2[7])) {
  6738. var overlaps = getOverlaps(v1, v2);
  6739. if (overlaps) {
  6740. for (var i = 0; i < 2; i++) {
  6741. var overlap = overlaps[i];
  6742. addLocation(locations, include,
  6743. c1, overlap[0],
  6744. c2, overlap[1], true);
  6745. }
  6746. } else {
  6747. var straight1 = Curve.isStraight(v1),
  6748. straight2 = Curve.isStraight(v2),
  6749. straight = straight1 && straight2,
  6750. flip = straight1 && !straight2,
  6751. before = locations.length;
  6752. (straight
  6753. ? addLineIntersection
  6754. : straight1 || straight2
  6755. ? addCurveLineIntersections
  6756. : addCurveIntersections)(
  6757. flip ? v2 : v1, flip ? v1 : v2,
  6758. flip ? c2 : c1, flip ? c1 : c2,
  6759. locations, include, flip,
  6760. 0, 0, 0, 1, 0, 1);
  6761. if (!straight || locations.length === before) {
  6762. for (var i = 0; i < 4; i++) {
  6763. var t1 = i >> 1,
  6764. t2 = i & 1,
  6765. i1 = t1 * 6,
  6766. i2 = t2 * 6,
  6767. p1 = new Point(v1[i1], v1[i1 + 1]),
  6768. p2 = new Point(v2[i2], v2[i2 + 1]);
  6769. if (p1.isClose(p2, epsilon)) {
  6770. addLocation(locations, include,
  6771. c1, t1,
  6772. c2, t2);
  6773. }
  6774. }
  6775. }
  6776. }
  6777. }
  6778. return locations;
  6779. }
  6780. function getSelfIntersection(v1, c1, locations, include) {
  6781. var info = Curve.classify(v1);
  6782. if (info.type === 'loop') {
  6783. var roots = info.roots;
  6784. addLocation(locations, include,
  6785. c1, roots[0],
  6786. c1, roots[1]);
  6787. }
  6788. return locations;
  6789. }
  6790. function getIntersections(curves1, curves2, include, matrix1, matrix2,
  6791. _returnFirst) {
  6792. var epsilon = 1e-7,
  6793. self = !curves2;
  6794. if (self)
  6795. curves2 = curves1;
  6796. var length1 = curves1.length,
  6797. length2 = curves2.length,
  6798. values1 = new Array(length1),
  6799. values2 = self ? values1 : new Array(length2),
  6800. locations = [];
  6801. for (var i = 0; i < length1; i++) {
  6802. values1[i] = curves1[i].getValues(matrix1);
  6803. }
  6804. if (!self) {
  6805. for (var i = 0; i < length2; i++) {
  6806. values2[i] = curves2[i].getValues(matrix2);
  6807. }
  6808. }
  6809. var boundsCollisions = CollisionDetection.findCurveBoundsCollisions(
  6810. values1, values2, epsilon);
  6811. for (var index1 = 0; index1 < length1; index1++) {
  6812. var curve1 = curves1[index1],
  6813. v1 = values1[index1];
  6814. if (self) {
  6815. getSelfIntersection(v1, curve1, locations, include);
  6816. }
  6817. var collisions1 = boundsCollisions[index1];
  6818. if (collisions1) {
  6819. for (var j = 0; j < collisions1.length; j++) {
  6820. if (_returnFirst && locations.length)
  6821. return locations;
  6822. var index2 = collisions1[j];
  6823. if (!self || index2 > index1) {
  6824. var curve2 = curves2[index2],
  6825. v2 = values2[index2];
  6826. getCurveIntersections(
  6827. v1, v2, curve1, curve2, locations, include);
  6828. }
  6829. }
  6830. }
  6831. }
  6832. return locations;
  6833. }
  6834. function getOverlaps(v1, v2) {
  6835. function getSquaredLineLength(v) {
  6836. var x = v[6] - v[0],
  6837. y = v[7] - v[1];
  6838. return x * x + y * y;
  6839. }
  6840. var abs = Math.abs,
  6841. getDistance = Line.getDistance,
  6842. timeEpsilon = 1e-8,
  6843. geomEpsilon = 1e-7,
  6844. straight1 = Curve.isStraight(v1),
  6845. straight2 = Curve.isStraight(v2),
  6846. straightBoth = straight1 && straight2,
  6847. flip = getSquaredLineLength(v1) < getSquaredLineLength(v2),
  6848. l1 = flip ? v2 : v1,
  6849. l2 = flip ? v1 : v2,
  6850. px = l1[0], py = l1[1],
  6851. vx = l1[6] - px, vy = l1[7] - py;
  6852. if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon &&
  6853. getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) {
  6854. if (!straightBoth &&
  6855. getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon &&
  6856. getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon &&
  6857. getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon &&
  6858. getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) {
  6859. straight1 = straight2 = straightBoth = true;
  6860. }
  6861. } else if (straightBoth) {
  6862. return null;
  6863. }
  6864. if (straight1 ^ straight2) {
  6865. return null;
  6866. }
  6867. var v = [v1, v2],
  6868. pairs = [];
  6869. for (var i = 0; i < 4 && pairs.length < 2; i++) {
  6870. var i1 = i & 1,
  6871. i2 = i1 ^ 1,
  6872. t1 = i >> 1,
  6873. t2 = Curve.getTimeOf(v[i1], new Point(
  6874. v[i2][t1 ? 6 : 0],
  6875. v[i2][t1 ? 7 : 1]));
  6876. if (t2 != null) {
  6877. var pair = i1 ? [t1, t2] : [t2, t1];
  6878. if (!pairs.length ||
  6879. abs(pair[0] - pairs[0][0]) > timeEpsilon &&
  6880. abs(pair[1] - pairs[0][1]) > timeEpsilon) {
  6881. pairs.push(pair);
  6882. }
  6883. }
  6884. if (i > 2 && !pairs.length)
  6885. break;
  6886. }
  6887. if (pairs.length !== 2) {
  6888. pairs = null;
  6889. } else if (!straightBoth) {
  6890. var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]),
  6891. o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]);
  6892. if (abs(o2[2] - o1[2]) > geomEpsilon ||
  6893. abs(o2[3] - o1[3]) > geomEpsilon ||
  6894. abs(o2[4] - o1[4]) > geomEpsilon ||
  6895. abs(o2[5] - o1[5]) > geomEpsilon)
  6896. pairs = null;
  6897. }
  6898. return pairs;
  6899. }
  6900. function getTimesWithTangent(v, tangent) {
  6901. var x0 = v[0], y0 = v[1],
  6902. x1 = v[2], y1 = v[3],
  6903. x2 = v[4], y2 = v[5],
  6904. x3 = v[6], y3 = v[7],
  6905. normalized = tangent.normalize(),
  6906. tx = normalized.x,
  6907. ty = normalized.y,
  6908. ax = 3 * x3 - 9 * x2 + 9 * x1 - 3 * x0,
  6909. ay = 3 * y3 - 9 * y2 + 9 * y1 - 3 * y0,
  6910. bx = 6 * x2 - 12 * x1 + 6 * x0,
  6911. by = 6 * y2 - 12 * y1 + 6 * y0,
  6912. cx = 3 * x1 - 3 * x0,
  6913. cy = 3 * y1 - 3 * y0,
  6914. den = 2 * ax * ty - 2 * ay * tx,
  6915. times = [];
  6916. if (Math.abs(den) < Numerical.CURVETIME_EPSILON) {
  6917. var num = ax * cy - ay * cx,
  6918. den = ax * by - ay * bx;
  6919. if (den != 0) {
  6920. var t = -num / den;
  6921. if (t >= 0 && t <= 1) times.push(t);
  6922. }
  6923. } else {
  6924. var delta = (bx * bx - 4 * ax * cx) * ty * ty +
  6925. (-2 * bx * by + 4 * ay * cx + 4 * ax * cy) * tx * ty +
  6926. (by * by - 4 * ay * cy) * tx * tx,
  6927. k = bx * ty - by * tx;
  6928. if (delta >= 0 && den != 0) {
  6929. var d = Math.sqrt(delta),
  6930. t0 = -(k + d) / den,
  6931. t1 = (-k + d) / den;
  6932. if (t0 >= 0 && t0 <= 1) times.push(t0);
  6933. if (t1 >= 0 && t1 <= 1) times.push(t1);
  6934. }
  6935. }
  6936. return times;
  6937. }
  6938. return {
  6939. getIntersections: function(curve) {
  6940. var v1 = this.getValues(),
  6941. v2 = curve && curve !== this && curve.getValues();
  6942. return v2 ? getCurveIntersections(v1, v2, this, curve, [])
  6943. : getSelfIntersection(v1, this, []);
  6944. },
  6945. statics: {
  6946. getOverlaps: getOverlaps,
  6947. getIntersections: getIntersections,
  6948. getCurveLineIntersections: getCurveLineIntersections,
  6949. getTimesWithTangent: getTimesWithTangent
  6950. }
  6951. };
  6952. });
  6953. var CurveLocation = Base.extend({
  6954. _class: 'CurveLocation',
  6955. initialize: function CurveLocation(curve, time, point, _overlap, _distance) {
  6956. if (time >= 0.99999999) {
  6957. var next = curve.getNext();
  6958. if (next) {
  6959. time = 0;
  6960. curve = next;
  6961. }
  6962. }
  6963. this._setCurve(curve);
  6964. this._time = time;
  6965. this._point = point || curve.getPointAtTime(time);
  6966. this._overlap = _overlap;
  6967. this._distance = _distance;
  6968. this._intersection = this._next = this._previous = null;
  6969. },
  6970. _setPath: function(path) {
  6971. this._path = path;
  6972. this._version = path ? path._version : 0;
  6973. },
  6974. _setCurve: function(curve) {
  6975. this._setPath(curve._path);
  6976. this._curve = curve;
  6977. this._segment = null;
  6978. this._segment1 = curve._segment1;
  6979. this._segment2 = curve._segment2;
  6980. },
  6981. _setSegment: function(segment) {
  6982. var curve = segment.getCurve();
  6983. if (curve) {
  6984. this._setCurve(curve);
  6985. } else {
  6986. this._setPath(segment._path);
  6987. this._segment1 = segment;
  6988. this._segment2 = null;
  6989. }
  6990. this._segment = segment;
  6991. this._time = segment === this._segment1 ? 0 : 1;
  6992. this._point = segment._point.clone();
  6993. },
  6994. getSegment: function() {
  6995. var segment = this._segment;
  6996. if (!segment) {
  6997. var curve = this.getCurve(),
  6998. time = this.getTime();
  6999. if (time === 0) {
  7000. segment = curve._segment1;
  7001. } else if (time === 1) {
  7002. segment = curve._segment2;
  7003. } else if (time != null) {
  7004. segment = curve.getPartLength(0, time)
  7005. < curve.getPartLength(time, 1)
  7006. ? curve._segment1
  7007. : curve._segment2;
  7008. }
  7009. this._segment = segment;
  7010. }
  7011. return segment;
  7012. },
  7013. getCurve: function() {
  7014. var path = this._path,
  7015. that = this;
  7016. if (path && path._version !== this._version) {
  7017. this._time = this._offset = this._curveOffset = this._curve = null;
  7018. }
  7019. function trySegment(segment) {
  7020. var curve = segment && segment.getCurve();
  7021. if (curve && (that._time = curve.getTimeOf(that._point)) != null) {
  7022. that._setCurve(curve);
  7023. return curve;
  7024. }
  7025. }
  7026. return this._curve
  7027. || trySegment(this._segment)
  7028. || trySegment(this._segment1)
  7029. || trySegment(this._segment2.getPrevious());
  7030. },
  7031. getPath: function() {
  7032. var curve = this.getCurve();
  7033. return curve && curve._path;
  7034. },
  7035. getIndex: function() {
  7036. var curve = this.getCurve();
  7037. return curve && curve.getIndex();
  7038. },
  7039. getTime: function() {
  7040. var curve = this.getCurve(),
  7041. time = this._time;
  7042. return curve && time == null
  7043. ? this._time = curve.getTimeOf(this._point)
  7044. : time;
  7045. },
  7046. getParameter: '#getTime',
  7047. getPoint: function() {
  7048. return this._point;
  7049. },
  7050. getOffset: function() {
  7051. var offset = this._offset;
  7052. if (offset == null) {
  7053. offset = 0;
  7054. var path = this.getPath(),
  7055. index = this.getIndex();
  7056. if (path && index != null) {
  7057. var curves = path.getCurves();
  7058. for (var i = 0; i < index; i++)
  7059. offset += curves[i].getLength();
  7060. }
  7061. this._offset = offset += this.getCurveOffset();
  7062. }
  7063. return offset;
  7064. },
  7065. getCurveOffset: function() {
  7066. var offset = this._curveOffset;
  7067. if (offset == null) {
  7068. var curve = this.getCurve(),
  7069. time = this.getTime();
  7070. this._curveOffset = offset = time != null && curve
  7071. && curve.getPartLength(0, time);
  7072. }
  7073. return offset;
  7074. },
  7075. getIntersection: function() {
  7076. return this._intersection;
  7077. },
  7078. getDistance: function() {
  7079. return this._distance;
  7080. },
  7081. divide: function() {
  7082. var curve = this.getCurve(),
  7083. res = curve && curve.divideAtTime(this.getTime());
  7084. if (res) {
  7085. this._setSegment(res._segment1);
  7086. }
  7087. return res;
  7088. },
  7089. split: function() {
  7090. var curve = this.getCurve(),
  7091. path = curve._path,
  7092. res = curve && curve.splitAtTime(this.getTime());
  7093. if (res) {
  7094. this._setSegment(path.getLastSegment());
  7095. }
  7096. return res;
  7097. },
  7098. equals: function(loc, _ignoreOther) {
  7099. var res = this === loc;
  7100. if (!res && loc instanceof CurveLocation) {
  7101. var c1 = this.getCurve(),
  7102. c2 = loc.getCurve(),
  7103. p1 = c1._path,
  7104. p2 = c2._path;
  7105. if (p1 === p2) {
  7106. var abs = Math.abs,
  7107. epsilon = 1e-7,
  7108. diff = abs(this.getOffset() - loc.getOffset()),
  7109. i1 = !_ignoreOther && this._intersection,
  7110. i2 = !_ignoreOther && loc._intersection;
  7111. res = (diff < epsilon
  7112. || p1 && abs(p1.getLength() - diff) < epsilon)
  7113. && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true));
  7114. }
  7115. }
  7116. return res;
  7117. },
  7118. toString: function() {
  7119. var parts = [],
  7120. point = this.getPoint(),
  7121. f = Formatter.instance;
  7122. if (point)
  7123. parts.push('point: ' + point);
  7124. var index = this.getIndex();
  7125. if (index != null)
  7126. parts.push('index: ' + index);
  7127. var time = this.getTime();
  7128. if (time != null)
  7129. parts.push('time: ' + f.number(time));
  7130. if (this._distance != null)
  7131. parts.push('distance: ' + f.number(this._distance));
  7132. return '{ ' + parts.join(', ') + ' }';
  7133. },
  7134. isTouching: function() {
  7135. var inter = this._intersection;
  7136. if (inter && this.getTangent().isCollinear(inter.getTangent())) {
  7137. var curve1 = this.getCurve(),
  7138. curve2 = inter.getCurve();
  7139. return !(curve1.isStraight() && curve2.isStraight()
  7140. && curve1.getLine().intersect(curve2.getLine()));
  7141. }
  7142. return false;
  7143. },
  7144. isCrossing: function() {
  7145. var inter = this._intersection;
  7146. if (!inter)
  7147. return false;
  7148. var t1 = this.getTime(),
  7149. t2 = inter.getTime(),
  7150. tMin = 1e-8,
  7151. tMax = 1 - tMin,
  7152. t1Inside = t1 >= tMin && t1 <= tMax,
  7153. t2Inside = t2 >= tMin && t2 <= tMax;
  7154. if (t1Inside && t2Inside)
  7155. return !this.isTouching();
  7156. var c2 = this.getCurve(),
  7157. c1 = c2 && t1 < tMin ? c2.getPrevious() : c2,
  7158. c4 = inter.getCurve(),
  7159. c3 = c4 && t2 < tMin ? c4.getPrevious() : c4;
  7160. if (t1 > tMax)
  7161. c2 = c2.getNext();
  7162. if (t2 > tMax)
  7163. c4 = c4.getNext();
  7164. if (!c1 || !c2 || !c3 || !c4)
  7165. return false;
  7166. var offsets = [];
  7167. function addOffsets(curve, end) {
  7168. var v = curve.getValues(),
  7169. roots = Curve.classify(v).roots || Curve.getPeaks(v),
  7170. count = roots.length,
  7171. offset = Curve.getLength(v,
  7172. end && count ? roots[count - 1] : 0,
  7173. !end && count ? roots[0] : 1);
  7174. offsets.push(count ? offset : offset / 32);
  7175. }
  7176. function isInRange(angle, min, max) {
  7177. return min < max
  7178. ? angle > min && angle < max
  7179. : angle > min || angle < max;
  7180. }
  7181. if (!t1Inside) {
  7182. addOffsets(c1, true);
  7183. addOffsets(c2, false);
  7184. }
  7185. if (!t2Inside) {
  7186. addOffsets(c3, true);
  7187. addOffsets(c4, false);
  7188. }
  7189. var pt = this.getPoint(),
  7190. offset = Math.min.apply(Math, offsets),
  7191. v2 = t1Inside ? c2.getTangentAtTime(t1)
  7192. : c2.getPointAt(offset).subtract(pt),
  7193. v1 = t1Inside ? v2.negate()
  7194. : c1.getPointAt(-offset).subtract(pt),
  7195. v4 = t2Inside ? c4.getTangentAtTime(t2)
  7196. : c4.getPointAt(offset).subtract(pt),
  7197. v3 = t2Inside ? v4.negate()
  7198. : c3.getPointAt(-offset).subtract(pt),
  7199. a1 = v1.getAngle(),
  7200. a2 = v2.getAngle(),
  7201. a3 = v3.getAngle(),
  7202. a4 = v4.getAngle();
  7203. return !!(t1Inside
  7204. ? (isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4)) &&
  7205. (isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3))
  7206. : (isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2)) &&
  7207. (isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1)));
  7208. },
  7209. hasOverlap: function() {
  7210. return !!this._overlap;
  7211. }
  7212. }, Base.each(Curve._evaluateMethods, function(name) {
  7213. var get = name + 'At';
  7214. this[name] = function() {
  7215. var curve = this.getCurve(),
  7216. time = this.getTime();
  7217. return time != null && curve && curve[get](time, true);
  7218. };
  7219. }, {
  7220. preserve: true
  7221. }),
  7222. new function() {
  7223. function insert(locations, loc, merge) {
  7224. var length = locations.length,
  7225. l = 0,
  7226. r = length - 1;
  7227. function search(index, dir) {
  7228. for (var i = index + dir; i >= -1 && i <= length; i += dir) {
  7229. var loc2 = locations[((i % length) + length) % length];
  7230. if (!loc.getPoint().isClose(loc2.getPoint(),
  7231. 1e-7))
  7232. break;
  7233. if (loc.equals(loc2))
  7234. return loc2;
  7235. }
  7236. return null;
  7237. }
  7238. while (l <= r) {
  7239. var m = (l + r) >>> 1,
  7240. loc2 = locations[m],
  7241. found;
  7242. if (merge && (found = loc.equals(loc2) ? loc2
  7243. : (search(m, -1) || search(m, 1)))) {
  7244. if (loc._overlap) {
  7245. found._overlap = found._intersection._overlap = true;
  7246. }
  7247. return found;
  7248. }
  7249. var path1 = loc.getPath(),
  7250. path2 = loc2.getPath(),
  7251. diff = path1 !== path2
  7252. ? path1._id - path2._id
  7253. : (loc.getIndex() + loc.getTime())
  7254. - (loc2.getIndex() + loc2.getTime());
  7255. if (diff < 0) {
  7256. r = m - 1;
  7257. } else {
  7258. l = m + 1;
  7259. }
  7260. }
  7261. locations.splice(l, 0, loc);
  7262. return loc;
  7263. }
  7264. return { statics: {
  7265. insert: insert,
  7266. expand: function(locations) {
  7267. var expanded = locations.slice();
  7268. for (var i = locations.length - 1; i >= 0; i--) {
  7269. insert(expanded, locations[i]._intersection, false);
  7270. }
  7271. return expanded;
  7272. }
  7273. }};
  7274. });
  7275. var PathItem = Item.extend({
  7276. _class: 'PathItem',
  7277. _selectBounds: false,
  7278. _canScaleStroke: true,
  7279. beans: true,
  7280. initialize: function PathItem() {
  7281. },
  7282. statics: {
  7283. create: function(arg) {
  7284. var data,
  7285. segments,
  7286. compound;
  7287. if (Base.isPlainObject(arg)) {
  7288. segments = arg.segments;
  7289. data = arg.pathData;
  7290. } else if (Array.isArray(arg)) {
  7291. segments = arg;
  7292. } else if (typeof arg === 'string') {
  7293. data = arg;
  7294. }
  7295. if (segments) {
  7296. var first = segments[0];
  7297. compound = first && Array.isArray(first[0]);
  7298. } else if (data) {
  7299. compound = (data.match(/m/gi) || []).length > 1
  7300. || /z\s*\S+/i.test(data);
  7301. }
  7302. var ctor = compound ? CompoundPath : Path;
  7303. return new ctor(arg);
  7304. }
  7305. },
  7306. _asPathItem: function() {
  7307. return this;
  7308. },
  7309. isClockwise: function() {
  7310. return this.getArea() >= 0;
  7311. },
  7312. setClockwise: function(clockwise) {
  7313. if (this.isClockwise() != (clockwise = !!clockwise))
  7314. this.reverse();
  7315. },
  7316. setPathData: function(data) {
  7317. var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
  7318. coords,
  7319. relative = false,
  7320. previous,
  7321. control,
  7322. current = new Point(),
  7323. start = new Point();
  7324. function getCoord(index, coord) {
  7325. var val = +coords[index];
  7326. if (relative)
  7327. val += current[coord];
  7328. return val;
  7329. }
  7330. function getPoint(index) {
  7331. return new Point(
  7332. getCoord(index, 'x'),
  7333. getCoord(index + 1, 'y')
  7334. );
  7335. }
  7336. this.clear();
  7337. for (var i = 0, l = parts && parts.length; i < l; i++) {
  7338. var part = parts[i],
  7339. command = part[0],
  7340. lower = command.toLowerCase();
  7341. coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
  7342. var length = coords && coords.length;
  7343. relative = command === lower;
  7344. if (previous === 'z' && !/[mz]/.test(lower))
  7345. this.moveTo(current);
  7346. switch (lower) {
  7347. case 'm':
  7348. case 'l':
  7349. var move = lower === 'm';
  7350. for (var j = 0; j < length; j += 2) {
  7351. this[move ? 'moveTo' : 'lineTo'](current = getPoint(j));
  7352. if (move) {
  7353. start = current;
  7354. move = false;
  7355. }
  7356. }
  7357. control = current;
  7358. break;
  7359. case 'h':
  7360. case 'v':
  7361. var coord = lower === 'h' ? 'x' : 'y';
  7362. current = current.clone();
  7363. for (var j = 0; j < length; j++) {
  7364. current[coord] = getCoord(j, coord);
  7365. this.lineTo(current);
  7366. }
  7367. control = current;
  7368. break;
  7369. case 'c':
  7370. for (var j = 0; j < length; j += 6) {
  7371. this.cubicCurveTo(
  7372. getPoint(j),
  7373. control = getPoint(j + 2),
  7374. current = getPoint(j + 4));
  7375. }
  7376. break;
  7377. case 's':
  7378. for (var j = 0; j < length; j += 4) {
  7379. this.cubicCurveTo(
  7380. /[cs]/.test(previous)
  7381. ? current.multiply(2).subtract(control)
  7382. : current,
  7383. control = getPoint(j),
  7384. current = getPoint(j + 2));
  7385. previous = lower;
  7386. }
  7387. break;
  7388. case 'q':
  7389. for (var j = 0; j < length; j += 4) {
  7390. this.quadraticCurveTo(
  7391. control = getPoint(j),
  7392. current = getPoint(j + 2));
  7393. }
  7394. break;
  7395. case 't':
  7396. for (var j = 0; j < length; j += 2) {
  7397. this.quadraticCurveTo(
  7398. control = (/[qt]/.test(previous)
  7399. ? current.multiply(2).subtract(control)
  7400. : current),
  7401. current = getPoint(j));
  7402. previous = lower;
  7403. }
  7404. break;
  7405. case 'a':
  7406. for (var j = 0; j < length; j += 7) {
  7407. this.arcTo(current = getPoint(j + 5),
  7408. new Size(+coords[j], +coords[j + 1]),
  7409. +coords[j + 2], +coords[j + 4], +coords[j + 3]);
  7410. }
  7411. break;
  7412. case 'z':
  7413. this.closePath(1e-12);
  7414. current = start;
  7415. break;
  7416. }
  7417. previous = lower;
  7418. }
  7419. },
  7420. _canComposite: function() {
  7421. return !(this.hasFill() && this.hasStroke());
  7422. },
  7423. _contains: function(point) {
  7424. var winding = point.isInside(
  7425. this.getBounds({ internal: true, handle: true }))
  7426. ? this._getWinding(point)
  7427. : {};
  7428. return winding.onPath || !!(this.getFillRule() === 'evenodd'
  7429. ? winding.windingL & 1 || winding.windingR & 1
  7430. : winding.winding);
  7431. },
  7432. getIntersections: function(path, include, _matrix, _returnFirst) {
  7433. var self = this === path || !path,
  7434. matrix1 = this._matrix._orNullIfIdentity(),
  7435. matrix2 = self ? matrix1
  7436. : (_matrix || path._matrix)._orNullIfIdentity();
  7437. return self || this.getBounds(matrix1).intersects(
  7438. path.getBounds(matrix2), 1e-12)
  7439. ? Curve.getIntersections(
  7440. this.getCurves(), !self && path.getCurves(), include,
  7441. matrix1, matrix2, _returnFirst)
  7442. : [];
  7443. },
  7444. getCrossings: function(path) {
  7445. return this.getIntersections(path, function(inter) {
  7446. return inter.isCrossing();
  7447. });
  7448. },
  7449. getNearestLocation: function() {
  7450. var point = Point.read(arguments),
  7451. curves = this.getCurves(),
  7452. minDist = Infinity,
  7453. minLoc = null;
  7454. for (var i = 0, l = curves.length; i < l; i++) {
  7455. var loc = curves[i].getNearestLocation(point);
  7456. if (loc._distance < minDist) {
  7457. minDist = loc._distance;
  7458. minLoc = loc;
  7459. }
  7460. }
  7461. return minLoc;
  7462. },
  7463. getNearestPoint: function() {
  7464. var loc = this.getNearestLocation.apply(this, arguments);
  7465. return loc ? loc.getPoint() : loc;
  7466. },
  7467. interpolate: function(from, to, factor) {
  7468. var isPath = !this._children,
  7469. name = isPath ? '_segments' : '_children',
  7470. itemsFrom = from[name],
  7471. itemsTo = to[name],
  7472. items = this[name];
  7473. if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) {
  7474. throw new Error('Invalid operands in interpolate() call: ' +
  7475. from + ', ' + to);
  7476. }
  7477. var current = items.length,
  7478. length = itemsTo.length;
  7479. if (current < length) {
  7480. var ctor = isPath ? Segment : Path;
  7481. for (var i = current; i < length; i++) {
  7482. this.add(new ctor());
  7483. }
  7484. } else if (current > length) {
  7485. this[isPath ? 'removeSegments' : 'removeChildren'](length, current);
  7486. }
  7487. for (var i = 0; i < length; i++) {
  7488. items[i].interpolate(itemsFrom[i], itemsTo[i], factor);
  7489. }
  7490. if (isPath) {
  7491. this.setClosed(from._closed);
  7492. this._changed(9);
  7493. }
  7494. },
  7495. compare: function(path) {
  7496. var ok = false;
  7497. if (path) {
  7498. var paths1 = this._children || [this],
  7499. paths2 = path._children ? path._children.slice() : [path],
  7500. length1 = paths1.length,
  7501. length2 = paths2.length,
  7502. matched = [],
  7503. count = 0;
  7504. ok = true;
  7505. var boundsOverlaps = CollisionDetection.findItemBoundsCollisions(paths1, paths2, Numerical.GEOMETRIC_EPSILON);
  7506. for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) {
  7507. var path1 = paths1[i1];
  7508. ok = false;
  7509. var pathBoundsOverlaps = boundsOverlaps[i1];
  7510. if (pathBoundsOverlaps) {
  7511. for (var i2 = pathBoundsOverlaps.length - 1; i2 >= 0 && !ok; i2--) {
  7512. if (path1.compare(paths2[pathBoundsOverlaps[i2]])) {
  7513. if (!matched[pathBoundsOverlaps[i2]]) {
  7514. matched[pathBoundsOverlaps[i2]] = true;
  7515. count++;
  7516. }
  7517. ok = true;
  7518. }
  7519. }
  7520. }
  7521. }
  7522. ok = ok && count === length2;
  7523. }
  7524. return ok;
  7525. },
  7526. });
  7527. var Path = PathItem.extend({
  7528. _class: 'Path',
  7529. _serializeFields: {
  7530. segments: [],
  7531. closed: false
  7532. },
  7533. initialize: function Path(arg) {
  7534. this._closed = false;
  7535. this._segments = [];
  7536. this._version = 0;
  7537. var args = arguments,
  7538. segments = Array.isArray(arg)
  7539. ? typeof arg[0] === 'object'
  7540. ? arg
  7541. : args
  7542. : arg && (arg.size === undefined && (arg.x !== undefined
  7543. || arg.point !== undefined))
  7544. ? args
  7545. : null;
  7546. if (segments && segments.length > 0) {
  7547. this.setSegments(segments);
  7548. } else {
  7549. this._curves = undefined;
  7550. this._segmentSelection = 0;
  7551. if (!segments && typeof arg === 'string') {
  7552. this.setPathData(arg);
  7553. arg = null;
  7554. }
  7555. }
  7556. this._initialize(!segments && arg);
  7557. },
  7558. _equals: function(item) {
  7559. return this._closed === item._closed
  7560. && Base.equals(this._segments, item._segments);
  7561. },
  7562. copyContent: function(source) {
  7563. this.setSegments(source._segments);
  7564. this._closed = source._closed;
  7565. },
  7566. _changed: function _changed(flags) {
  7567. _changed.base.call(this, flags);
  7568. if (flags & 8) {
  7569. this._length = this._area = undefined;
  7570. if (flags & 32) {
  7571. this._version++;
  7572. } else if (this._curves) {
  7573. for (var i = 0, l = this._curves.length; i < l; i++)
  7574. this._curves[i]._changed();
  7575. }
  7576. } else if (flags & 64) {
  7577. this._bounds = undefined;
  7578. }
  7579. },
  7580. getStyle: function() {
  7581. var parent = this._parent;
  7582. return (parent instanceof CompoundPath ? parent : this)._style;
  7583. },
  7584. getSegments: function() {
  7585. return this._segments;
  7586. },
  7587. setSegments: function(segments) {
  7588. var fullySelected = this.isFullySelected(),
  7589. length = segments && segments.length;
  7590. this._segments.length = 0;
  7591. this._segmentSelection = 0;
  7592. this._curves = undefined;
  7593. if (length) {
  7594. var last = segments[length - 1];
  7595. if (typeof last === 'boolean') {
  7596. this.setClosed(last);
  7597. length--;
  7598. }
  7599. this._add(Segment.readList(segments, 0, {}, length));
  7600. }
  7601. if (fullySelected)
  7602. this.setFullySelected(true);
  7603. },
  7604. getFirstSegment: function() {
  7605. return this._segments[0];
  7606. },
  7607. getLastSegment: function() {
  7608. return this._segments[this._segments.length - 1];
  7609. },
  7610. getCurves: function() {
  7611. var curves = this._curves,
  7612. segments = this._segments;
  7613. if (!curves) {
  7614. var length = this._countCurves();
  7615. curves = this._curves = new Array(length);
  7616. for (var i = 0; i < length; i++)
  7617. curves[i] = new Curve(this, segments[i],
  7618. segments[i + 1] || segments[0]);
  7619. }
  7620. return curves;
  7621. },
  7622. getFirstCurve: function() {
  7623. return this.getCurves()[0];
  7624. },
  7625. getLastCurve: function() {
  7626. var curves = this.getCurves();
  7627. return curves[curves.length - 1];
  7628. },
  7629. isClosed: function() {
  7630. return this._closed;
  7631. },
  7632. setClosed: function(closed) {
  7633. if (this._closed != (closed = !!closed)) {
  7634. this._closed = closed;
  7635. if (this._curves) {
  7636. var length = this._curves.length = this._countCurves();
  7637. if (closed)
  7638. this._curves[length - 1] = new Curve(this,
  7639. this._segments[length - 1], this._segments[0]);
  7640. }
  7641. this._changed(41);
  7642. }
  7643. }
  7644. }, {
  7645. beans: true,
  7646. getPathData: function(_matrix, _precision) {
  7647. var segments = this._segments,
  7648. length = segments.length,
  7649. f = new Formatter(_precision),
  7650. coords = new Array(6),
  7651. first = true,
  7652. curX, curY,
  7653. prevX, prevY,
  7654. inX, inY,
  7655. outX, outY,
  7656. parts = [];
  7657. function addSegment(segment, skipLine) {
  7658. segment._transformCoordinates(_matrix, coords);
  7659. curX = coords[0];
  7660. curY = coords[1];
  7661. if (first) {
  7662. parts.push('M' + f.pair(curX, curY));
  7663. first = false;
  7664. } else {
  7665. inX = coords[2];
  7666. inY = coords[3];
  7667. if (inX === curX && inY === curY
  7668. && outX === prevX && outY === prevY) {
  7669. if (!skipLine) {
  7670. var dx = curX - prevX,
  7671. dy = curY - prevY;
  7672. parts.push(
  7673. dx === 0 ? 'v' + f.number(dy)
  7674. : dy === 0 ? 'h' + f.number(dx)
  7675. : 'l' + f.pair(dx, dy));
  7676. }
  7677. } else {
  7678. parts.push('c' + f.pair(outX - prevX, outY - prevY)
  7679. + ' ' + f.pair( inX - prevX, inY - prevY)
  7680. + ' ' + f.pair(curX - prevX, curY - prevY));
  7681. }
  7682. }
  7683. prevX = curX;
  7684. prevY = curY;
  7685. outX = coords[4];
  7686. outY = coords[5];
  7687. }
  7688. if (!length)
  7689. return '';
  7690. for (var i = 0; i < length; i++)
  7691. addSegment(segments[i]);
  7692. if (this._closed && length > 0) {
  7693. addSegment(segments[0], true);
  7694. parts.push('z');
  7695. }
  7696. return parts.join('');
  7697. },
  7698. isEmpty: function() {
  7699. return !this._segments.length;
  7700. },
  7701. _transformContent: function(matrix) {
  7702. var segments = this._segments,
  7703. coords = new Array(6);
  7704. for (var i = 0, l = segments.length; i < l; i++)
  7705. segments[i]._transformCoordinates(matrix, coords, true);
  7706. return true;
  7707. },
  7708. _add: function(segs, index) {
  7709. var segments = this._segments,
  7710. curves = this._curves,
  7711. amount = segs.length,
  7712. append = index == null,
  7713. index = append ? segments.length : index;
  7714. for (var i = 0; i < amount; i++) {
  7715. var segment = segs[i];
  7716. if (segment._path)
  7717. segment = segs[i] = segment.clone();
  7718. segment._path = this;
  7719. segment._index = index + i;
  7720. if (segment._selection)
  7721. this._updateSelection(segment, 0, segment._selection);
  7722. }
  7723. if (append) {
  7724. Base.push(segments, segs);
  7725. } else {
  7726. segments.splice.apply(segments, [index, 0].concat(segs));
  7727. for (var i = index + amount, l = segments.length; i < l; i++)
  7728. segments[i]._index = i;
  7729. }
  7730. if (curves) {
  7731. var total = this._countCurves(),
  7732. start = index > 0 && index + amount - 1 === total ? index - 1
  7733. : index,
  7734. insert = start,
  7735. end = Math.min(start + amount, total);
  7736. if (segs._curves) {
  7737. curves.splice.apply(curves, [start, 0].concat(segs._curves));
  7738. insert += segs._curves.length;
  7739. }
  7740. for (var i = insert; i < end; i++)
  7741. curves.splice(i, 0, new Curve(this, null, null));
  7742. this._adjustCurves(start, end);
  7743. }
  7744. this._changed(41);
  7745. return segs;
  7746. },
  7747. _adjustCurves: function(start, end) {
  7748. var segments = this._segments,
  7749. curves = this._curves,
  7750. curve;
  7751. for (var i = start; i < end; i++) {
  7752. curve = curves[i];
  7753. curve._path = this;
  7754. curve._segment1 = segments[i];
  7755. curve._segment2 = segments[i + 1] || segments[0];
  7756. curve._changed();
  7757. }
  7758. if (curve = curves[this._closed && !start ? segments.length - 1
  7759. : start - 1]) {
  7760. curve._segment2 = segments[start] || segments[0];
  7761. curve._changed();
  7762. }
  7763. if (curve = curves[end]) {
  7764. curve._segment1 = segments[end];
  7765. curve._changed();
  7766. }
  7767. },
  7768. _countCurves: function() {
  7769. var length = this._segments.length;
  7770. return !this._closed && length > 0 ? length - 1 : length;
  7771. },
  7772. add: function(segment1 ) {
  7773. var args = arguments;
  7774. return args.length > 1 && typeof segment1 !== 'number'
  7775. ? this._add(Segment.readList(args))
  7776. : this._add([ Segment.read(args) ])[0];
  7777. },
  7778. insert: function(index, segment1 ) {
  7779. var args = arguments;
  7780. return args.length > 2 && typeof segment1 !== 'number'
  7781. ? this._add(Segment.readList(args, 1), index)
  7782. : this._add([ Segment.read(args, 1) ], index)[0];
  7783. },
  7784. addSegment: function() {
  7785. return this._add([ Segment.read(arguments) ])[0];
  7786. },
  7787. insertSegment: function(index ) {
  7788. return this._add([ Segment.read(arguments, 1) ], index)[0];
  7789. },
  7790. addSegments: function(segments) {
  7791. return this._add(Segment.readList(segments));
  7792. },
  7793. insertSegments: function(index, segments) {
  7794. return this._add(Segment.readList(segments), index);
  7795. },
  7796. removeSegment: function(index) {
  7797. return this.removeSegments(index, index + 1)[0] || null;
  7798. },
  7799. removeSegments: function(start, end, _includeCurves) {
  7800. start = start || 0;
  7801. end = Base.pick(end, this._segments.length);
  7802. var segments = this._segments,
  7803. curves = this._curves,
  7804. count = segments.length,
  7805. removed = segments.splice(start, end - start),
  7806. amount = removed.length;
  7807. if (!amount)
  7808. return removed;
  7809. for (var i = 0; i < amount; i++) {
  7810. var segment = removed[i];
  7811. if (segment._selection)
  7812. this._updateSelection(segment, segment._selection, 0);
  7813. segment._index = segment._path = null;
  7814. }
  7815. for (var i = start, l = segments.length; i < l; i++)
  7816. segments[i]._index = i;
  7817. if (curves) {
  7818. var index = start > 0 && end === count + (this._closed ? 1 : 0)
  7819. ? start - 1
  7820. : start,
  7821. curves = curves.splice(index, amount);
  7822. for (var i = curves.length - 1; i >= 0; i--)
  7823. curves[i]._path = null;
  7824. if (_includeCurves)
  7825. removed._curves = curves.slice(1);
  7826. this._adjustCurves(index, index);
  7827. }
  7828. this._changed(41);
  7829. return removed;
  7830. },
  7831. clear: '#removeSegments',
  7832. hasHandles: function() {
  7833. var segments = this._segments;
  7834. for (var i = 0, l = segments.length; i < l; i++) {
  7835. if (segments[i].hasHandles())
  7836. return true;
  7837. }
  7838. return false;
  7839. },
  7840. clearHandles: function() {
  7841. var segments = this._segments;
  7842. for (var i = 0, l = segments.length; i < l; i++)
  7843. segments[i].clearHandles();
  7844. },
  7845. getLength: function() {
  7846. if (this._length == null) {
  7847. var curves = this.getCurves(),
  7848. length = 0;
  7849. for (var i = 0, l = curves.length; i < l; i++)
  7850. length += curves[i].getLength();
  7851. this._length = length;
  7852. }
  7853. return this._length;
  7854. },
  7855. getArea: function() {
  7856. var area = this._area;
  7857. if (area == null) {
  7858. var segments = this._segments,
  7859. closed = this._closed;
  7860. area = 0;
  7861. for (var i = 0, l = segments.length; i < l; i++) {
  7862. var last = i + 1 === l;
  7863. area += Curve.getArea(Curve.getValues(
  7864. segments[i], segments[last ? 0 : i + 1],
  7865. null, last && !closed));
  7866. }
  7867. this._area = area;
  7868. }
  7869. return area;
  7870. },
  7871. isFullySelected: function() {
  7872. var length = this._segments.length;
  7873. return this.isSelected() && length > 0 && this._segmentSelection
  7874. === length * 7;
  7875. },
  7876. setFullySelected: function(selected) {
  7877. if (selected)
  7878. this._selectSegments(true);
  7879. this.setSelected(selected);
  7880. },
  7881. setSelection: function setSelection(selection) {
  7882. if (!(selection & 1))
  7883. this._selectSegments(false);
  7884. setSelection.base.call(this, selection);
  7885. },
  7886. _selectSegments: function(selected) {
  7887. var segments = this._segments,
  7888. length = segments.length,
  7889. selection = selected ? 7 : 0;
  7890. this._segmentSelection = selection * length;
  7891. for (var i = 0; i < length; i++)
  7892. segments[i]._selection = selection;
  7893. },
  7894. _updateSelection: function(segment, oldSelection, newSelection) {
  7895. segment._selection = newSelection;
  7896. var selection = this._segmentSelection += newSelection - oldSelection;
  7897. if (selection > 0)
  7898. this.setSelected(true);
  7899. },
  7900. divideAt: function(location) {
  7901. var loc = this.getLocationAt(location),
  7902. curve;
  7903. return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset()))
  7904. ? curve._segment1
  7905. : null;
  7906. },
  7907. splitAt: function(location) {
  7908. var loc = this.getLocationAt(location),
  7909. index = loc && loc.index,
  7910. time = loc && loc.time,
  7911. tMin = 1e-8,
  7912. tMax = 1 - tMin;
  7913. if (time > tMax) {
  7914. index++;
  7915. time = 0;
  7916. }
  7917. var curves = this.getCurves();
  7918. if (index >= 0 && index < curves.length) {
  7919. if (time >= tMin) {
  7920. curves[index++].divideAtTime(time);
  7921. }
  7922. var segs = this.removeSegments(index, this._segments.length, true),
  7923. path;
  7924. if (this._closed) {
  7925. this.setClosed(false);
  7926. path = this;
  7927. } else {
  7928. path = new Path(Item.NO_INSERT);
  7929. path.insertAbove(this);
  7930. path.copyAttributes(this);
  7931. }
  7932. path._add(segs, 0);
  7933. this.addSegment(segs[0]);
  7934. return path;
  7935. }
  7936. return null;
  7937. },
  7938. split: function(index, time) {
  7939. var curve,
  7940. location = time === undefined ? index
  7941. : (curve = this.getCurves()[index])
  7942. && curve.getLocationAtTime(time);
  7943. return location != null ? this.splitAt(location) : null;
  7944. },
  7945. join: function(path, tolerance) {
  7946. var epsilon = tolerance || 0;
  7947. if (path && path !== this) {
  7948. var segments = path._segments,
  7949. last1 = this.getLastSegment(),
  7950. last2 = path.getLastSegment();
  7951. if (!last2)
  7952. return this;
  7953. if (last1 && last1._point.isClose(last2._point, epsilon))
  7954. path.reverse();
  7955. var first2 = path.getFirstSegment();
  7956. if (last1 && last1._point.isClose(first2._point, epsilon)) {
  7957. last1.setHandleOut(first2._handleOut);
  7958. this._add(segments.slice(1));
  7959. } else {
  7960. var first1 = this.getFirstSegment();
  7961. if (first1 && first1._point.isClose(first2._point, epsilon))
  7962. path.reverse();
  7963. last2 = path.getLastSegment();
  7964. if (first1 && first1._point.isClose(last2._point, epsilon)) {
  7965. first1.setHandleIn(last2._handleIn);
  7966. this._add(segments.slice(0, segments.length - 1), 0);
  7967. } else {
  7968. this._add(segments.slice());
  7969. }
  7970. }
  7971. if (path._closed)
  7972. this._add([segments[0]]);
  7973. path.remove();
  7974. }
  7975. var first = this.getFirstSegment(),
  7976. last = this.getLastSegment();
  7977. if (first !== last && first._point.isClose(last._point, epsilon)) {
  7978. first.setHandleIn(last._handleIn);
  7979. last.remove();
  7980. this.setClosed(true);
  7981. }
  7982. return this;
  7983. },
  7984. reduce: function(options) {
  7985. var curves = this.getCurves(),
  7986. simplify = options && options.simplify,
  7987. tolerance = simplify ? 1e-7 : 0;
  7988. for (var i = curves.length - 1; i >= 0; i--) {
  7989. var curve = curves[i];
  7990. if (!curve.hasHandles() && (!curve.hasLength(tolerance)
  7991. || simplify && curve.isCollinear(curve.getNext())))
  7992. curve.remove();
  7993. }
  7994. return this;
  7995. },
  7996. reverse: function() {
  7997. this._segments.reverse();
  7998. for (var i = 0, l = this._segments.length; i < l; i++) {
  7999. var segment = this._segments[i];
  8000. var handleIn = segment._handleIn;
  8001. segment._handleIn = segment._handleOut;
  8002. segment._handleOut = handleIn;
  8003. segment._index = i;
  8004. }
  8005. this._curves = null;
  8006. this._changed(9);
  8007. },
  8008. flatten: function(flatness) {
  8009. var flattener = new PathFlattener(this, flatness || 0.25, 256, true),
  8010. parts = flattener.parts,
  8011. length = parts.length,
  8012. segments = [];
  8013. for (var i = 0; i < length; i++) {
  8014. segments.push(new Segment(parts[i].curve.slice(0, 2)));
  8015. }
  8016. if (!this._closed && length > 0) {
  8017. segments.push(new Segment(parts[length - 1].curve.slice(6)));
  8018. }
  8019. this.setSegments(segments);
  8020. },
  8021. simplify: function(tolerance) {
  8022. var segments = new PathFitter(this).fit(tolerance || 2.5);
  8023. if (segments)
  8024. this.setSegments(segments);
  8025. return !!segments;
  8026. },
  8027. smooth: function(options) {
  8028. var that = this,
  8029. opts = options || {},
  8030. type = opts.type || 'asymmetric',
  8031. segments = this._segments,
  8032. length = segments.length,
  8033. closed = this._closed;
  8034. function getIndex(value, _default) {
  8035. var index = value && value.index;
  8036. if (index != null) {
  8037. var path = value.path;
  8038. if (path && path !== that)
  8039. throw new Error(value._class + ' ' + index + ' of ' + path
  8040. + ' is not part of ' + that);
  8041. if (_default && value instanceof Curve)
  8042. index++;
  8043. } else {
  8044. index = typeof value === 'number' ? value : _default;
  8045. }
  8046. return Math.min(index < 0 && closed
  8047. ? index % length
  8048. : index < 0 ? index + length : index, length - 1);
  8049. }
  8050. var loop = closed && opts.from === undefined && opts.to === undefined,
  8051. from = getIndex(opts.from, 0),
  8052. to = getIndex(opts.to, length - 1);
  8053. if (from > to) {
  8054. if (closed) {
  8055. from -= length;
  8056. } else {
  8057. var tmp = from;
  8058. from = to;
  8059. to = tmp;
  8060. }
  8061. }
  8062. if (/^(?:asymmetric|continuous)$/.test(type)) {
  8063. var asymmetric = type === 'asymmetric',
  8064. min = Math.min,
  8065. amount = to - from + 1,
  8066. n = amount - 1,
  8067. padding = loop ? min(amount, 4) : 1,
  8068. paddingLeft = padding,
  8069. paddingRight = padding,
  8070. knots = [];
  8071. if (!closed) {
  8072. paddingLeft = min(1, from);
  8073. paddingRight = min(1, length - to - 1);
  8074. }
  8075. n += paddingLeft + paddingRight;
  8076. if (n <= 1)
  8077. return;
  8078. for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) {
  8079. knots[i] = segments[(j < 0 ? j + length : j) % length]._point;
  8080. }
  8081. var x = knots[0]._x + 2 * knots[1]._x,
  8082. y = knots[0]._y + 2 * knots[1]._y,
  8083. f = 2,
  8084. n_1 = n - 1,
  8085. rx = [x],
  8086. ry = [y],
  8087. rf = [f],
  8088. px = [],
  8089. py = [];
  8090. for (var i = 1; i < n; i++) {
  8091. var internal = i < n_1,
  8092. a = internal ? 1 : asymmetric ? 1 : 2,
  8093. b = internal ? 4 : asymmetric ? 2 : 7,
  8094. u = internal ? 4 : asymmetric ? 3 : 8,
  8095. v = internal ? 2 : asymmetric ? 0 : 1,
  8096. m = a / f;
  8097. f = rf[i] = b - m;
  8098. x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x;
  8099. y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y;
  8100. }
  8101. px[n_1] = rx[n_1] / rf[n_1];
  8102. py[n_1] = ry[n_1] / rf[n_1];
  8103. for (var i = n - 2; i >= 0; i--) {
  8104. px[i] = (rx[i] - px[i + 1]) / rf[i];
  8105. py[i] = (ry[i] - py[i + 1]) / rf[i];
  8106. }
  8107. px[n] = (3 * knots[n]._x - px[n_1]) / 2;
  8108. py[n] = (3 * knots[n]._y - py[n_1]) / 2;
  8109. for (var i = paddingLeft, max = n - paddingRight, j = from;
  8110. i <= max; i++, j++) {
  8111. var segment = segments[j < 0 ? j + length : j],
  8112. pt = segment._point,
  8113. hx = px[i] - pt._x,
  8114. hy = py[i] - pt._y;
  8115. if (loop || i < max)
  8116. segment.setHandleOut(hx, hy);
  8117. if (loop || i > paddingLeft)
  8118. segment.setHandleIn(-hx, -hy);
  8119. }
  8120. } else {
  8121. for (var i = from; i <= to; i++) {
  8122. segments[i < 0 ? i + length : i].smooth(opts,
  8123. !loop && i === from, !loop && i === to);
  8124. }
  8125. }
  8126. },
  8127. toShape: function(insert) {
  8128. if (!this._closed)
  8129. return null;
  8130. var segments = this._segments,
  8131. type,
  8132. size,
  8133. radius,
  8134. topCenter;
  8135. function isCollinear(i, j) {
  8136. var seg1 = segments[i],
  8137. seg2 = seg1.getNext(),
  8138. seg3 = segments[j],
  8139. seg4 = seg3.getNext();
  8140. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  8141. && seg3._handleOut.isZero() && seg4._handleIn.isZero()
  8142. && seg2._point.subtract(seg1._point).isCollinear(
  8143. seg4._point.subtract(seg3._point));
  8144. }
  8145. function isOrthogonal(i) {
  8146. var seg2 = segments[i],
  8147. seg1 = seg2.getPrevious(),
  8148. seg3 = seg2.getNext();
  8149. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  8150. && seg2._handleOut.isZero() && seg3._handleIn.isZero()
  8151. && seg2._point.subtract(seg1._point).isOrthogonal(
  8152. seg3._point.subtract(seg2._point));
  8153. }
  8154. function isArc(i) {
  8155. var seg1 = segments[i],
  8156. seg2 = seg1.getNext(),
  8157. handle1 = seg1._handleOut,
  8158. handle2 = seg2._handleIn,
  8159. kappa = 0.5522847498307936;
  8160. if (handle1.isOrthogonal(handle2)) {
  8161. var pt1 = seg1._point,
  8162. pt2 = seg2._point,
  8163. corner = new Line(pt1, handle1, true).intersect(
  8164. new Line(pt2, handle2, true), true);
  8165. return corner && Numerical.isZero(handle1.getLength() /
  8166. corner.subtract(pt1).getLength() - kappa)
  8167. && Numerical.isZero(handle2.getLength() /
  8168. corner.subtract(pt2).getLength() - kappa);
  8169. }
  8170. return false;
  8171. }
  8172. function getDistance(i, j) {
  8173. return segments[i]._point.getDistance(segments[j]._point);
  8174. }
  8175. if (!this.hasHandles() && segments.length === 4
  8176. && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) {
  8177. type = Shape.Rectangle;
  8178. size = new Size(getDistance(0, 3), getDistance(0, 1));
  8179. topCenter = segments[1]._point.add(segments[2]._point).divide(2);
  8180. } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
  8181. && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) {
  8182. type = Shape.Rectangle;
  8183. size = new Size(getDistance(1, 6), getDistance(0, 3));
  8184. radius = size.subtract(new Size(getDistance(0, 7),
  8185. getDistance(1, 2))).divide(2);
  8186. topCenter = segments[3]._point.add(segments[4]._point).divide(2);
  8187. } else if (segments.length === 4
  8188. && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
  8189. if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
  8190. type = Shape.Circle;
  8191. radius = getDistance(0, 2) / 2;
  8192. } else {
  8193. type = Shape.Ellipse;
  8194. radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
  8195. }
  8196. topCenter = segments[1]._point;
  8197. }
  8198. if (type) {
  8199. var center = this.getPosition(true),
  8200. shape = new type({
  8201. center: center,
  8202. size: size,
  8203. radius: radius,
  8204. insert: false
  8205. });
  8206. shape.copyAttributes(this, true);
  8207. shape._matrix.prepend(this._matrix);
  8208. shape.rotate(topCenter.subtract(center).getAngle() + 90);
  8209. if (insert === undefined || insert)
  8210. shape.insertAbove(this);
  8211. return shape;
  8212. }
  8213. return null;
  8214. },
  8215. toPath: '#clone',
  8216. compare: function compare(path) {
  8217. if (!path || path instanceof CompoundPath)
  8218. return compare.base.call(this, path);
  8219. var curves1 = this.getCurves(),
  8220. curves2 = path.getCurves(),
  8221. length1 = curves1.length,
  8222. length2 = curves2.length;
  8223. if (!length1 || !length2) {
  8224. return length1 == length2;
  8225. }
  8226. var v1 = curves1[0].getValues(),
  8227. values2 = [],
  8228. pos1 = 0, pos2,
  8229. end1 = 0, end2;
  8230. for (var i = 0; i < length2; i++) {
  8231. var v2 = curves2[i].getValues();
  8232. values2.push(v2);
  8233. var overlaps = Curve.getOverlaps(v1, v2);
  8234. if (overlaps) {
  8235. pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i;
  8236. end2 = overlaps[0][1];
  8237. break;
  8238. }
  8239. }
  8240. var abs = Math.abs,
  8241. epsilon = 1e-8,
  8242. v2 = values2[pos2],
  8243. start2;
  8244. while (v1 && v2) {
  8245. var overlaps = Curve.getOverlaps(v1, v2);
  8246. if (overlaps) {
  8247. var t1 = overlaps[0][0];
  8248. if (abs(t1 - end1) < epsilon) {
  8249. end1 = overlaps[1][0];
  8250. if (end1 === 1) {
  8251. v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null;
  8252. end1 = 0;
  8253. }
  8254. var t2 = overlaps[0][1];
  8255. if (abs(t2 - end2) < epsilon) {
  8256. if (!start2)
  8257. start2 = [pos2, t2];
  8258. end2 = overlaps[1][1];
  8259. if (end2 === 1) {
  8260. if (++pos2 >= length2)
  8261. pos2 = 0;
  8262. v2 = values2[pos2] || curves2[pos2].getValues();
  8263. end2 = 0;
  8264. }
  8265. if (!v1) {
  8266. return start2[0] === pos2 && start2[1] === end2;
  8267. }
  8268. continue;
  8269. }
  8270. }
  8271. }
  8272. break;
  8273. }
  8274. return false;
  8275. },
  8276. _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) {
  8277. var that = this,
  8278. style = this.getStyle(),
  8279. segments = this._segments,
  8280. numSegments = segments.length,
  8281. closed = this._closed,
  8282. tolerancePadding = options._tolerancePadding,
  8283. strokePadding = tolerancePadding,
  8284. join, cap, miterLimit,
  8285. area, loc, res,
  8286. hitStroke = options.stroke && style.hasStroke(),
  8287. hitFill = options.fill && style.hasFill(),
  8288. hitCurves = options.curves,
  8289. strokeRadius = hitStroke
  8290. ? style.getStrokeWidth() / 2
  8291. : hitFill && options.tolerance > 0 || hitCurves
  8292. ? 0 : null;
  8293. if (strokeRadius !== null) {
  8294. if (strokeRadius > 0) {
  8295. join = style.getStrokeJoin();
  8296. cap = style.getStrokeCap();
  8297. miterLimit = style.getMiterLimit();
  8298. strokePadding = strokePadding.add(
  8299. Path._getStrokePadding(strokeRadius, strokeMatrix));
  8300. } else {
  8301. join = cap = 'round';
  8302. }
  8303. }
  8304. function isCloseEnough(pt, padding) {
  8305. return point.subtract(pt).divide(padding).length <= 1;
  8306. }
  8307. function checkSegmentPoint(seg, pt, name) {
  8308. if (!options.selected || pt.isSelected()) {
  8309. var anchor = seg._point;
  8310. if (pt !== anchor)
  8311. pt = pt.add(anchor);
  8312. if (isCloseEnough(pt, strokePadding)) {
  8313. return new HitResult(name, that, {
  8314. segment: seg,
  8315. point: pt
  8316. });
  8317. }
  8318. }
  8319. }
  8320. function checkSegmentPoints(seg, ends) {
  8321. return (ends || options.segments)
  8322. && checkSegmentPoint(seg, seg._point, 'segment')
  8323. || (!ends && options.handles) && (
  8324. checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||
  8325. checkSegmentPoint(seg, seg._handleOut, 'handle-out'));
  8326. }
  8327. function addToArea(point) {
  8328. area.add(point);
  8329. }
  8330. function checkSegmentStroke(segment) {
  8331. var isJoin = closed || segment._index > 0
  8332. && segment._index < numSegments - 1;
  8333. if ((isJoin ? join : cap) === 'round') {
  8334. return isCloseEnough(segment._point, strokePadding);
  8335. } else {
  8336. area = new Path({ internal: true, closed: true });
  8337. if (isJoin) {
  8338. if (!segment.isSmooth()) {
  8339. Path._addBevelJoin(segment, join, strokeRadius,
  8340. miterLimit, null, strokeMatrix, addToArea, true);
  8341. }
  8342. } else if (cap === 'square') {
  8343. Path._addSquareCap(segment, cap, strokeRadius, null,
  8344. strokeMatrix, addToArea, true);
  8345. }
  8346. if (!area.isEmpty()) {
  8347. var loc;
  8348. return area.contains(point)
  8349. || (loc = area.getNearestLocation(point))
  8350. && isCloseEnough(loc.getPoint(), tolerancePadding);
  8351. }
  8352. }
  8353. }
  8354. if (options.ends && !options.segments && !closed) {
  8355. if (res = checkSegmentPoints(segments[0], true)
  8356. || checkSegmentPoints(segments[numSegments - 1], true))
  8357. return res;
  8358. } else if (options.segments || options.handles) {
  8359. for (var i = 0; i < numSegments; i++)
  8360. if (res = checkSegmentPoints(segments[i]))
  8361. return res;
  8362. }
  8363. if (strokeRadius !== null) {
  8364. loc = this.getNearestLocation(point);
  8365. if (loc) {
  8366. var time = loc.getTime();
  8367. if (time === 0 || time === 1 && numSegments > 1) {
  8368. if (!checkSegmentStroke(loc.getSegment()))
  8369. loc = null;
  8370. } else if (!isCloseEnough(loc.getPoint(), strokePadding)) {
  8371. loc = null;
  8372. }
  8373. }
  8374. if (!loc && join === 'miter' && numSegments > 1) {
  8375. for (var i = 0; i < numSegments; i++) {
  8376. var segment = segments[i];
  8377. if (point.getDistance(segment._point)
  8378. <= miterLimit * strokeRadius
  8379. && checkSegmentStroke(segment)) {
  8380. loc = segment.getLocation();
  8381. break;
  8382. }
  8383. }
  8384. }
  8385. }
  8386. return !loc && hitFill && this._contains(point)
  8387. || loc && !hitStroke && !hitCurves
  8388. ? new HitResult('fill', this)
  8389. : loc
  8390. ? new HitResult(hitStroke ? 'stroke' : 'curve', this, {
  8391. location: loc,
  8392. point: loc.getPoint()
  8393. })
  8394. : null;
  8395. }
  8396. }, Base.each(Curve._evaluateMethods,
  8397. function(name) {
  8398. this[name + 'At'] = function(offset) {
  8399. var loc = this.getLocationAt(offset);
  8400. return loc && loc[name]();
  8401. };
  8402. },
  8403. {
  8404. beans: false,
  8405. getLocationOf: function() {
  8406. var point = Point.read(arguments),
  8407. curves = this.getCurves();
  8408. for (var i = 0, l = curves.length; i < l; i++) {
  8409. var loc = curves[i].getLocationOf(point);
  8410. if (loc)
  8411. return loc;
  8412. }
  8413. return null;
  8414. },
  8415. getOffsetOf: function() {
  8416. var loc = this.getLocationOf.apply(this, arguments);
  8417. return loc ? loc.getOffset() : null;
  8418. },
  8419. getLocationAt: function(offset) {
  8420. if (typeof offset === 'number') {
  8421. var curves = this.getCurves(),
  8422. length = 0;
  8423. for (var i = 0, l = curves.length; i < l; i++) {
  8424. var start = length,
  8425. curve = curves[i];
  8426. length += curve.getLength();
  8427. if (length > offset) {
  8428. return curve.getLocationAt(offset - start);
  8429. }
  8430. }
  8431. if (curves.length > 0 && offset <= this.getLength()) {
  8432. return new CurveLocation(curves[curves.length - 1], 1);
  8433. }
  8434. } else if (offset && offset.getPath && offset.getPath() === this) {
  8435. return offset;
  8436. }
  8437. return null;
  8438. },
  8439. getOffsetsWithTangent: function() {
  8440. var tangent = Point.read(arguments);
  8441. if (tangent.isZero()) {
  8442. return [];
  8443. }
  8444. var offsets = [];
  8445. var curveStart = 0;
  8446. var curves = this.getCurves();
  8447. for (var i = 0, l = curves.length; i < l; i++) {
  8448. var curve = curves[i];
  8449. var curveTimes = curve.getTimesWithTangent(tangent);
  8450. for (var j = 0, m = curveTimes.length; j < m; j++) {
  8451. var offset = curveStart + curve.getOffsetAtTime(curveTimes[j]);
  8452. if (offsets.indexOf(offset) < 0) {
  8453. offsets.push(offset);
  8454. }
  8455. }
  8456. curveStart += curve.length;
  8457. }
  8458. return offsets;
  8459. }
  8460. }),
  8461. new function() {
  8462. function drawHandles(ctx, segments, matrix, size) {
  8463. if (size <= 0) return;
  8464. var half = size / 2,
  8465. miniSize = size - 2,
  8466. miniHalf = half - 1,
  8467. coords = new Array(6),
  8468. pX, pY;
  8469. function drawHandle(index) {
  8470. var hX = coords[index],
  8471. hY = coords[index + 1];
  8472. if (pX != hX || pY != hY) {
  8473. ctx.beginPath();
  8474. ctx.moveTo(pX, pY);
  8475. ctx.lineTo(hX, hY);
  8476. ctx.stroke();
  8477. ctx.beginPath();
  8478. ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
  8479. ctx.fill();
  8480. }
  8481. }
  8482. for (var i = 0, l = segments.length; i < l; i++) {
  8483. var segment = segments[i],
  8484. selection = segment._selection;
  8485. segment._transformCoordinates(matrix, coords);
  8486. pX = coords[0];
  8487. pY = coords[1];
  8488. if (selection & 2)
  8489. drawHandle(2);
  8490. if (selection & 4)
  8491. drawHandle(4);
  8492. ctx.fillRect(pX - half, pY - half, size, size);
  8493. if (miniSize > 0 && !(selection & 1)) {
  8494. var fillStyle = ctx.fillStyle;
  8495. ctx.fillStyle = '#ffffff';
  8496. ctx.fillRect(pX - miniHalf, pY - miniHalf, miniSize, miniSize);
  8497. ctx.fillStyle = fillStyle;
  8498. }
  8499. }
  8500. }
  8501. function drawSegments(ctx, path, matrix) {
  8502. var segments = path._segments,
  8503. length = segments.length,
  8504. coords = new Array(6),
  8505. first = true,
  8506. curX, curY,
  8507. prevX, prevY,
  8508. inX, inY,
  8509. outX, outY;
  8510. function drawSegment(segment) {
  8511. if (matrix) {
  8512. segment._transformCoordinates(matrix, coords);
  8513. curX = coords[0];
  8514. curY = coords[1];
  8515. } else {
  8516. var point = segment._point;
  8517. curX = point._x;
  8518. curY = point._y;
  8519. }
  8520. if (first) {
  8521. ctx.moveTo(curX, curY);
  8522. first = false;
  8523. } else {
  8524. if (matrix) {
  8525. inX = coords[2];
  8526. inY = coords[3];
  8527. } else {
  8528. var handle = segment._handleIn;
  8529. inX = curX + handle._x;
  8530. inY = curY + handle._y;
  8531. }
  8532. if (inX === curX && inY === curY
  8533. && outX === prevX && outY === prevY) {
  8534. ctx.lineTo(curX, curY);
  8535. } else {
  8536. ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
  8537. }
  8538. }
  8539. prevX = curX;
  8540. prevY = curY;
  8541. if (matrix) {
  8542. outX = coords[4];
  8543. outY = coords[5];
  8544. } else {
  8545. var handle = segment._handleOut;
  8546. outX = prevX + handle._x;
  8547. outY = prevY + handle._y;
  8548. }
  8549. }
  8550. for (var i = 0; i < length; i++)
  8551. drawSegment(segments[i]);
  8552. if (path._closed && length > 0)
  8553. drawSegment(segments[0]);
  8554. }
  8555. return {
  8556. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8557. var dontStart = param.dontStart,
  8558. dontPaint = param.dontFinish || param.clip,
  8559. style = this.getStyle(),
  8560. hasFill = style.hasFill(),
  8561. hasStroke = style.hasStroke(),
  8562. dashArray = style.getDashArray(),
  8563. dashLength = !paper.support.nativeDash && hasStroke
  8564. && dashArray && dashArray.length;
  8565. if (!dontStart)
  8566. ctx.beginPath();
  8567. if (hasFill || hasStroke && !dashLength || dontPaint) {
  8568. drawSegments(ctx, this, strokeMatrix);
  8569. if (this._closed)
  8570. ctx.closePath();
  8571. }
  8572. function getOffset(i) {
  8573. return dashArray[((i % dashLength) + dashLength) % dashLength];
  8574. }
  8575. if (!dontPaint && (hasFill || hasStroke)) {
  8576. this._setStyles(ctx, param, viewMatrix);
  8577. if (hasFill) {
  8578. ctx.fill(style.getFillRule());
  8579. ctx.shadowColor = 'rgba(0,0,0,0)';
  8580. }
  8581. if (hasStroke) {
  8582. if (dashLength) {
  8583. if (!dontStart)
  8584. ctx.beginPath();
  8585. var flattener = new PathFlattener(this, 0.25, 32, false,
  8586. strokeMatrix),
  8587. length = flattener.length,
  8588. from = -style.getDashOffset(), to,
  8589. i = 0;
  8590. while (from > 0) {
  8591. from -= getOffset(i--) + getOffset(i--);
  8592. }
  8593. while (from < length) {
  8594. to = from + getOffset(i++);
  8595. if (from > 0 || to > 0)
  8596. flattener.drawPart(ctx,
  8597. Math.max(from, 0), Math.max(to, 0));
  8598. from = to + getOffset(i++);
  8599. }
  8600. }
  8601. ctx.stroke();
  8602. }
  8603. }
  8604. },
  8605. _drawSelected: function(ctx, matrix) {
  8606. ctx.beginPath();
  8607. drawSegments(ctx, this, matrix);
  8608. ctx.stroke();
  8609. drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);
  8610. }
  8611. };
  8612. },
  8613. new function() {
  8614. function getCurrentSegment(that) {
  8615. var segments = that._segments;
  8616. if (!segments.length)
  8617. throw new Error('Use a moveTo() command first');
  8618. return segments[segments.length - 1];
  8619. }
  8620. return {
  8621. moveTo: function() {
  8622. var segments = this._segments;
  8623. if (segments.length === 1)
  8624. this.removeSegment(0);
  8625. if (!segments.length)
  8626. this._add([ new Segment(Point.read(arguments)) ]);
  8627. },
  8628. moveBy: function() {
  8629. throw new Error('moveBy() is unsupported on Path items.');
  8630. },
  8631. lineTo: function() {
  8632. this._add([ new Segment(Point.read(arguments)) ]);
  8633. },
  8634. cubicCurveTo: function() {
  8635. var args = arguments,
  8636. handle1 = Point.read(args),
  8637. handle2 = Point.read(args),
  8638. to = Point.read(args),
  8639. current = getCurrentSegment(this);
  8640. current.setHandleOut(handle1.subtract(current._point));
  8641. this._add([ new Segment(to, handle2.subtract(to)) ]);
  8642. },
  8643. quadraticCurveTo: function() {
  8644. var args = arguments,
  8645. handle = Point.read(args),
  8646. to = Point.read(args),
  8647. current = getCurrentSegment(this)._point;
  8648. this.cubicCurveTo(
  8649. handle.add(current.subtract(handle).multiply(1 / 3)),
  8650. handle.add(to.subtract(handle).multiply(1 / 3)),
  8651. to
  8652. );
  8653. },
  8654. curveTo: function() {
  8655. var args = arguments,
  8656. through = Point.read(args),
  8657. to = Point.read(args),
  8658. t = Base.pick(Base.read(args), 0.5),
  8659. t1 = 1 - t,
  8660. current = getCurrentSegment(this)._point,
  8661. handle = through.subtract(current.multiply(t1 * t1))
  8662. .subtract(to.multiply(t * t)).divide(2 * t * t1);
  8663. if (handle.isNaN())
  8664. throw new Error(
  8665. 'Cannot put a curve through points with parameter = ' + t);
  8666. this.quadraticCurveTo(handle, to);
  8667. },
  8668. arcTo: function() {
  8669. var args = arguments,
  8670. abs = Math.abs,
  8671. sqrt = Math.sqrt,
  8672. current = getCurrentSegment(this),
  8673. from = current._point,
  8674. to = Point.read(args),
  8675. through,
  8676. peek = Base.peek(args),
  8677. clockwise = Base.pick(peek, true),
  8678. center, extent, vector, matrix;
  8679. if (typeof clockwise === 'boolean') {
  8680. var middle = from.add(to).divide(2),
  8681. through = middle.add(middle.subtract(from).rotate(
  8682. clockwise ? -90 : 90));
  8683. } else if (Base.remain(args) <= 2) {
  8684. through = to;
  8685. to = Point.read(args);
  8686. } else if (!from.equals(to)) {
  8687. var radius = Size.read(args),
  8688. isZero = Numerical.isZero;
  8689. if (isZero(radius.width) || isZero(radius.height))
  8690. return this.lineTo(to);
  8691. var rotation = Base.read(args),
  8692. clockwise = !!Base.read(args),
  8693. large = !!Base.read(args),
  8694. middle = from.add(to).divide(2),
  8695. pt = from.subtract(middle).rotate(-rotation),
  8696. x = pt.x,
  8697. y = pt.y,
  8698. rx = abs(radius.width),
  8699. ry = abs(radius.height),
  8700. rxSq = rx * rx,
  8701. rySq = ry * ry,
  8702. xSq = x * x,
  8703. ySq = y * y;
  8704. var factor = sqrt(xSq / rxSq + ySq / rySq);
  8705. if (factor > 1) {
  8706. rx *= factor;
  8707. ry *= factor;
  8708. rxSq = rx * rx;
  8709. rySq = ry * ry;
  8710. }
  8711. factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /
  8712. (rxSq * ySq + rySq * xSq);
  8713. if (abs(factor) < 1e-12)
  8714. factor = 0;
  8715. if (factor < 0)
  8716. throw new Error(
  8717. 'Cannot create an arc with the given arguments');
  8718. center = new Point(rx * y / ry, -ry * x / rx)
  8719. .multiply((large === clockwise ? -1 : 1) * sqrt(factor))
  8720. .rotate(rotation).add(middle);
  8721. matrix = new Matrix().translate(center).rotate(rotation)
  8722. .scale(rx, ry);
  8723. vector = matrix._inverseTransform(from);
  8724. extent = vector.getDirectedAngle(matrix._inverseTransform(to));
  8725. if (!clockwise && extent > 0)
  8726. extent -= 360;
  8727. else if (clockwise && extent < 0)
  8728. extent += 360;
  8729. }
  8730. if (through) {
  8731. var l1 = new Line(from.add(through).divide(2),
  8732. through.subtract(from).rotate(90), true),
  8733. l2 = new Line(through.add(to).divide(2),
  8734. to.subtract(through).rotate(90), true),
  8735. line = new Line(from, to),
  8736. throughSide = line.getSide(through);
  8737. center = l1.intersect(l2, true);
  8738. if (!center) {
  8739. if (!throughSide)
  8740. return this.lineTo(to);
  8741. throw new Error(
  8742. 'Cannot create an arc with the given arguments');
  8743. }
  8744. vector = from.subtract(center);
  8745. extent = vector.getDirectedAngle(to.subtract(center));
  8746. var centerSide = line.getSide(center, true);
  8747. if (centerSide === 0) {
  8748. extent = throughSide * abs(extent);
  8749. } else if (throughSide === centerSide) {
  8750. extent += extent < 0 ? 360 : -360;
  8751. }
  8752. }
  8753. if (extent) {
  8754. var epsilon = 1e-7,
  8755. ext = abs(extent),
  8756. count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90),
  8757. inc = extent / count,
  8758. half = inc * Math.PI / 360,
  8759. z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
  8760. segments = [];
  8761. for (var i = 0; i <= count; i++) {
  8762. var pt = to,
  8763. out = null;
  8764. if (i < count) {
  8765. out = vector.rotate(90).multiply(z);
  8766. if (matrix) {
  8767. pt = matrix._transformPoint(vector);
  8768. out = matrix._transformPoint(vector.add(out))
  8769. .subtract(pt);
  8770. } else {
  8771. pt = center.add(vector);
  8772. }
  8773. }
  8774. if (!i) {
  8775. current.setHandleOut(out);
  8776. } else {
  8777. var _in = vector.rotate(-90).multiply(z);
  8778. if (matrix) {
  8779. _in = matrix._transformPoint(vector.add(_in))
  8780. .subtract(pt);
  8781. }
  8782. segments.push(new Segment(pt, _in, out));
  8783. }
  8784. vector = vector.rotate(inc);
  8785. }
  8786. this._add(segments);
  8787. }
  8788. },
  8789. lineBy: function() {
  8790. var to = Point.read(arguments),
  8791. current = getCurrentSegment(this)._point;
  8792. this.lineTo(current.add(to));
  8793. },
  8794. curveBy: function() {
  8795. var args = arguments,
  8796. through = Point.read(args),
  8797. to = Point.read(args),
  8798. parameter = Base.read(args),
  8799. current = getCurrentSegment(this)._point;
  8800. this.curveTo(current.add(through), current.add(to), parameter);
  8801. },
  8802. cubicCurveBy: function() {
  8803. var args = arguments,
  8804. handle1 = Point.read(args),
  8805. handle2 = Point.read(args),
  8806. to = Point.read(args),
  8807. current = getCurrentSegment(this)._point;
  8808. this.cubicCurveTo(current.add(handle1), current.add(handle2),
  8809. current.add(to));
  8810. },
  8811. quadraticCurveBy: function() {
  8812. var args = arguments,
  8813. handle = Point.read(args),
  8814. to = Point.read(args),
  8815. current = getCurrentSegment(this)._point;
  8816. this.quadraticCurveTo(current.add(handle), current.add(to));
  8817. },
  8818. arcBy: function() {
  8819. var args = arguments,
  8820. current = getCurrentSegment(this)._point,
  8821. point = current.add(Point.read(args)),
  8822. clockwise = Base.pick(Base.peek(args), true);
  8823. if (typeof clockwise === 'boolean') {
  8824. this.arcTo(point, clockwise);
  8825. } else {
  8826. this.arcTo(point, current.add(Point.read(args)));
  8827. }
  8828. },
  8829. closePath: function(tolerance) {
  8830. this.setClosed(true);
  8831. this.join(this, tolerance);
  8832. }
  8833. };
  8834. }, {
  8835. _getBounds: function(matrix, options) {
  8836. var method = options.handle
  8837. ? 'getHandleBounds'
  8838. : options.stroke
  8839. ? 'getStrokeBounds'
  8840. : 'getBounds';
  8841. return Path[method](this._segments, this._closed, this, matrix, options);
  8842. },
  8843. statics: {
  8844. getBounds: function(segments, closed, path, matrix, options, strokePadding) {
  8845. var first = segments[0];
  8846. if (!first)
  8847. return new Rectangle();
  8848. var coords = new Array(6),
  8849. prevCoords = first._transformCoordinates(matrix, new Array(6)),
  8850. min = prevCoords.slice(0, 2),
  8851. max = min.slice(),
  8852. roots = new Array(2);
  8853. function processSegment(segment) {
  8854. segment._transformCoordinates(matrix, coords);
  8855. for (var i = 0; i < 2; i++) {
  8856. Curve._addBounds(
  8857. prevCoords[i],
  8858. prevCoords[i + 4],
  8859. coords[i + 2],
  8860. coords[i],
  8861. i, strokePadding ? strokePadding[i] : 0, min, max, roots);
  8862. }
  8863. var tmp = prevCoords;
  8864. prevCoords = coords;
  8865. coords = tmp;
  8866. }
  8867. for (var i = 1, l = segments.length; i < l; i++)
  8868. processSegment(segments[i]);
  8869. if (closed)
  8870. processSegment(first);
  8871. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  8872. },
  8873. getStrokeBounds: function(segments, closed, path, matrix, options) {
  8874. var style = path.getStyle(),
  8875. stroke = style.hasStroke(),
  8876. strokeWidth = style.getStrokeWidth(),
  8877. strokeMatrix = stroke && path._getStrokeMatrix(matrix, options),
  8878. strokePadding = stroke && Path._getStrokePadding(strokeWidth,
  8879. strokeMatrix),
  8880. bounds = Path.getBounds(segments, closed, path, matrix, options,
  8881. strokePadding);
  8882. if (!stroke)
  8883. return bounds;
  8884. var strokeRadius = strokeWidth / 2,
  8885. join = style.getStrokeJoin(),
  8886. cap = style.getStrokeCap(),
  8887. miterLimit = style.getMiterLimit(),
  8888. joinBounds = new Rectangle(new Size(strokePadding));
  8889. function addPoint(point) {
  8890. bounds = bounds.include(point);
  8891. }
  8892. function addRound(segment) {
  8893. bounds = bounds.unite(
  8894. joinBounds.setCenter(segment._point.transform(matrix)));
  8895. }
  8896. function addJoin(segment, join) {
  8897. if (join === 'round' || segment.isSmooth()) {
  8898. addRound(segment);
  8899. } else {
  8900. Path._addBevelJoin(segment, join, strokeRadius, miterLimit,
  8901. matrix, strokeMatrix, addPoint);
  8902. }
  8903. }
  8904. function addCap(segment, cap) {
  8905. if (cap === 'round') {
  8906. addRound(segment);
  8907. } else {
  8908. Path._addSquareCap(segment, cap, strokeRadius, matrix,
  8909. strokeMatrix, addPoint);
  8910. }
  8911. }
  8912. var length = segments.length - (closed ? 0 : 1);
  8913. if (length > 0) {
  8914. for (var i = 1; i < length; i++) {
  8915. addJoin(segments[i], join);
  8916. }
  8917. if (closed) {
  8918. addJoin(segments[0], join);
  8919. } else {
  8920. addCap(segments[0], cap);
  8921. addCap(segments[segments.length - 1], cap);
  8922. }
  8923. }
  8924. return bounds;
  8925. },
  8926. _getStrokePadding: function(radius, matrix) {
  8927. if (!matrix)
  8928. return [radius, radius];
  8929. var hor = new Point(radius, 0).transform(matrix),
  8930. ver = new Point(0, radius).transform(matrix),
  8931. phi = hor.getAngleInRadians(),
  8932. a = hor.getLength(),
  8933. b = ver.getLength();
  8934. var sin = Math.sin(phi),
  8935. cos = Math.cos(phi),
  8936. tan = Math.tan(phi),
  8937. tx = Math.atan2(b * tan, a),
  8938. ty = Math.atan2(b, tan * a);
  8939. return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin),
  8940. Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
  8941. },
  8942. _addBevelJoin: function(segment, join, radius, miterLimit, matrix,
  8943. strokeMatrix, addPoint, isArea) {
  8944. var curve2 = segment.getCurve(),
  8945. curve1 = curve2.getPrevious(),
  8946. point = curve2.getPoint1().transform(matrix),
  8947. normal1 = curve1.getNormalAtTime(1).multiply(radius)
  8948. .transform(strokeMatrix),
  8949. normal2 = curve2.getNormalAtTime(0).multiply(radius)
  8950. .transform(strokeMatrix),
  8951. angle = normal1.getDirectedAngle(normal2);
  8952. if (angle < 0 || angle >= 180) {
  8953. normal1 = normal1.negate();
  8954. normal2 = normal2.negate();
  8955. }
  8956. if (isArea)
  8957. addPoint(point);
  8958. addPoint(point.add(normal1));
  8959. if (join === 'miter') {
  8960. var corner = new Line(point.add(normal1),
  8961. new Point(-normal1.y, normal1.x), true
  8962. ).intersect(new Line(point.add(normal2),
  8963. new Point(-normal2.y, normal2.x), true
  8964. ), true);
  8965. if (corner && point.getDistance(corner) <= miterLimit * radius) {
  8966. addPoint(corner);
  8967. }
  8968. }
  8969. addPoint(point.add(normal2));
  8970. },
  8971. _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix,
  8972. addPoint, isArea) {
  8973. var point = segment._point.transform(matrix),
  8974. loc = segment.getLocation(),
  8975. normal = loc.getNormal()
  8976. .multiply(loc.getTime() === 0 ? radius : -radius)
  8977. .transform(strokeMatrix);
  8978. if (cap === 'square') {
  8979. if (isArea) {
  8980. addPoint(point.subtract(normal));
  8981. addPoint(point.add(normal));
  8982. }
  8983. point = point.add(normal.rotate(-90));
  8984. }
  8985. addPoint(point.add(normal));
  8986. addPoint(point.subtract(normal));
  8987. },
  8988. getHandleBounds: function(segments, closed, path, matrix, options) {
  8989. var style = path.getStyle(),
  8990. stroke = options.stroke && style.hasStroke(),
  8991. strokePadding,
  8992. joinPadding;
  8993. if (stroke) {
  8994. var strokeMatrix = path._getStrokeMatrix(matrix, options),
  8995. strokeRadius = style.getStrokeWidth() / 2,
  8996. joinRadius = strokeRadius;
  8997. if (style.getStrokeJoin() === 'miter')
  8998. joinRadius = strokeRadius * style.getMiterLimit();
  8999. if (style.getStrokeCap() === 'square')
  9000. joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2);
  9001. strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix);
  9002. joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix);
  9003. }
  9004. var coords = new Array(6),
  9005. x1 = Infinity,
  9006. x2 = -x1,
  9007. y1 = x1,
  9008. y2 = x2;
  9009. for (var i = 0, l = segments.length; i < l; i++) {
  9010. var segment = segments[i];
  9011. segment._transformCoordinates(matrix, coords);
  9012. for (var j = 0; j < 6; j += 2) {
  9013. var padding = !j ? joinPadding : strokePadding,
  9014. paddingX = padding ? padding[0] : 0,
  9015. paddingY = padding ? padding[1] : 0,
  9016. x = coords[j],
  9017. y = coords[j + 1],
  9018. xn = x - paddingX,
  9019. xx = x + paddingX,
  9020. yn = y - paddingY,
  9021. yx = y + paddingY;
  9022. if (xn < x1) x1 = xn;
  9023. if (xx > x2) x2 = xx;
  9024. if (yn < y1) y1 = yn;
  9025. if (yx > y2) y2 = yx;
  9026. }
  9027. }
  9028. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  9029. }
  9030. }});
  9031. Path.inject({ statics: new function() {
  9032. var kappa = 0.5522847498307936,
  9033. ellipseSegments = [
  9034. new Segment([-1, 0], [0, kappa ], [0, -kappa]),
  9035. new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
  9036. new Segment([1, 0], [0, -kappa], [0, kappa ]),
  9037. new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
  9038. ];
  9039. function createPath(segments, closed, args) {
  9040. var props = Base.getNamed(args),
  9041. path = new Path(props && props.insert == false && Item.NO_INSERT);
  9042. path._add(segments);
  9043. path._closed = closed;
  9044. return path.set(props, { insert: true });
  9045. }
  9046. function createEllipse(center, radius, args) {
  9047. var segments = new Array(4);
  9048. for (var i = 0; i < 4; i++) {
  9049. var segment = ellipseSegments[i];
  9050. segments[i] = new Segment(
  9051. segment._point.multiply(radius).add(center),
  9052. segment._handleIn.multiply(radius),
  9053. segment._handleOut.multiply(radius)
  9054. );
  9055. }
  9056. return createPath(segments, true, args);
  9057. }
  9058. return {
  9059. Line: function() {
  9060. var args = arguments;
  9061. return createPath([
  9062. new Segment(Point.readNamed(args, 'from')),
  9063. new Segment(Point.readNamed(args, 'to'))
  9064. ], false, args);
  9065. },
  9066. Circle: function() {
  9067. var args = arguments,
  9068. center = Point.readNamed(args, 'center'),
  9069. radius = Base.readNamed(args, 'radius');
  9070. return createEllipse(center, new Size(radius), args);
  9071. },
  9072. Rectangle: function() {
  9073. var args = arguments,
  9074. rect = Rectangle.readNamed(args, 'rectangle'),
  9075. radius = Size.readNamed(args, 'radius', 0,
  9076. { readNull: true }),
  9077. bl = rect.getBottomLeft(true),
  9078. tl = rect.getTopLeft(true),
  9079. tr = rect.getTopRight(true),
  9080. br = rect.getBottomRight(true),
  9081. segments;
  9082. if (!radius || radius.isZero()) {
  9083. segments = [
  9084. new Segment(bl),
  9085. new Segment(tl),
  9086. new Segment(tr),
  9087. new Segment(br)
  9088. ];
  9089. } else {
  9090. radius = Size.min(radius, rect.getSize(true).divide(2));
  9091. var rx = radius.width,
  9092. ry = radius.height,
  9093. hx = rx * kappa,
  9094. hy = ry * kappa;
  9095. segments = [
  9096. new Segment(bl.add(rx, 0), null, [-hx, 0]),
  9097. new Segment(bl.subtract(0, ry), [0, hy]),
  9098. new Segment(tl.add(0, ry), null, [0, -hy]),
  9099. new Segment(tl.add(rx, 0), [-hx, 0], null),
  9100. new Segment(tr.subtract(rx, 0), null, [hx, 0]),
  9101. new Segment(tr.add(0, ry), [0, -hy], null),
  9102. new Segment(br.subtract(0, ry), null, [0, hy]),
  9103. new Segment(br.subtract(rx, 0), [hx, 0])
  9104. ];
  9105. }
  9106. return createPath(segments, true, args);
  9107. },
  9108. RoundRectangle: '#Rectangle',
  9109. Ellipse: function() {
  9110. var args = arguments,
  9111. ellipse = Shape._readEllipse(args);
  9112. return createEllipse(ellipse.center, ellipse.radius, args);
  9113. },
  9114. Oval: '#Ellipse',
  9115. Arc: function() {
  9116. var args = arguments,
  9117. from = Point.readNamed(args, 'from'),
  9118. through = Point.readNamed(args, 'through'),
  9119. to = Point.readNamed(args, 'to'),
  9120. props = Base.getNamed(args),
  9121. path = new Path(props && props.insert == false
  9122. && Item.NO_INSERT);
  9123. path.moveTo(from);
  9124. path.arcTo(through, to);
  9125. return path.set(props);
  9126. },
  9127. RegularPolygon: function() {
  9128. var args = arguments,
  9129. center = Point.readNamed(args, 'center'),
  9130. sides = Base.readNamed(args, 'sides'),
  9131. radius = Base.readNamed(args, 'radius'),
  9132. step = 360 / sides,
  9133. three = sides % 3 === 0,
  9134. vector = new Point(0, three ? -radius : radius),
  9135. offset = three ? -1 : 0.5,
  9136. segments = new Array(sides);
  9137. for (var i = 0; i < sides; i++)
  9138. segments[i] = new Segment(center.add(
  9139. vector.rotate((i + offset) * step)));
  9140. return createPath(segments, true, args);
  9141. },
  9142. Star: function() {
  9143. var args = arguments,
  9144. center = Point.readNamed(args, 'center'),
  9145. points = Base.readNamed(args, 'points') * 2,
  9146. radius1 = Base.readNamed(args, 'radius1'),
  9147. radius2 = Base.readNamed(args, 'radius2'),
  9148. step = 360 / points,
  9149. vector = new Point(0, -1),
  9150. segments = new Array(points);
  9151. for (var i = 0; i < points; i++)
  9152. segments[i] = new Segment(center.add(vector.rotate(step * i)
  9153. .multiply(i % 2 ? radius2 : radius1)));
  9154. return createPath(segments, true, args);
  9155. }
  9156. };
  9157. }});
  9158. var CompoundPath = PathItem.extend({
  9159. _class: 'CompoundPath',
  9160. _serializeFields: {
  9161. children: []
  9162. },
  9163. beans: true,
  9164. initialize: function CompoundPath(arg) {
  9165. this._children = [];
  9166. this._namedChildren = {};
  9167. if (!this._initialize(arg)) {
  9168. if (typeof arg === 'string') {
  9169. this.setPathData(arg);
  9170. } else {
  9171. this.addChildren(Array.isArray(arg) ? arg : arguments);
  9172. }
  9173. }
  9174. },
  9175. insertChildren: function insertChildren(index, items) {
  9176. var list = items,
  9177. first = list[0];
  9178. if (first && typeof first[0] === 'number')
  9179. list = [list];
  9180. for (var i = items.length - 1; i >= 0; i--) {
  9181. var item = list[i];
  9182. if (list === items && !(item instanceof Path))
  9183. list = Base.slice(list);
  9184. if (Array.isArray(item)) {
  9185. list[i] = new Path({ segments: item, insert: false });
  9186. } else if (item instanceof CompoundPath) {
  9187. list.splice.apply(list, [i, 1].concat(item.removeChildren()));
  9188. item.remove();
  9189. }
  9190. }
  9191. return insertChildren.base.call(this, index, list);
  9192. },
  9193. reduce: function reduce(options) {
  9194. var children = this._children;
  9195. for (var i = children.length - 1; i >= 0; i--) {
  9196. var path = children[i].reduce(options);
  9197. if (path.isEmpty())
  9198. path.remove();
  9199. }
  9200. if (!children.length) {
  9201. var path = new Path(Item.NO_INSERT);
  9202. path.copyAttributes(this);
  9203. path.insertAbove(this);
  9204. this.remove();
  9205. return path;
  9206. }
  9207. return reduce.base.call(this);
  9208. },
  9209. isClosed: function() {
  9210. var children = this._children;
  9211. for (var i = 0, l = children.length; i < l; i++) {
  9212. if (!children[i]._closed)
  9213. return false;
  9214. }
  9215. return true;
  9216. },
  9217. setClosed: function(closed) {
  9218. var children = this._children;
  9219. for (var i = 0, l = children.length; i < l; i++) {
  9220. children[i].setClosed(closed);
  9221. }
  9222. },
  9223. getFirstSegment: function() {
  9224. var first = this.getFirstChild();
  9225. return first && first.getFirstSegment();
  9226. },
  9227. getLastSegment: function() {
  9228. var last = this.getLastChild();
  9229. return last && last.getLastSegment();
  9230. },
  9231. getCurves: function() {
  9232. var children = this._children,
  9233. curves = [];
  9234. for (var i = 0, l = children.length; i < l; i++) {
  9235. Base.push(curves, children[i].getCurves());
  9236. }
  9237. return curves;
  9238. },
  9239. getFirstCurve: function() {
  9240. var first = this.getFirstChild();
  9241. return first && first.getFirstCurve();
  9242. },
  9243. getLastCurve: function() {
  9244. var last = this.getLastChild();
  9245. return last && last.getLastCurve();
  9246. },
  9247. getArea: function() {
  9248. var children = this._children,
  9249. area = 0;
  9250. for (var i = 0, l = children.length; i < l; i++)
  9251. area += children[i].getArea();
  9252. return area;
  9253. },
  9254. getLength: function() {
  9255. var children = this._children,
  9256. length = 0;
  9257. for (var i = 0, l = children.length; i < l; i++)
  9258. length += children[i].getLength();
  9259. return length;
  9260. },
  9261. getPathData: function(_matrix, _precision) {
  9262. var children = this._children,
  9263. paths = [];
  9264. for (var i = 0, l = children.length; i < l; i++) {
  9265. var child = children[i],
  9266. mx = child._matrix;
  9267. paths.push(child.getPathData(_matrix && !mx.isIdentity()
  9268. ? _matrix.appended(mx) : _matrix, _precision));
  9269. }
  9270. return paths.join('');
  9271. },
  9272. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  9273. return _hitTestChildren.base.call(this, point,
  9274. options.class === Path || options.type === 'path' ? options
  9275. : Base.set({}, options, { fill: false }),
  9276. viewMatrix);
  9277. },
  9278. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  9279. var children = this._children;
  9280. if (!children.length)
  9281. return;
  9282. param = param.extend({ dontStart: true, dontFinish: true });
  9283. ctx.beginPath();
  9284. for (var i = 0, l = children.length; i < l; i++)
  9285. children[i].draw(ctx, param, strokeMatrix);
  9286. if (!param.clip) {
  9287. this._setStyles(ctx, param, viewMatrix);
  9288. var style = this._style;
  9289. if (style.hasFill()) {
  9290. ctx.fill(style.getFillRule());
  9291. ctx.shadowColor = 'rgba(0,0,0,0)';
  9292. }
  9293. if (style.hasStroke())
  9294. ctx.stroke();
  9295. }
  9296. },
  9297. _drawSelected: function(ctx, matrix, selectionItems) {
  9298. var children = this._children;
  9299. for (var i = 0, l = children.length; i < l; i++) {
  9300. var child = children[i],
  9301. mx = child._matrix;
  9302. if (!selectionItems[child._id]) {
  9303. child._drawSelected(ctx, mx.isIdentity() ? matrix
  9304. : matrix.appended(mx));
  9305. }
  9306. }
  9307. }
  9308. },
  9309. new function() {
  9310. function getCurrentPath(that, check) {
  9311. var children = that._children;
  9312. if (check && !children.length)
  9313. throw new Error('Use a moveTo() command first');
  9314. return children[children.length - 1];
  9315. }
  9316. return Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
  9317. 'arcTo', 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy',
  9318. 'arcBy'],
  9319. function(key) {
  9320. this[key] = function() {
  9321. var path = getCurrentPath(this, true);
  9322. path[key].apply(path, arguments);
  9323. };
  9324. }, {
  9325. moveTo: function() {
  9326. var current = getCurrentPath(this),
  9327. path = current && current.isEmpty() ? current
  9328. : new Path(Item.NO_INSERT);
  9329. if (path !== current)
  9330. this.addChild(path);
  9331. path.moveTo.apply(path, arguments);
  9332. },
  9333. moveBy: function() {
  9334. var current = getCurrentPath(this, true),
  9335. last = current && current.getLastSegment(),
  9336. point = Point.read(arguments);
  9337. this.moveTo(last ? point.add(last._point) : point);
  9338. },
  9339. closePath: function(tolerance) {
  9340. getCurrentPath(this, true).closePath(tolerance);
  9341. }
  9342. }
  9343. );
  9344. }, Base.each(['reverse', 'flatten', 'simplify', 'smooth'], function(key) {
  9345. this[key] = function(param) {
  9346. var children = this._children,
  9347. res;
  9348. for (var i = 0, l = children.length; i < l; i++) {
  9349. res = children[i][key](param) || res;
  9350. }
  9351. return res;
  9352. };
  9353. }, {}));
  9354. PathItem.inject(new function() {
  9355. var min = Math.min,
  9356. max = Math.max,
  9357. abs = Math.abs,
  9358. operators = {
  9359. unite: { '1': true, '2': true },
  9360. intersect: { '2': true },
  9361. subtract: { '1': true },
  9362. exclude: { '1': true, '-1': true }
  9363. };
  9364. function getPaths(path) {
  9365. return path._children || [path];
  9366. }
  9367. function preparePath(path, resolve) {
  9368. var res = path
  9369. .clone(false)
  9370. .reduce({ simplify: true })
  9371. .transform(null, true, true);
  9372. if (resolve) {
  9373. var paths = getPaths(res);
  9374. for (var i = 0, l = paths.length; i < l; i++) {
  9375. var path = paths[i];
  9376. if (!path._closed && !path.isEmpty()) {
  9377. path.closePath(1e-12);
  9378. path.getFirstSegment().setHandleIn(0, 0);
  9379. path.getLastSegment().setHandleOut(0, 0);
  9380. }
  9381. }
  9382. res = res
  9383. .resolveCrossings()
  9384. .reorient(res.getFillRule() === 'nonzero', true);
  9385. }
  9386. return res;
  9387. }
  9388. function createResult(paths, simplify, path1, path2, options) {
  9389. var result = new CompoundPath(Item.NO_INSERT);
  9390. result.addChildren(paths, true);
  9391. result = result.reduce({ simplify: simplify });
  9392. if (!(options && options.insert == false)) {
  9393. result.insertAbove(path2 && path1.isSibling(path2)
  9394. && path1.getIndex() < path2.getIndex() ? path2 : path1);
  9395. }
  9396. result.copyAttributes(path1, true);
  9397. return result;
  9398. }
  9399. function filterIntersection(inter) {
  9400. return inter.hasOverlap() || inter.isCrossing();
  9401. }
  9402. function traceBoolean(path1, path2, operation, options) {
  9403. if (options && (options.trace == false || options.stroke) &&
  9404. /^(subtract|intersect)$/.test(operation))
  9405. return splitBoolean(path1, path2, operation);
  9406. var _path1 = preparePath(path1, true),
  9407. _path2 = path2 && path1 !== path2 && preparePath(path2, true),
  9408. operator = operators[operation];
  9409. operator[operation] = true;
  9410. if (_path2 && (operator.subtract || operator.exclude)
  9411. ^ (_path2.isClockwise() ^ _path1.isClockwise()))
  9412. _path2.reverse();
  9413. var crossings = divideLocations(CurveLocation.expand(
  9414. _path1.getIntersections(_path2, filterIntersection))),
  9415. paths1 = getPaths(_path1),
  9416. paths2 = _path2 && getPaths(_path2),
  9417. segments = [],
  9418. curves = [],
  9419. paths;
  9420. function collectPaths(paths) {
  9421. for (var i = 0, l = paths.length; i < l; i++) {
  9422. var path = paths[i];
  9423. Base.push(segments, path._segments);
  9424. Base.push(curves, path.getCurves());
  9425. path._overlapsOnly = true;
  9426. }
  9427. }
  9428. function getCurves(indices) {
  9429. var list = [];
  9430. for (var i = 0, l = indices && indices.length; i < l; i++) {
  9431. list.push(curves[indices[i]]);
  9432. }
  9433. return list;
  9434. }
  9435. if (crossings.length) {
  9436. collectPaths(paths1);
  9437. if (paths2)
  9438. collectPaths(paths2);
  9439. var curvesValues = new Array(curves.length);
  9440. for (var i = 0, l = curves.length; i < l; i++) {
  9441. curvesValues[i] = curves[i].getValues();
  9442. }
  9443. var curveCollisions = CollisionDetection.findCurveBoundsCollisions(
  9444. curvesValues, curvesValues, 0, true);
  9445. var curveCollisionsMap = {};
  9446. for (var i = 0; i < curves.length; i++) {
  9447. var curve = curves[i],
  9448. id = curve._path._id,
  9449. map = curveCollisionsMap[id] = curveCollisionsMap[id] || {};
  9450. map[curve.getIndex()] = {
  9451. hor: getCurves(curveCollisions[i].hor),
  9452. ver: getCurves(curveCollisions[i].ver)
  9453. };
  9454. }
  9455. for (var i = 0, l = crossings.length; i < l; i++) {
  9456. propagateWinding(crossings[i]._segment, _path1, _path2,
  9457. curveCollisionsMap, operator);
  9458. }
  9459. for (var i = 0, l = segments.length; i < l; i++) {
  9460. var segment = segments[i],
  9461. inter = segment._intersection;
  9462. if (!segment._winding) {
  9463. propagateWinding(segment, _path1, _path2,
  9464. curveCollisionsMap, operator);
  9465. }
  9466. if (!(inter && inter._overlap))
  9467. segment._path._overlapsOnly = false;
  9468. }
  9469. paths = tracePaths(segments, operator);
  9470. } else {
  9471. paths = reorientPaths(
  9472. paths2 ? paths1.concat(paths2) : paths1.slice(),
  9473. function(w) {
  9474. return !!operator[w];
  9475. });
  9476. }
  9477. return createResult(paths, true, path1, path2, options);
  9478. }
  9479. function splitBoolean(path1, path2, operation) {
  9480. var _path1 = preparePath(path1),
  9481. _path2 = preparePath(path2),
  9482. crossings = _path1.getIntersections(_path2, filterIntersection),
  9483. subtract = operation === 'subtract',
  9484. divide = operation === 'divide',
  9485. added = {},
  9486. paths = [];
  9487. function addPath(path) {
  9488. if (!added[path._id] && (divide ||
  9489. _path2.contains(path.getPointAt(path.getLength() / 2))
  9490. ^ subtract)) {
  9491. paths.unshift(path);
  9492. return added[path._id] = true;
  9493. }
  9494. }
  9495. for (var i = crossings.length - 1; i >= 0; i--) {
  9496. var path = crossings[i].split();
  9497. if (path) {
  9498. if (addPath(path))
  9499. path.getFirstSegment().setHandleIn(0, 0);
  9500. _path1.getLastSegment().setHandleOut(0, 0);
  9501. }
  9502. }
  9503. addPath(_path1);
  9504. return createResult(paths, false, path1, path2);
  9505. }
  9506. function linkIntersections(from, to) {
  9507. var prev = from;
  9508. while (prev) {
  9509. if (prev === to)
  9510. return;
  9511. prev = prev._previous;
  9512. }
  9513. while (from._next && from._next !== to)
  9514. from = from._next;
  9515. if (!from._next) {
  9516. while (to._previous)
  9517. to = to._previous;
  9518. from._next = to;
  9519. to._previous = from;
  9520. }
  9521. }
  9522. function clearCurveHandles(curves) {
  9523. for (var i = curves.length - 1; i >= 0; i--)
  9524. curves[i].clearHandles();
  9525. }
  9526. function reorientPaths(paths, isInside, clockwise) {
  9527. var length = paths && paths.length;
  9528. if (length) {
  9529. var lookup = Base.each(paths, function (path, i) {
  9530. this[path._id] = {
  9531. container: null,
  9532. winding: path.isClockwise() ? 1 : -1,
  9533. index: i
  9534. };
  9535. }, {}),
  9536. sorted = paths.slice().sort(function (a, b) {
  9537. return abs(b.getArea()) - abs(a.getArea());
  9538. }),
  9539. first = sorted[0];
  9540. var collisions = CollisionDetection.findItemBoundsCollisions(sorted,
  9541. null, Numerical.GEOMETRIC_EPSILON);
  9542. if (clockwise == null)
  9543. clockwise = first.isClockwise();
  9544. for (var i = 0; i < length; i++) {
  9545. var path1 = sorted[i],
  9546. entry1 = lookup[path1._id],
  9547. containerWinding = 0,
  9548. indices = collisions[i];
  9549. if (indices) {
  9550. var point = null;
  9551. for (var j = indices.length - 1; j >= 0; j--) {
  9552. if (indices[j] < i) {
  9553. point = point || path1.getInteriorPoint();
  9554. var path2 = sorted[indices[j]];
  9555. if (path2.contains(point)) {
  9556. var entry2 = lookup[path2._id];
  9557. containerWinding = entry2.winding;
  9558. entry1.winding += containerWinding;
  9559. entry1.container = entry2.exclude
  9560. ? entry2.container : path2;
  9561. break;
  9562. }
  9563. }
  9564. }
  9565. }
  9566. if (isInside(entry1.winding) === isInside(containerWinding)) {
  9567. entry1.exclude = true;
  9568. paths[entry1.index] = null;
  9569. } else {
  9570. var container = entry1.container;
  9571. path1.setClockwise(
  9572. container ? !container.isClockwise() : clockwise);
  9573. }
  9574. }
  9575. }
  9576. return paths;
  9577. }
  9578. function divideLocations(locations, include, clearLater) {
  9579. var results = include && [],
  9580. tMin = 1e-8,
  9581. tMax = 1 - tMin,
  9582. clearHandles = false,
  9583. clearCurves = clearLater || [],
  9584. clearLookup = clearLater && {},
  9585. renormalizeLocs,
  9586. prevCurve,
  9587. prevTime;
  9588. function getId(curve) {
  9589. return curve._path._id + '.' + curve._segment1._index;
  9590. }
  9591. for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) {
  9592. var curve = clearLater[i];
  9593. if (curve._path)
  9594. clearLookup[getId(curve)] = true;
  9595. }
  9596. for (var i = locations.length - 1; i >= 0; i--) {
  9597. var loc = locations[i],
  9598. time = loc._time,
  9599. origTime = time,
  9600. exclude = include && !include(loc),
  9601. curve = loc._curve,
  9602. segment;
  9603. if (curve) {
  9604. if (curve !== prevCurve) {
  9605. clearHandles = !curve.hasHandles()
  9606. || clearLookup && clearLookup[getId(curve)];
  9607. renormalizeLocs = [];
  9608. prevTime = null;
  9609. prevCurve = curve;
  9610. } else if (prevTime >= tMin) {
  9611. time /= prevTime;
  9612. }
  9613. }
  9614. if (exclude) {
  9615. if (renormalizeLocs)
  9616. renormalizeLocs.push(loc);
  9617. continue;
  9618. } else if (include) {
  9619. results.unshift(loc);
  9620. }
  9621. prevTime = origTime;
  9622. if (time < tMin) {
  9623. segment = curve._segment1;
  9624. } else if (time > tMax) {
  9625. segment = curve._segment2;
  9626. } else {
  9627. var newCurve = curve.divideAtTime(time, true);
  9628. if (clearHandles)
  9629. clearCurves.push(curve, newCurve);
  9630. segment = newCurve._segment1;
  9631. for (var j = renormalizeLocs.length - 1; j >= 0; j--) {
  9632. var l = renormalizeLocs[j];
  9633. l._time = (l._time - time) / (1 - time);
  9634. }
  9635. }
  9636. loc._setSegment(segment);
  9637. var inter = segment._intersection,
  9638. dest = loc._intersection;
  9639. if (inter) {
  9640. linkIntersections(inter, dest);
  9641. var other = inter;
  9642. while (other) {
  9643. linkIntersections(other._intersection, inter);
  9644. other = other._next;
  9645. }
  9646. } else {
  9647. segment._intersection = dest;
  9648. }
  9649. }
  9650. if (!clearLater)
  9651. clearCurveHandles(clearCurves);
  9652. return results || locations;
  9653. }
  9654. function getWinding(point, curves, dir, closed, dontFlip) {
  9655. var curvesList = Array.isArray(curves)
  9656. ? curves
  9657. : curves[dir ? 'hor' : 'ver'];
  9658. var ia = dir ? 1 : 0,
  9659. io = ia ^ 1,
  9660. pv = [point.x, point.y],
  9661. pa = pv[ia],
  9662. po = pv[io],
  9663. windingEpsilon = 1e-9,
  9664. qualityEpsilon = 1e-6,
  9665. paL = pa - windingEpsilon,
  9666. paR = pa + windingEpsilon,
  9667. windingL = 0,
  9668. windingR = 0,
  9669. pathWindingL = 0,
  9670. pathWindingR = 0,
  9671. onPath = false,
  9672. onAnyPath = false,
  9673. quality = 1,
  9674. roots = [],
  9675. vPrev,
  9676. vClose;
  9677. function addWinding(v) {
  9678. var o0 = v[io + 0],
  9679. o3 = v[io + 6];
  9680. if (po < min(o0, o3) || po > max(o0, o3)) {
  9681. return;
  9682. }
  9683. var a0 = v[ia + 0],
  9684. a1 = v[ia + 2],
  9685. a2 = v[ia + 4],
  9686. a3 = v[ia + 6];
  9687. if (o0 === o3) {
  9688. if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) {
  9689. onPath = true;
  9690. }
  9691. return;
  9692. }
  9693. var t = po === o0 ? 0
  9694. : po === o3 ? 1
  9695. : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3)
  9696. ? 1
  9697. : Curve.solveCubic(v, io, po, roots, 0, 1) > 0
  9698. ? roots[0]
  9699. : 1,
  9700. a = t === 0 ? a0
  9701. : t === 1 ? a3
  9702. : Curve.getPoint(v, t)[dir ? 'y' : 'x'],
  9703. winding = o0 > o3 ? 1 : -1,
  9704. windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1,
  9705. a3Prev = vPrev[ia + 6];
  9706. if (po !== o0) {
  9707. if (a < paL) {
  9708. pathWindingL += winding;
  9709. } else if (a > paR) {
  9710. pathWindingR += winding;
  9711. } else {
  9712. onPath = true;
  9713. }
  9714. if (a > pa - qualityEpsilon && a < pa + qualityEpsilon)
  9715. quality /= 2;
  9716. } else {
  9717. if (winding !== windingPrev) {
  9718. if (a0 < paL) {
  9719. pathWindingL += winding;
  9720. } else if (a0 > paR) {
  9721. pathWindingR += winding;
  9722. }
  9723. } else if (a0 != a3Prev) {
  9724. if (a3Prev < paR && a > paR) {
  9725. pathWindingR += winding;
  9726. onPath = true;
  9727. } else if (a3Prev > paL && a < paL) {
  9728. pathWindingL += winding;
  9729. onPath = true;
  9730. }
  9731. }
  9732. quality /= 4;
  9733. }
  9734. vPrev = v;
  9735. return !dontFlip && a > paL && a < paR
  9736. && Curve.getTangent(v, t)[dir ? 'x' : 'y'] === 0
  9737. && getWinding(point, curves, !dir, closed, true);
  9738. }
  9739. function handleCurve(v) {
  9740. var o0 = v[io + 0],
  9741. o1 = v[io + 2],
  9742. o2 = v[io + 4],
  9743. o3 = v[io + 6];
  9744. if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) {
  9745. var a0 = v[ia + 0],
  9746. a1 = v[ia + 2],
  9747. a2 = v[ia + 4],
  9748. a3 = v[ia + 6],
  9749. monoCurves = paL > max(a0, a1, a2, a3) ||
  9750. paR < min(a0, a1, a2, a3)
  9751. ? [v] : Curve.getMonoCurves(v, dir),
  9752. res;
  9753. for (var i = 0, l = monoCurves.length; i < l; i++) {
  9754. if (res = addWinding(monoCurves[i]))
  9755. return res;
  9756. }
  9757. }
  9758. }
  9759. for (var i = 0, l = curvesList.length; i < l; i++) {
  9760. var curve = curvesList[i],
  9761. path = curve._path,
  9762. v = curve.getValues(),
  9763. res;
  9764. if (!i || curvesList[i - 1]._path !== path) {
  9765. vPrev = null;
  9766. if (!path._closed) {
  9767. vClose = Curve.getValues(
  9768. path.getLastCurve().getSegment2(),
  9769. curve.getSegment1(),
  9770. null, !closed);
  9771. if (vClose[io] !== vClose[io + 6]) {
  9772. vPrev = vClose;
  9773. }
  9774. }
  9775. if (!vPrev) {
  9776. vPrev = v;
  9777. var prev = path.getLastCurve();
  9778. while (prev && prev !== curve) {
  9779. var v2 = prev.getValues();
  9780. if (v2[io] !== v2[io + 6]) {
  9781. vPrev = v2;
  9782. break;
  9783. }
  9784. prev = prev.getPrevious();
  9785. }
  9786. }
  9787. }
  9788. if (res = handleCurve(v))
  9789. return res;
  9790. if (i + 1 === l || curvesList[i + 1]._path !== path) {
  9791. if (vClose && (res = handleCurve(vClose)))
  9792. return res;
  9793. if (onPath && !pathWindingL && !pathWindingR) {
  9794. pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir
  9795. ? 1 : -1;
  9796. }
  9797. windingL += pathWindingL;
  9798. windingR += pathWindingR;
  9799. pathWindingL = pathWindingR = 0;
  9800. if (onPath) {
  9801. onAnyPath = true;
  9802. onPath = false;
  9803. }
  9804. vClose = null;
  9805. }
  9806. }
  9807. windingL = abs(windingL);
  9808. windingR = abs(windingR);
  9809. return {
  9810. winding: max(windingL, windingR),
  9811. windingL: windingL,
  9812. windingR: windingR,
  9813. quality: quality,
  9814. onPath: onAnyPath
  9815. };
  9816. }
  9817. function propagateWinding(segment, path1, path2, curveCollisionsMap,
  9818. operator) {
  9819. var chain = [],
  9820. start = segment,
  9821. totalLength = 0,
  9822. winding;
  9823. do {
  9824. var curve = segment.getCurve();
  9825. if (curve) {
  9826. var length = curve.getLength();
  9827. chain.push({ segment: segment, curve: curve, length: length });
  9828. totalLength += length;
  9829. }
  9830. segment = segment.getNext();
  9831. } while (segment && !segment._intersection && segment !== start);
  9832. var offsets = [0.5, 0.25, 0.75],
  9833. winding = { winding: 0, quality: -1 },
  9834. tMin = 1e-3,
  9835. tMax = 1 - tMin;
  9836. for (var i = 0; i < offsets.length && winding.quality < 0.5; i++) {
  9837. var length = totalLength * offsets[i];
  9838. for (var j = 0, l = chain.length; j < l; j++) {
  9839. var entry = chain[j],
  9840. curveLength = entry.length;
  9841. if (length <= curveLength) {
  9842. var curve = entry.curve,
  9843. path = curve._path,
  9844. parent = path._parent,
  9845. operand = parent instanceof CompoundPath ? parent : path,
  9846. t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax),
  9847. pt = curve.getPointAtTime(t),
  9848. dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2;
  9849. var wind = null;
  9850. if (operator.subtract && path2) {
  9851. var otherPath = operand === path1 ? path2 : path1,
  9852. pathWinding = otherPath._getWinding(pt, dir, true);
  9853. if (operand === path1 && pathWinding.winding ||
  9854. operand === path2 && !pathWinding.winding) {
  9855. if (pathWinding.quality < 1) {
  9856. continue;
  9857. } else {
  9858. wind = { winding: 0, quality: 1 };
  9859. }
  9860. }
  9861. }
  9862. wind = wind || getWinding(
  9863. pt, curveCollisionsMap[path._id][curve.getIndex()],
  9864. dir, true);
  9865. if (wind.quality > winding.quality)
  9866. winding = wind;
  9867. break;
  9868. }
  9869. length -= curveLength;
  9870. }
  9871. }
  9872. for (var j = chain.length - 1; j >= 0; j--) {
  9873. chain[j].segment._winding = winding;
  9874. }
  9875. }
  9876. function tracePaths(segments, operator) {
  9877. var paths = [],
  9878. starts;
  9879. function isValid(seg) {
  9880. var winding;
  9881. return !!(seg && !seg._visited && (!operator
  9882. || operator[(winding = seg._winding || {}).winding]
  9883. && !(operator.unite && winding.winding === 2
  9884. && winding.windingL && winding.windingR)));
  9885. }
  9886. function isStart(seg) {
  9887. if (seg) {
  9888. for (var i = 0, l = starts.length; i < l; i++) {
  9889. if (seg === starts[i])
  9890. return true;
  9891. }
  9892. }
  9893. return false;
  9894. }
  9895. function visitPath(path) {
  9896. var segments = path._segments;
  9897. for (var i = 0, l = segments.length; i < l; i++) {
  9898. segments[i]._visited = true;
  9899. }
  9900. }
  9901. function getCrossingSegments(segment, collectStarts) {
  9902. var inter = segment._intersection,
  9903. start = inter,
  9904. crossings = [];
  9905. if (collectStarts)
  9906. starts = [segment];
  9907. function collect(inter, end) {
  9908. while (inter && inter !== end) {
  9909. var other = inter._segment,
  9910. path = other && other._path;
  9911. if (path) {
  9912. var next = other.getNext() || path.getFirstSegment(),
  9913. nextInter = next._intersection;
  9914. if (other !== segment && (isStart(other)
  9915. || isStart(next)
  9916. || next && (isValid(other) && (isValid(next)
  9917. || nextInter && isValid(nextInter._segment))))
  9918. ) {
  9919. crossings.push(other);
  9920. }
  9921. if (collectStarts)
  9922. starts.push(other);
  9923. }
  9924. inter = inter._next;
  9925. }
  9926. }
  9927. if (inter) {
  9928. collect(inter);
  9929. while (inter && inter._previous)
  9930. inter = inter._previous;
  9931. collect(inter, start);
  9932. }
  9933. return crossings;
  9934. }
  9935. segments.sort(function(seg1, seg2) {
  9936. var inter1 = seg1._intersection,
  9937. inter2 = seg2._intersection,
  9938. over1 = !!(inter1 && inter1._overlap),
  9939. over2 = !!(inter2 && inter2._overlap),
  9940. path1 = seg1._path,
  9941. path2 = seg2._path;
  9942. return over1 ^ over2
  9943. ? over1 ? 1 : -1
  9944. : !inter1 ^ !inter2
  9945. ? inter1 ? 1 : -1
  9946. : path1 !== path2
  9947. ? path1._id - path2._id
  9948. : seg1._index - seg2._index;
  9949. });
  9950. for (var i = 0, l = segments.length; i < l; i++) {
  9951. var seg = segments[i],
  9952. valid = isValid(seg),
  9953. path = null,
  9954. finished = false,
  9955. closed = true,
  9956. branches = [],
  9957. branch,
  9958. visited,
  9959. handleIn;
  9960. if (valid && seg._path._overlapsOnly) {
  9961. var path1 = seg._path,
  9962. path2 = seg._intersection._segment._path;
  9963. if (path1.compare(path2)) {
  9964. if (path1.getArea())
  9965. paths.push(path1.clone(false));
  9966. visitPath(path1);
  9967. visitPath(path2);
  9968. valid = false;
  9969. }
  9970. }
  9971. while (valid) {
  9972. var first = !path,
  9973. crossings = getCrossingSegments(seg, first),
  9974. other = crossings.shift(),
  9975. finished = !first && (isStart(seg) || isStart(other)),
  9976. cross = !finished && other;
  9977. if (first) {
  9978. path = new Path(Item.NO_INSERT);
  9979. branch = null;
  9980. }
  9981. if (finished) {
  9982. if (seg.isFirst() || seg.isLast())
  9983. closed = seg._path._closed;
  9984. seg._visited = true;
  9985. break;
  9986. }
  9987. if (cross && branch) {
  9988. branches.push(branch);
  9989. branch = null;
  9990. }
  9991. if (!branch) {
  9992. if (cross)
  9993. crossings.push(seg);
  9994. branch = {
  9995. start: path._segments.length,
  9996. crossings: crossings,
  9997. visited: visited = [],
  9998. handleIn: handleIn
  9999. };
  10000. }
  10001. if (cross)
  10002. seg = other;
  10003. if (!isValid(seg)) {
  10004. path.removeSegments(branch.start);
  10005. for (var j = 0, k = visited.length; j < k; j++) {
  10006. visited[j]._visited = false;
  10007. }
  10008. visited.length = 0;
  10009. do {
  10010. seg = branch && branch.crossings.shift();
  10011. if (!seg || !seg._path) {
  10012. seg = null;
  10013. branch = branches.pop();
  10014. if (branch) {
  10015. visited = branch.visited;
  10016. handleIn = branch.handleIn;
  10017. }
  10018. }
  10019. } while (branch && !isValid(seg));
  10020. if (!seg)
  10021. break;
  10022. }
  10023. var next = seg.getNext();
  10024. path.add(new Segment(seg._point, handleIn,
  10025. next && seg._handleOut));
  10026. seg._visited = true;
  10027. visited.push(seg);
  10028. seg = next || seg._path.getFirstSegment();
  10029. handleIn = next && next._handleIn;
  10030. }
  10031. if (finished) {
  10032. if (closed) {
  10033. path.getFirstSegment().setHandleIn(handleIn);
  10034. path.setClosed(closed);
  10035. }
  10036. if (path.getArea() !== 0) {
  10037. paths.push(path);
  10038. }
  10039. }
  10040. }
  10041. return paths;
  10042. }
  10043. return {
  10044. _getWinding: function(point, dir, closed) {
  10045. return getWinding(point, this.getCurves(), dir, closed);
  10046. },
  10047. unite: function(path, options) {
  10048. return traceBoolean(this, path, 'unite', options);
  10049. },
  10050. intersect: function(path, options) {
  10051. return traceBoolean(this, path, 'intersect', options);
  10052. },
  10053. subtract: function(path, options) {
  10054. return traceBoolean(this, path, 'subtract', options);
  10055. },
  10056. exclude: function(path, options) {
  10057. return traceBoolean(this, path, 'exclude', options);
  10058. },
  10059. divide: function(path, options) {
  10060. return options && (options.trace == false || options.stroke)
  10061. ? splitBoolean(this, path, 'divide')
  10062. : createResult([
  10063. this.subtract(path, options),
  10064. this.intersect(path, options)
  10065. ], true, this, path, options);
  10066. },
  10067. resolveCrossings: function() {
  10068. var children = this._children,
  10069. paths = children || [this];
  10070. function hasOverlap(seg, path) {
  10071. var inter = seg && seg._intersection;
  10072. return inter && inter._overlap && inter._path === path;
  10073. }
  10074. var hasOverlaps = false,
  10075. hasCrossings = false,
  10076. intersections = this.getIntersections(null, function(inter) {
  10077. return inter.hasOverlap() && (hasOverlaps = true) ||
  10078. inter.isCrossing() && (hasCrossings = true);
  10079. }),
  10080. clearCurves = hasOverlaps && hasCrossings && [];
  10081. intersections = CurveLocation.expand(intersections);
  10082. if (hasOverlaps) {
  10083. var overlaps = divideLocations(intersections, function(inter) {
  10084. return inter.hasOverlap();
  10085. }, clearCurves);
  10086. for (var i = overlaps.length - 1; i >= 0; i--) {
  10087. var overlap = overlaps[i],
  10088. path = overlap._path,
  10089. seg = overlap._segment,
  10090. prev = seg.getPrevious(),
  10091. next = seg.getNext();
  10092. if (hasOverlap(prev, path) && hasOverlap(next, path)) {
  10093. seg.remove();
  10094. prev._handleOut._set(0, 0);
  10095. next._handleIn._set(0, 0);
  10096. if (prev !== seg && !prev.getCurve().hasLength()) {
  10097. next._handleIn.set(prev._handleIn);
  10098. prev.remove();
  10099. }
  10100. }
  10101. }
  10102. }
  10103. if (hasCrossings) {
  10104. divideLocations(intersections, hasOverlaps && function(inter) {
  10105. var curve1 = inter.getCurve(),
  10106. seg1 = inter.getSegment(),
  10107. other = inter._intersection,
  10108. curve2 = other._curve,
  10109. seg2 = other._segment;
  10110. if (curve1 && curve2 && curve1._path && curve2._path)
  10111. return true;
  10112. if (seg1)
  10113. seg1._intersection = null;
  10114. if (seg2)
  10115. seg2._intersection = null;
  10116. }, clearCurves);
  10117. if (clearCurves)
  10118. clearCurveHandles(clearCurves);
  10119. paths = tracePaths(Base.each(paths, function(path) {
  10120. Base.push(this, path._segments);
  10121. }, []));
  10122. }
  10123. var length = paths.length,
  10124. item;
  10125. if (length > 1 && children) {
  10126. if (paths !== children)
  10127. this.setChildren(paths);
  10128. item = this;
  10129. } else if (length === 1 && !children) {
  10130. if (paths[0] !== this)
  10131. this.setSegments(paths[0].removeSegments());
  10132. item = this;
  10133. }
  10134. if (!item) {
  10135. item = new CompoundPath(Item.NO_INSERT);
  10136. item.addChildren(paths);
  10137. item = item.reduce();
  10138. item.copyAttributes(this);
  10139. this.replaceWith(item);
  10140. }
  10141. return item;
  10142. },
  10143. reorient: function(nonZero, clockwise) {
  10144. var children = this._children;
  10145. if (children && children.length) {
  10146. this.setChildren(reorientPaths(this.removeChildren(),
  10147. function(w) {
  10148. return !!(nonZero ? w : w & 1);
  10149. },
  10150. clockwise));
  10151. } else if (clockwise !== undefined) {
  10152. this.setClockwise(clockwise);
  10153. }
  10154. return this;
  10155. },
  10156. getInteriorPoint: function() {
  10157. var bounds = this.getBounds(),
  10158. point = bounds.getCenter(true);
  10159. if (!this.contains(point)) {
  10160. var curves = this.getCurves(),
  10161. y = point.y,
  10162. intercepts = [],
  10163. roots = [];
  10164. for (var i = 0, l = curves.length; i < l; i++) {
  10165. var v = curves[i].getValues(),
  10166. o0 = v[1],
  10167. o1 = v[3],
  10168. o2 = v[5],
  10169. o3 = v[7];
  10170. if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) {
  10171. var monoCurves = Curve.getMonoCurves(v);
  10172. for (var j = 0, m = monoCurves.length; j < m; j++) {
  10173. var mv = monoCurves[j],
  10174. mo0 = mv[1],
  10175. mo3 = mv[7];
  10176. if ((mo0 !== mo3) &&
  10177. (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)){
  10178. var x = y === mo0 ? mv[0]
  10179. : y === mo3 ? mv[6]
  10180. : Curve.solveCubic(mv, 1, y, roots, 0, 1)
  10181. === 1
  10182. ? Curve.getPoint(mv, roots[0]).x
  10183. : (mv[0] + mv[6]) / 2;
  10184. intercepts.push(x);
  10185. }
  10186. }
  10187. }
  10188. }
  10189. if (intercepts.length > 1) {
  10190. intercepts.sort(function(a, b) { return a - b; });
  10191. point.x = (intercepts[0] + intercepts[1]) / 2;
  10192. }
  10193. }
  10194. return point;
  10195. }
  10196. };
  10197. });
  10198. var PathFlattener = Base.extend({
  10199. _class: 'PathFlattener',
  10200. initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) {
  10201. var curves = [],
  10202. parts = [],
  10203. length = 0,
  10204. minSpan = 1 / (maxRecursion || 32),
  10205. segments = path._segments,
  10206. segment1 = segments[0],
  10207. segment2;
  10208. function addCurve(segment1, segment2) {
  10209. var curve = Curve.getValues(segment1, segment2, matrix);
  10210. curves.push(curve);
  10211. computeParts(curve, segment1._index, 0, 1);
  10212. }
  10213. function computeParts(curve, index, t1, t2) {
  10214. if ((t2 - t1) > minSpan
  10215. && !(ignoreStraight && Curve.isStraight(curve))
  10216. && !Curve.isFlatEnough(curve, flatness || 0.25)) {
  10217. var halves = Curve.subdivide(curve, 0.5),
  10218. tMid = (t1 + t2) / 2;
  10219. computeParts(halves[0], index, t1, tMid);
  10220. computeParts(halves[1], index, tMid, t2);
  10221. } else {
  10222. var dx = curve[6] - curve[0],
  10223. dy = curve[7] - curve[1],
  10224. dist = Math.sqrt(dx * dx + dy * dy);
  10225. if (dist > 0) {
  10226. length += dist;
  10227. parts.push({
  10228. offset: length,
  10229. curve: curve,
  10230. index: index,
  10231. time: t2,
  10232. });
  10233. }
  10234. }
  10235. }
  10236. for (var i = 1, l = segments.length; i < l; i++) {
  10237. segment2 = segments[i];
  10238. addCurve(segment1, segment2);
  10239. segment1 = segment2;
  10240. }
  10241. if (path._closed)
  10242. addCurve(segment2 || segment1, segments[0]);
  10243. this.curves = curves;
  10244. this.parts = parts;
  10245. this.length = length;
  10246. this.index = 0;
  10247. },
  10248. _get: function(offset) {
  10249. var parts = this.parts,
  10250. length = parts.length,
  10251. start,
  10252. i, j = this.index;
  10253. for (;;) {
  10254. i = j;
  10255. if (!j || parts[--j].offset < offset)
  10256. break;
  10257. }
  10258. for (; i < length; i++) {
  10259. var part = parts[i];
  10260. if (part.offset >= offset) {
  10261. this.index = i;
  10262. var prev = parts[i - 1],
  10263. prevTime = prev && prev.index === part.index ? prev.time : 0,
  10264. prevOffset = prev ? prev.offset : 0;
  10265. return {
  10266. index: part.index,
  10267. time: prevTime + (part.time - prevTime)
  10268. * (offset - prevOffset) / (part.offset - prevOffset)
  10269. };
  10270. }
  10271. }
  10272. return {
  10273. index: parts[length - 1].index,
  10274. time: 1
  10275. };
  10276. },
  10277. drawPart: function(ctx, from, to) {
  10278. var start = this._get(from),
  10279. end = this._get(to);
  10280. for (var i = start.index, l = end.index; i <= l; i++) {
  10281. var curve = Curve.getPart(this.curves[i],
  10282. i === start.index ? start.time : 0,
  10283. i === end.index ? end.time : 1);
  10284. if (i === start.index)
  10285. ctx.moveTo(curve[0], curve[1]);
  10286. ctx.bezierCurveTo.apply(ctx, curve.slice(2));
  10287. }
  10288. }
  10289. }, Base.each(Curve._evaluateMethods,
  10290. function(name) {
  10291. this[name + 'At'] = function(offset) {
  10292. var param = this._get(offset);
  10293. return Curve[name](this.curves[param.index], param.time);
  10294. };
  10295. }, {})
  10296. );
  10297. var PathFitter = Base.extend({
  10298. initialize: function(path) {
  10299. var points = this.points = [],
  10300. segments = path._segments,
  10301. closed = path._closed;
  10302. for (var i = 0, prev, l = segments.length; i < l; i++) {
  10303. var point = segments[i].point;
  10304. if (!prev || !prev.equals(point)) {
  10305. points.push(prev = point.clone());
  10306. }
  10307. }
  10308. if (closed) {
  10309. points.unshift(points[points.length - 1]);
  10310. points.push(points[1]);
  10311. }
  10312. this.closed = closed;
  10313. },
  10314. fit: function(error) {
  10315. var points = this.points,
  10316. length = points.length,
  10317. segments = null;
  10318. if (length > 0) {
  10319. segments = [new Segment(points[0])];
  10320. if (length > 1) {
  10321. this.fitCubic(segments, error, 0, length - 1,
  10322. points[1].subtract(points[0]),
  10323. points[length - 2].subtract(points[length - 1]));
  10324. if (this.closed) {
  10325. segments.shift();
  10326. segments.pop();
  10327. }
  10328. }
  10329. }
  10330. return segments;
  10331. },
  10332. fitCubic: function(segments, error, first, last, tan1, tan2) {
  10333. var points = this.points;
  10334. if (last - first === 1) {
  10335. var pt1 = points[first],
  10336. pt2 = points[last],
  10337. dist = pt1.getDistance(pt2) / 3;
  10338. this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)),
  10339. pt2.add(tan2.normalize(dist)), pt2]);
  10340. return;
  10341. }
  10342. var uPrime = this.chordLengthParameterize(first, last),
  10343. maxError = Math.max(error, error * error),
  10344. split,
  10345. parametersInOrder = true;
  10346. for (var i = 0; i <= 4; i++) {
  10347. var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
  10348. var max = this.findMaxError(first, last, curve, uPrime);
  10349. if (max.error < error && parametersInOrder) {
  10350. this.addCurve(segments, curve);
  10351. return;
  10352. }
  10353. split = max.index;
  10354. if (max.error >= maxError)
  10355. break;
  10356. parametersInOrder = this.reparameterize(first, last, uPrime, curve);
  10357. maxError = max.error;
  10358. }
  10359. var tanCenter = points[split - 1].subtract(points[split + 1]);
  10360. this.fitCubic(segments, error, first, split, tan1, tanCenter);
  10361. this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2);
  10362. },
  10363. addCurve: function(segments, curve) {
  10364. var prev = segments[segments.length - 1];
  10365. prev.setHandleOut(curve[1].subtract(curve[0]));
  10366. segments.push(new Segment(curve[3], curve[2].subtract(curve[3])));
  10367. },
  10368. generateBezier: function(first, last, uPrime, tan1, tan2) {
  10369. var epsilon = 1e-12,
  10370. abs = Math.abs,
  10371. points = this.points,
  10372. pt1 = points[first],
  10373. pt2 = points[last],
  10374. C = [[0, 0], [0, 0]],
  10375. X = [0, 0];
  10376. for (var i = 0, l = last - first + 1; i < l; i++) {
  10377. var u = uPrime[i],
  10378. t = 1 - u,
  10379. b = 3 * u * t,
  10380. b0 = t * t * t,
  10381. b1 = b * t,
  10382. b2 = b * u,
  10383. b3 = u * u * u,
  10384. a1 = tan1.normalize(b1),
  10385. a2 = tan2.normalize(b2),
  10386. tmp = points[first + i]
  10387. .subtract(pt1.multiply(b0 + b1))
  10388. .subtract(pt2.multiply(b2 + b3));
  10389. C[0][0] += a1.dot(a1);
  10390. C[0][1] += a1.dot(a2);
  10391. C[1][0] = C[0][1];
  10392. C[1][1] += a2.dot(a2);
  10393. X[0] += a1.dot(tmp);
  10394. X[1] += a2.dot(tmp);
  10395. }
  10396. var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
  10397. alpha1,
  10398. alpha2;
  10399. if (abs(detC0C1) > epsilon) {
  10400. var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
  10401. detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
  10402. alpha1 = detXC1 / detC0C1;
  10403. alpha2 = detC0X / detC0C1;
  10404. } else {
  10405. var c0 = C[0][0] + C[0][1],
  10406. c1 = C[1][0] + C[1][1];
  10407. alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0
  10408. : abs(c1) > epsilon ? X[1] / c1
  10409. : 0;
  10410. }
  10411. var segLength = pt2.getDistance(pt1),
  10412. eps = epsilon * segLength,
  10413. handle1,
  10414. handle2;
  10415. if (alpha1 < eps || alpha2 < eps) {
  10416. alpha1 = alpha2 = segLength / 3;
  10417. } else {
  10418. var line = pt2.subtract(pt1);
  10419. handle1 = tan1.normalize(alpha1);
  10420. handle2 = tan2.normalize(alpha2);
  10421. if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) {
  10422. alpha1 = alpha2 = segLength / 3;
  10423. handle1 = handle2 = null;
  10424. }
  10425. }
  10426. return [pt1,
  10427. pt1.add(handle1 || tan1.normalize(alpha1)),
  10428. pt2.add(handle2 || tan2.normalize(alpha2)),
  10429. pt2];
  10430. },
  10431. reparameterize: function(first, last, u, curve) {
  10432. for (var i = first; i <= last; i++) {
  10433. u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
  10434. }
  10435. for (var i = 1, l = u.length; i < l; i++) {
  10436. if (u[i] <= u[i - 1])
  10437. return false;
  10438. }
  10439. return true;
  10440. },
  10441. findRoot: function(curve, point, u) {
  10442. var curve1 = [],
  10443. curve2 = [];
  10444. for (var i = 0; i <= 2; i++) {
  10445. curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
  10446. }
  10447. for (var i = 0; i <= 1; i++) {
  10448. curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
  10449. }
  10450. var pt = this.evaluate(3, curve, u),
  10451. pt1 = this.evaluate(2, curve1, u),
  10452. pt2 = this.evaluate(1, curve2, u),
  10453. diff = pt.subtract(point),
  10454. df = pt1.dot(pt1) + diff.dot(pt2);
  10455. return Numerical.isMachineZero(df) ? u : u - diff.dot(pt1) / df;
  10456. },
  10457. evaluate: function(degree, curve, t) {
  10458. var tmp = curve.slice();
  10459. for (var i = 1; i <= degree; i++) {
  10460. for (var j = 0; j <= degree - i; j++) {
  10461. tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
  10462. }
  10463. }
  10464. return tmp[0];
  10465. },
  10466. chordLengthParameterize: function(first, last) {
  10467. var u = [0];
  10468. for (var i = first + 1; i <= last; i++) {
  10469. u[i - first] = u[i - first - 1]
  10470. + this.points[i].getDistance(this.points[i - 1]);
  10471. }
  10472. for (var i = 1, m = last - first; i <= m; i++) {
  10473. u[i] /= u[m];
  10474. }
  10475. return u;
  10476. },
  10477. findMaxError: function(first, last, curve, u) {
  10478. var index = Math.floor((last - first + 1) / 2),
  10479. maxDist = 0;
  10480. for (var i = first + 1; i < last; i++) {
  10481. var P = this.evaluate(3, curve, u[i - first]);
  10482. var v = P.subtract(this.points[i]);
  10483. var dist = v.x * v.x + v.y * v.y;
  10484. if (dist >= maxDist) {
  10485. maxDist = dist;
  10486. index = i;
  10487. }
  10488. }
  10489. return {
  10490. error: maxDist,
  10491. index: index
  10492. };
  10493. }
  10494. });
  10495. var TextItem = Item.extend({
  10496. _class: 'TextItem',
  10497. _applyMatrix: false,
  10498. _canApplyMatrix: false,
  10499. _serializeFields: {
  10500. content: null
  10501. },
  10502. _boundsOptions: { stroke: false, handle: false },
  10503. initialize: function TextItem(arg) {
  10504. this._content = '';
  10505. this._lines = [];
  10506. var hasProps = arg && Base.isPlainObject(arg)
  10507. && arg.x === undefined && arg.y === undefined;
  10508. this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
  10509. },
  10510. _equals: function(item) {
  10511. return this._content === item._content;
  10512. },
  10513. copyContent: function(source) {
  10514. this.setContent(source._content);
  10515. },
  10516. getContent: function() {
  10517. return this._content;
  10518. },
  10519. setContent: function(content) {
  10520. this._content = '' + content;
  10521. this._lines = this._content.split(/\r\n|\n|\r/mg);
  10522. this._changed(521);
  10523. },
  10524. isEmpty: function() {
  10525. return !this._content;
  10526. },
  10527. getCharacterStyle: '#getStyle',
  10528. setCharacterStyle: '#setStyle',
  10529. getParagraphStyle: '#getStyle',
  10530. setParagraphStyle: '#setStyle'
  10531. });
  10532. var PointText = TextItem.extend({
  10533. _class: 'PointText',
  10534. initialize: function PointText() {
  10535. TextItem.apply(this, arguments);
  10536. },
  10537. getPoint: function() {
  10538. var point = this._matrix.getTranslation();
  10539. return new LinkedPoint(point.x, point.y, this, 'setPoint');
  10540. },
  10541. setPoint: function() {
  10542. var point = Point.read(arguments);
  10543. this.translate(point.subtract(this._matrix.getTranslation()));
  10544. },
  10545. _draw: function(ctx, param, viewMatrix) {
  10546. if (!this._content)
  10547. return;
  10548. this._setStyles(ctx, param, viewMatrix);
  10549. var lines = this._lines,
  10550. style = this._style,
  10551. hasFill = style.hasFill(),
  10552. hasStroke = style.hasStroke(),
  10553. leading = style.getLeading(),
  10554. shadowColor = ctx.shadowColor;
  10555. ctx.font = style.getFontStyle();
  10556. ctx.textAlign = style.getJustification();
  10557. for (var i = 0, l = lines.length; i < l; i++) {
  10558. ctx.shadowColor = shadowColor;
  10559. var line = lines[i];
  10560. if (hasFill) {
  10561. ctx.fillText(line, 0, 0);
  10562. ctx.shadowColor = 'rgba(0,0,0,0)';
  10563. }
  10564. if (hasStroke)
  10565. ctx.strokeText(line, 0, 0);
  10566. ctx.translate(0, leading);
  10567. }
  10568. },
  10569. _getBounds: function(matrix, options) {
  10570. var style = this._style,
  10571. lines = this._lines,
  10572. numLines = lines.length,
  10573. justification = style.getJustification(),
  10574. leading = style.getLeading(),
  10575. width = this.getView().getTextWidth(style.getFontStyle(), lines),
  10576. x = 0;
  10577. if (justification !== 'left')
  10578. x -= width / (justification === 'center' ? 2: 1);
  10579. var rect = new Rectangle(x,
  10580. numLines ? - 0.75 * leading : 0,
  10581. width, numLines * leading);
  10582. return matrix ? matrix._transformBounds(rect, rect) : rect;
  10583. }
  10584. });
  10585. var Color = Base.extend(new function() {
  10586. var types = {
  10587. gray: ['gray'],
  10588. rgb: ['red', 'green', 'blue'],
  10589. hsb: ['hue', 'saturation', 'brightness'],
  10590. hsl: ['hue', 'saturation', 'lightness'],
  10591. gradient: ['gradient', 'origin', 'destination', 'highlight']
  10592. };
  10593. var componentParsers = {},
  10594. namedColors = {
  10595. transparent: [0, 0, 0, 0]
  10596. },
  10597. colorCtx;
  10598. function fromCSS(string) {
  10599. var match = string.match(
  10600. /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i
  10601. ) || string.match(
  10602. /^#([\da-f])([\da-f])([\da-f])([\da-f])?$/i
  10603. ),
  10604. type = 'rgb',
  10605. components;
  10606. if (match) {
  10607. var amount = match[4] ? 4 : 3;
  10608. components = new Array(amount);
  10609. for (var i = 0; i < amount; i++) {
  10610. var value = match[i + 1];
  10611. components[i] = parseInt(value.length == 1
  10612. ? value + value : value, 16) / 255;
  10613. }
  10614. } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) {
  10615. type = match[1];
  10616. components = match[2].trim().split(/[,\s]+/g);
  10617. var isHSL = type === 'hsl';
  10618. for (var i = 0, l = Math.min(components.length, 4); i < l; i++) {
  10619. var component = components[i];
  10620. var value = parseFloat(component);
  10621. if (isHSL) {
  10622. if (i === 0) {
  10623. var unit = component.match(/([a-z]*)$/)[1];
  10624. value *= ({
  10625. turn: 360,
  10626. rad: 180 / Math.PI,
  10627. grad: 0.9
  10628. }[unit] || 1);
  10629. } else if (i < 3) {
  10630. value /= 100;
  10631. }
  10632. } else if (i < 3) {
  10633. value /= /%$/.test(component) ? 100 : 255;
  10634. }
  10635. components[i] = value;
  10636. }
  10637. } else {
  10638. var color = namedColors[string];
  10639. if (!color) {
  10640. if (window) {
  10641. if (!colorCtx) {
  10642. colorCtx = CanvasProvider.getContext(1, 1);
  10643. colorCtx.globalCompositeOperation = 'copy';
  10644. }
  10645. colorCtx.fillStyle = 'rgba(0,0,0,0)';
  10646. colorCtx.fillStyle = string;
  10647. colorCtx.fillRect(0, 0, 1, 1);
  10648. var data = colorCtx.getImageData(0, 0, 1, 1).data;
  10649. color = namedColors[string] = [
  10650. data[0] / 255,
  10651. data[1] / 255,
  10652. data[2] / 255
  10653. ];
  10654. } else {
  10655. color = [0, 0, 0];
  10656. }
  10657. }
  10658. components = color.slice();
  10659. }
  10660. return [type, components];
  10661. }
  10662. var hsbIndices = [
  10663. [0, 3, 1],
  10664. [2, 0, 1],
  10665. [1, 0, 3],
  10666. [1, 2, 0],
  10667. [3, 1, 0],
  10668. [0, 1, 2]
  10669. ];
  10670. var converters = {
  10671. 'rgb-hsb': function(r, g, b) {
  10672. var max = Math.max(r, g, b),
  10673. min = Math.min(r, g, b),
  10674. delta = max - min,
  10675. h = delta === 0 ? 0
  10676. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10677. : max == g ? (b - r) / delta + 2
  10678. : (r - g) / delta + 4) * 60;
  10679. return [h, max === 0 ? 0 : delta / max, max];
  10680. },
  10681. 'hsb-rgb': function(h, s, b) {
  10682. h = (((h / 60) % 6) + 6) % 6;
  10683. var i = Math.floor(h),
  10684. f = h - i,
  10685. i = hsbIndices[i],
  10686. v = [
  10687. b,
  10688. b * (1 - s),
  10689. b * (1 - s * f),
  10690. b * (1 - s * (1 - f))
  10691. ];
  10692. return [v[i[0]], v[i[1]], v[i[2]]];
  10693. },
  10694. 'rgb-hsl': function(r, g, b) {
  10695. var max = Math.max(r, g, b),
  10696. min = Math.min(r, g, b),
  10697. delta = max - min,
  10698. achromatic = delta === 0,
  10699. h = achromatic ? 0
  10700. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10701. : max == g ? (b - r) / delta + 2
  10702. : (r - g) / delta + 4) * 60,
  10703. l = (max + min) / 2,
  10704. s = achromatic ? 0 : l < 0.5
  10705. ? delta / (max + min)
  10706. : delta / (2 - max - min);
  10707. return [h, s, l];
  10708. },
  10709. 'hsl-rgb': function(h, s, l) {
  10710. h = (((h / 360) % 1) + 1) % 1;
  10711. if (s === 0)
  10712. return [l, l, l];
  10713. var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
  10714. t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
  10715. t1 = 2 * l - t2,
  10716. c = [];
  10717. for (var i = 0; i < 3; i++) {
  10718. var t3 = t3s[i];
  10719. if (t3 < 0) t3 += 1;
  10720. if (t3 > 1) t3 -= 1;
  10721. c[i] = 6 * t3 < 1
  10722. ? t1 + (t2 - t1) * 6 * t3
  10723. : 2 * t3 < 1
  10724. ? t2
  10725. : 3 * t3 < 2
  10726. ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
  10727. : t1;
  10728. }
  10729. return c;
  10730. },
  10731. 'rgb-gray': function(r, g, b) {
  10732. return [r * 0.2989 + g * 0.587 + b * 0.114];
  10733. },
  10734. 'gray-rgb': function(g) {
  10735. return [g, g, g];
  10736. },
  10737. 'gray-hsb': function(g) {
  10738. return [0, 0, g];
  10739. },
  10740. 'gray-hsl': function(g) {
  10741. return [0, 0, g];
  10742. },
  10743. 'gradient-rgb': function() {
  10744. return [];
  10745. },
  10746. 'rgb-gradient': function() {
  10747. return [];
  10748. }
  10749. };
  10750. return Base.each(types, function(properties, type) {
  10751. componentParsers[type] = [];
  10752. Base.each(properties, function(name, index) {
  10753. var part = Base.capitalize(name),
  10754. hasOverlap = /^(hue|saturation)$/.test(name),
  10755. parser = componentParsers[type][index] = type === 'gradient'
  10756. ? name === 'gradient'
  10757. ? function(value) {
  10758. var current = this._components[0];
  10759. value = Gradient.read(
  10760. Array.isArray(value)
  10761. ? value
  10762. : arguments, 0, { readNull: true }
  10763. );
  10764. if (current !== value) {
  10765. if (current)
  10766. current._removeOwner(this);
  10767. if (value)
  10768. value._addOwner(this);
  10769. }
  10770. return value;
  10771. }
  10772. : function() {
  10773. return Point.read(arguments, 0, {
  10774. readNull: name === 'highlight',
  10775. clone: true
  10776. });
  10777. }
  10778. : function(value) {
  10779. return value == null || isNaN(value) ? 0 : +value;
  10780. };
  10781. this['get' + part] = function() {
  10782. return this._type === type
  10783. || hasOverlap && /^hs[bl]$/.test(this._type)
  10784. ? this._components[index]
  10785. : this._convert(type)[index];
  10786. };
  10787. this['set' + part] = function(value) {
  10788. if (this._type !== type
  10789. && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
  10790. this._components = this._convert(type);
  10791. this._properties = types[type];
  10792. this._type = type;
  10793. }
  10794. this._components[index] = parser.call(this, value);
  10795. this._changed();
  10796. };
  10797. }, this);
  10798. }, {
  10799. _class: 'Color',
  10800. _readIndex: true,
  10801. initialize: function Color(arg) {
  10802. var args = arguments,
  10803. reading = this.__read,
  10804. read = 0,
  10805. type,
  10806. components,
  10807. alpha,
  10808. values;
  10809. if (Array.isArray(arg)) {
  10810. args = arg;
  10811. arg = args[0];
  10812. }
  10813. var argType = arg != null && typeof arg;
  10814. if (argType === 'string' && arg in types) {
  10815. type = arg;
  10816. arg = args[1];
  10817. if (Array.isArray(arg)) {
  10818. components = arg;
  10819. alpha = args[2];
  10820. } else {
  10821. if (reading)
  10822. read = 1;
  10823. args = Base.slice(args, 1);
  10824. argType = typeof arg;
  10825. }
  10826. }
  10827. if (!components) {
  10828. values = argType === 'number'
  10829. ? args
  10830. : argType === 'object' && arg.length != null
  10831. ? arg
  10832. : null;
  10833. if (values) {
  10834. if (!type)
  10835. type = values.length >= 3
  10836. ? 'rgb'
  10837. : 'gray';
  10838. var length = types[type].length;
  10839. alpha = values[length];
  10840. if (reading) {
  10841. read += values === arguments
  10842. ? length + (alpha != null ? 1 : 0)
  10843. : 1;
  10844. }
  10845. if (values.length > length)
  10846. values = Base.slice(values, 0, length);
  10847. } else if (argType === 'string') {
  10848. var converted = fromCSS(arg);
  10849. type = converted[0];
  10850. components = converted[1];
  10851. if (components.length === 4) {
  10852. alpha = components[3];
  10853. components.length--;
  10854. }
  10855. } else if (argType === 'object') {
  10856. if (arg.constructor === Color) {
  10857. type = arg._type;
  10858. components = arg._components.slice();
  10859. alpha = arg._alpha;
  10860. if (type === 'gradient') {
  10861. for (var i = 1, l = components.length; i < l; i++) {
  10862. var point = components[i];
  10863. if (point)
  10864. components[i] = point.clone();
  10865. }
  10866. }
  10867. } else if (arg.constructor === Gradient) {
  10868. type = 'gradient';
  10869. values = args;
  10870. } else {
  10871. type = 'hue' in arg
  10872. ? 'lightness' in arg
  10873. ? 'hsl'
  10874. : 'hsb'
  10875. : 'gradient' in arg || 'stops' in arg
  10876. || 'radial' in arg
  10877. ? 'gradient'
  10878. : 'gray' in arg
  10879. ? 'gray'
  10880. : 'rgb';
  10881. var properties = types[type],
  10882. parsers = componentParsers[type];
  10883. this._components = components = [];
  10884. for (var i = 0, l = properties.length; i < l; i++) {
  10885. var value = arg[properties[i]];
  10886. if (value == null && !i && type === 'gradient'
  10887. && 'stops' in arg) {
  10888. value = {
  10889. stops: arg.stops,
  10890. radial: arg.radial
  10891. };
  10892. }
  10893. value = parsers[i].call(this, value);
  10894. if (value != null)
  10895. components[i] = value;
  10896. }
  10897. alpha = arg.alpha;
  10898. }
  10899. }
  10900. if (reading && type)
  10901. read = 1;
  10902. }
  10903. this._type = type || 'rgb';
  10904. if (!components) {
  10905. this._components = components = [];
  10906. var parsers = componentParsers[this._type];
  10907. for (var i = 0, l = parsers.length; i < l; i++) {
  10908. var value = parsers[i].call(this, values && values[i]);
  10909. if (value != null)
  10910. components[i] = value;
  10911. }
  10912. }
  10913. this._components = components;
  10914. this._properties = types[this._type];
  10915. this._alpha = alpha;
  10916. if (reading)
  10917. this.__read = read;
  10918. return this;
  10919. },
  10920. set: '#initialize',
  10921. _serialize: function(options, dictionary) {
  10922. var components = this.getComponents();
  10923. return Base.serialize(
  10924. /^(gray|rgb)$/.test(this._type)
  10925. ? components
  10926. : [this._type].concat(components),
  10927. options, true, dictionary);
  10928. },
  10929. _changed: function() {
  10930. this._canvasStyle = null;
  10931. if (this._owner) {
  10932. if (this._setter) {
  10933. this._owner[this._setter](this);
  10934. } else {
  10935. this._owner._changed(129);
  10936. }
  10937. }
  10938. },
  10939. _convert: function(type) {
  10940. var converter;
  10941. return this._type === type
  10942. ? this._components.slice()
  10943. : (converter = converters[this._type + '-' + type])
  10944. ? converter.apply(this, this._components)
  10945. : converters['rgb-' + type].apply(this,
  10946. converters[this._type + '-rgb'].apply(this,
  10947. this._components));
  10948. },
  10949. convert: function(type) {
  10950. return new Color(type, this._convert(type), this._alpha);
  10951. },
  10952. getType: function() {
  10953. return this._type;
  10954. },
  10955. setType: function(type) {
  10956. this._components = this._convert(type);
  10957. this._properties = types[type];
  10958. this._type = type;
  10959. },
  10960. getComponents: function() {
  10961. var components = this._components.slice();
  10962. if (this._alpha != null)
  10963. components.push(this._alpha);
  10964. return components;
  10965. },
  10966. getAlpha: function() {
  10967. return this._alpha != null ? this._alpha : 1;
  10968. },
  10969. setAlpha: function(alpha) {
  10970. this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
  10971. this._changed();
  10972. },
  10973. hasAlpha: function() {
  10974. return this._alpha != null;
  10975. },
  10976. equals: function(color) {
  10977. var col = Base.isPlainValue(color, true)
  10978. ? Color.read(arguments)
  10979. : color;
  10980. return col === this || col && this._class === col._class
  10981. && this._type === col._type
  10982. && this.getAlpha() === col.getAlpha()
  10983. && Base.equals(this._components, col._components)
  10984. || false;
  10985. },
  10986. toString: function() {
  10987. var properties = this._properties,
  10988. parts = [],
  10989. isGradient = this._type === 'gradient',
  10990. f = Formatter.instance;
  10991. for (var i = 0, l = properties.length; i < l; i++) {
  10992. var value = this._components[i];
  10993. if (value != null)
  10994. parts.push(properties[i] + ': '
  10995. + (isGradient ? value : f.number(value)));
  10996. }
  10997. if (this._alpha != null)
  10998. parts.push('alpha: ' + f.number(this._alpha));
  10999. return '{ ' + parts.join(', ') + ' }';
  11000. },
  11001. toCSS: function(hex) {
  11002. var components = this._convert('rgb'),
  11003. alpha = hex || this._alpha == null ? 1 : this._alpha;
  11004. function convert(val) {
  11005. return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);
  11006. }
  11007. components = [
  11008. convert(components[0]),
  11009. convert(components[1]),
  11010. convert(components[2])
  11011. ];
  11012. if (alpha < 1)
  11013. components.push(alpha < 0 ? 0 : alpha);
  11014. return hex
  11015. ? '#' + ((1 << 24) + (components[0] << 16)
  11016. + (components[1] << 8)
  11017. + components[2]).toString(16).slice(1)
  11018. : (components.length == 4 ? 'rgba(' : 'rgb(')
  11019. + components.join(',') + ')';
  11020. },
  11021. toCanvasStyle: function(ctx, matrix) {
  11022. if (this._canvasStyle)
  11023. return this._canvasStyle;
  11024. if (this._type !== 'gradient')
  11025. return this._canvasStyle = this.toCSS();
  11026. var components = this._components,
  11027. gradient = components[0],
  11028. stops = gradient._stops,
  11029. origin = components[1],
  11030. destination = components[2],
  11031. highlight = components[3],
  11032. inverse = matrix && matrix.inverted(),
  11033. canvasGradient;
  11034. if (inverse) {
  11035. origin = inverse._transformPoint(origin);
  11036. destination = inverse._transformPoint(destination);
  11037. if (highlight)
  11038. highlight = inverse._transformPoint(highlight);
  11039. }
  11040. if (gradient._radial) {
  11041. var radius = destination.getDistance(origin);
  11042. if (highlight) {
  11043. var vector = highlight.subtract(origin);
  11044. if (vector.getLength() > radius)
  11045. highlight = origin.add(vector.normalize(radius - 0.1));
  11046. }
  11047. var start = highlight || origin;
  11048. canvasGradient = ctx.createRadialGradient(start.x, start.y,
  11049. 0, origin.x, origin.y, radius);
  11050. } else {
  11051. canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
  11052. destination.x, destination.y);
  11053. }
  11054. for (var i = 0, l = stops.length; i < l; i++) {
  11055. var stop = stops[i],
  11056. offset = stop._offset;
  11057. canvasGradient.addColorStop(
  11058. offset == null ? i / (l - 1) : offset,
  11059. stop._color.toCanvasStyle());
  11060. }
  11061. return this._canvasStyle = canvasGradient;
  11062. },
  11063. transform: function(matrix) {
  11064. if (this._type === 'gradient') {
  11065. var components = this._components;
  11066. for (var i = 1, l = components.length; i < l; i++) {
  11067. var point = components[i];
  11068. matrix._transformPoint(point, point, true);
  11069. }
  11070. this._changed();
  11071. }
  11072. },
  11073. statics: {
  11074. _types: types,
  11075. random: function() {
  11076. var random = Math.random;
  11077. return new Color(random(), random(), random());
  11078. },
  11079. _setOwner: function(color, owner, setter) {
  11080. if (color) {
  11081. if (color._owner && owner && color._owner !== owner) {
  11082. color = color.clone();
  11083. }
  11084. if (!color._owner ^ !owner) {
  11085. color._owner = owner || null;
  11086. color._setter = setter || null;
  11087. }
  11088. }
  11089. return color;
  11090. }
  11091. }
  11092. });
  11093. },
  11094. new function() {
  11095. var operators = {
  11096. add: function(a, b) {
  11097. return a + b;
  11098. },
  11099. subtract: function(a, b) {
  11100. return a - b;
  11101. },
  11102. multiply: function(a, b) {
  11103. return a * b;
  11104. },
  11105. divide: function(a, b) {
  11106. return a / b;
  11107. }
  11108. };
  11109. return Base.each(operators, function(operator, name) {
  11110. this[name] = function(color) {
  11111. color = Color.read(arguments);
  11112. var type = this._type,
  11113. components1 = this._components,
  11114. components2 = color._convert(type);
  11115. for (var i = 0, l = components1.length; i < l; i++)
  11116. components2[i] = operator(components1[i], components2[i]);
  11117. return new Color(type, components2,
  11118. this._alpha != null
  11119. ? operator(this._alpha, color.getAlpha())
  11120. : null);
  11121. };
  11122. }, {
  11123. });
  11124. });
  11125. var Gradient = Base.extend({
  11126. _class: 'Gradient',
  11127. initialize: function Gradient(stops, radial) {
  11128. this._id = UID.get();
  11129. if (stops && Base.isPlainObject(stops)) {
  11130. this.set(stops);
  11131. stops = radial = null;
  11132. }
  11133. if (this._stops == null) {
  11134. this.setStops(stops || ['white', 'black']);
  11135. }
  11136. if (this._radial == null) {
  11137. this.setRadial(typeof radial === 'string' && radial === 'radial'
  11138. || radial || false);
  11139. }
  11140. },
  11141. _serialize: function(options, dictionary) {
  11142. return dictionary.add(this, function() {
  11143. return Base.serialize([this._stops, this._radial],
  11144. options, true, dictionary);
  11145. });
  11146. },
  11147. _changed: function() {
  11148. for (var i = 0, l = this._owners && this._owners.length; i < l; i++) {
  11149. this._owners[i]._changed();
  11150. }
  11151. },
  11152. _addOwner: function(color) {
  11153. if (!this._owners)
  11154. this._owners = [];
  11155. this._owners.push(color);
  11156. },
  11157. _removeOwner: function(color) {
  11158. var index = this._owners ? this._owners.indexOf(color) : -1;
  11159. if (index != -1) {
  11160. this._owners.splice(index, 1);
  11161. if (!this._owners.length)
  11162. this._owners = undefined;
  11163. }
  11164. },
  11165. clone: function() {
  11166. var stops = [];
  11167. for (var i = 0, l = this._stops.length; i < l; i++) {
  11168. stops[i] = this._stops[i].clone();
  11169. }
  11170. return new Gradient(stops, this._radial);
  11171. },
  11172. getStops: function() {
  11173. return this._stops;
  11174. },
  11175. setStops: function(stops) {
  11176. if (stops.length < 2) {
  11177. throw new Error(
  11178. 'Gradient stop list needs to contain at least two stops.');
  11179. }
  11180. var _stops = this._stops;
  11181. if (_stops) {
  11182. for (var i = 0, l = _stops.length; i < l; i++)
  11183. _stops[i]._owner = undefined;
  11184. }
  11185. _stops = this._stops = GradientStop.readList(stops, 0, { clone: true });
  11186. for (var i = 0, l = _stops.length; i < l; i++)
  11187. _stops[i]._owner = this;
  11188. this._changed();
  11189. },
  11190. getRadial: function() {
  11191. return this._radial;
  11192. },
  11193. setRadial: function(radial) {
  11194. this._radial = radial;
  11195. this._changed();
  11196. },
  11197. equals: function(gradient) {
  11198. if (gradient === this)
  11199. return true;
  11200. if (gradient && this._class === gradient._class) {
  11201. var stops1 = this._stops,
  11202. stops2 = gradient._stops,
  11203. length = stops1.length;
  11204. if (length === stops2.length) {
  11205. for (var i = 0; i < length; i++) {
  11206. if (!stops1[i].equals(stops2[i]))
  11207. return false;
  11208. }
  11209. return true;
  11210. }
  11211. }
  11212. return false;
  11213. }
  11214. });
  11215. var GradientStop = Base.extend({
  11216. _class: 'GradientStop',
  11217. initialize: function GradientStop(arg0, arg1) {
  11218. var color = arg0,
  11219. offset = arg1;
  11220. if (typeof arg0 === 'object' && arg1 === undefined) {
  11221. if (Array.isArray(arg0) && typeof arg0[0] !== 'number') {
  11222. color = arg0[0];
  11223. offset = arg0[1];
  11224. } else if ('color' in arg0 || 'offset' in arg0
  11225. || 'rampPoint' in arg0) {
  11226. color = arg0.color;
  11227. offset = arg0.offset || arg0.rampPoint || 0;
  11228. }
  11229. }
  11230. this.setColor(color);
  11231. this.setOffset(offset);
  11232. },
  11233. clone: function() {
  11234. return new GradientStop(this._color.clone(), this._offset);
  11235. },
  11236. _serialize: function(options, dictionary) {
  11237. var color = this._color,
  11238. offset = this._offset;
  11239. return Base.serialize(offset == null ? [color] : [color, offset],
  11240. options, true, dictionary);
  11241. },
  11242. _changed: function() {
  11243. if (this._owner)
  11244. this._owner._changed(129);
  11245. },
  11246. getOffset: function() {
  11247. return this._offset;
  11248. },
  11249. setOffset: function(offset) {
  11250. this._offset = offset;
  11251. this._changed();
  11252. },
  11253. getRampPoint: '#getOffset',
  11254. setRampPoint: '#setOffset',
  11255. getColor: function() {
  11256. return this._color;
  11257. },
  11258. setColor: function() {
  11259. Color._setOwner(this._color, null);
  11260. this._color = Color._setOwner(Color.read(arguments, 0), this,
  11261. 'setColor');
  11262. this._changed();
  11263. },
  11264. equals: function(stop) {
  11265. return stop === this || stop && this._class === stop._class
  11266. && this._color.equals(stop._color)
  11267. && this._offset == stop._offset
  11268. || false;
  11269. }
  11270. });
  11271. var Style = Base.extend(new function() {
  11272. var itemDefaults = {
  11273. fillColor: null,
  11274. fillRule: 'nonzero',
  11275. strokeColor: null,
  11276. strokeWidth: 1,
  11277. strokeCap: 'butt',
  11278. strokeJoin: 'miter',
  11279. strokeScaling: true,
  11280. miterLimit: 10,
  11281. dashOffset: 0,
  11282. dashArray: [],
  11283. shadowColor: null,
  11284. shadowBlur: 0,
  11285. shadowOffset: new Point(),
  11286. selectedColor: null
  11287. },
  11288. groupDefaults = Base.set({}, itemDefaults, {
  11289. fontFamily: 'sans-serif',
  11290. fontWeight: 'normal',
  11291. fontSize: 12,
  11292. leading: null,
  11293. justification: 'left'
  11294. }),
  11295. textDefaults = Base.set({}, groupDefaults, {
  11296. fillColor: new Color()
  11297. }),
  11298. flags = {
  11299. strokeWidth: 193,
  11300. strokeCap: 193,
  11301. strokeJoin: 193,
  11302. strokeScaling: 201,
  11303. miterLimit: 193,
  11304. fontFamily: 9,
  11305. fontWeight: 9,
  11306. fontSize: 9,
  11307. font: 9,
  11308. leading: 9,
  11309. justification: 9
  11310. },
  11311. item = {
  11312. beans: true
  11313. },
  11314. fields = {
  11315. _class: 'Style',
  11316. beans: true,
  11317. initialize: function Style(style, _owner, _project) {
  11318. this._values = {};
  11319. this._owner = _owner;
  11320. this._project = _owner && _owner._project || _project
  11321. || paper.project;
  11322. this._defaults = !_owner || _owner instanceof Group ? groupDefaults
  11323. : _owner instanceof TextItem ? textDefaults
  11324. : itemDefaults;
  11325. if (style)
  11326. this.set(style);
  11327. }
  11328. };
  11329. Base.each(groupDefaults, function(value, key) {
  11330. var isColor = /Color$/.test(key),
  11331. isPoint = key === 'shadowOffset',
  11332. part = Base.capitalize(key),
  11333. flag = flags[key],
  11334. set = 'set' + part,
  11335. get = 'get' + part;
  11336. fields[set] = function(value) {
  11337. var owner = this._owner,
  11338. children = owner && owner._children,
  11339. applyToChildren = children && children.length > 0
  11340. && !(owner instanceof CompoundPath);
  11341. if (applyToChildren) {
  11342. for (var i = 0, l = children.length; i < l; i++)
  11343. children[i]._style[set](value);
  11344. }
  11345. if ((key === 'selectedColor' || !applyToChildren)
  11346. && key in this._defaults) {
  11347. var old = this._values[key];
  11348. if (old !== value) {
  11349. if (isColor) {
  11350. if (old) {
  11351. Color._setOwner(old, null);
  11352. old._canvasStyle = null;
  11353. }
  11354. if (value && value.constructor === Color) {
  11355. value = Color._setOwner(value, owner,
  11356. applyToChildren && set);
  11357. }
  11358. }
  11359. this._values[key] = value;
  11360. if (owner)
  11361. owner._changed(flag || 129);
  11362. }
  11363. }
  11364. };
  11365. fields[get] = function(_dontMerge) {
  11366. var owner = this._owner,
  11367. children = owner && owner._children,
  11368. applyToChildren = children && children.length > 0
  11369. && !(owner instanceof CompoundPath),
  11370. value;
  11371. if (applyToChildren && !_dontMerge) {
  11372. for (var i = 0, l = children.length; i < l; i++) {
  11373. var childValue = children[i]._style[get]();
  11374. if (!i) {
  11375. value = childValue;
  11376. } else if (!Base.equals(value, childValue)) {
  11377. return undefined;
  11378. }
  11379. }
  11380. } else if (key in this._defaults) {
  11381. var value = this._values[key];
  11382. if (value === undefined) {
  11383. value = this._defaults[key];
  11384. if (value && value.clone) {
  11385. value = value.clone();
  11386. }
  11387. } else {
  11388. var ctor = isColor ? Color : isPoint ? Point : null;
  11389. if (ctor && !(value && value.constructor === ctor)) {
  11390. this._values[key] = value = ctor.read([value], 0,
  11391. { readNull: true, clone: true });
  11392. }
  11393. }
  11394. }
  11395. if (value && isColor) {
  11396. value = Color._setOwner(value, owner, applyToChildren && set);
  11397. }
  11398. return value;
  11399. };
  11400. item[get] = function(_dontMerge) {
  11401. return this._style[get](_dontMerge);
  11402. };
  11403. item[set] = function(value) {
  11404. this._style[set](value);
  11405. };
  11406. });
  11407. Base.each({
  11408. Font: 'FontFamily',
  11409. WindingRule: 'FillRule'
  11410. }, function(value, key) {
  11411. var get = 'get' + key,
  11412. set = 'set' + key;
  11413. fields[get] = item[get] = '#get' + value;
  11414. fields[set] = item[set] = '#set' + value;
  11415. });
  11416. Item.inject(item);
  11417. return fields;
  11418. }, {
  11419. set: function(style) {
  11420. var isStyle = style instanceof Style,
  11421. values = isStyle ? style._values : style;
  11422. if (values) {
  11423. for (var key in values) {
  11424. if (key in this._defaults) {
  11425. var value = values[key];
  11426. this[key] = value && isStyle && value.clone
  11427. ? value.clone() : value;
  11428. }
  11429. }
  11430. }
  11431. },
  11432. equals: function(style) {
  11433. function compare(style1, style2, secondary) {
  11434. var values1 = style1._values,
  11435. values2 = style2._values,
  11436. defaults2 = style2._defaults;
  11437. for (var key in values1) {
  11438. var value1 = values1[key],
  11439. value2 = values2[key];
  11440. if (!(secondary && key in values2) && !Base.equals(value1,
  11441. value2 === undefined ? defaults2[key] : value2))
  11442. return false;
  11443. }
  11444. return true;
  11445. }
  11446. return style === this || style && this._class === style._class
  11447. && compare(this, style)
  11448. && compare(style, this, true)
  11449. || false;
  11450. },
  11451. _dispose: function() {
  11452. var color;
  11453. color = this.getFillColor();
  11454. if (color) color._canvasStyle = null;
  11455. color = this.getStrokeColor();
  11456. if (color) color._canvasStyle = null;
  11457. color = this.getShadowColor();
  11458. if (color) color._canvasStyle = null;
  11459. },
  11460. hasFill: function() {
  11461. var color = this.getFillColor();
  11462. return !!color && color.alpha > 0;
  11463. },
  11464. hasStroke: function() {
  11465. var color = this.getStrokeColor();
  11466. return !!color && color.alpha > 0 && this.getStrokeWidth() > 0;
  11467. },
  11468. hasShadow: function() {
  11469. var color = this.getShadowColor();
  11470. return !!color && color.alpha > 0 && (this.getShadowBlur() > 0
  11471. || !this.getShadowOffset().isZero());
  11472. },
  11473. getView: function() {
  11474. return this._project._view;
  11475. },
  11476. getFontStyle: function() {
  11477. var fontSize = this.getFontSize();
  11478. return this.getFontWeight()
  11479. + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')
  11480. + this.getFontFamily();
  11481. },
  11482. getFont: '#getFontFamily',
  11483. setFont: '#setFontFamily',
  11484. getLeading: function getLeading() {
  11485. var leading = getLeading.base.call(this),
  11486. fontSize = this.getFontSize();
  11487. if (/pt|em|%|px/.test(fontSize))
  11488. fontSize = this.getView().getPixelSize(fontSize);
  11489. return leading != null ? leading : fontSize * 1.2;
  11490. }
  11491. });
  11492. var DomElement = new function() {
  11493. function handlePrefix(el, name, set, value) {
  11494. var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'],
  11495. suffix = name[0].toUpperCase() + name.substring(1);
  11496. for (var i = 0; i < 6; i++) {
  11497. var prefix = prefixes[i],
  11498. key = prefix ? prefix + suffix : name;
  11499. if (key in el) {
  11500. if (set) {
  11501. el[key] = value;
  11502. } else {
  11503. return el[key];
  11504. }
  11505. break;
  11506. }
  11507. }
  11508. }
  11509. return {
  11510. getStyles: function(el) {
  11511. var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
  11512. view = doc && doc.defaultView;
  11513. return view && view.getComputedStyle(el, '');
  11514. },
  11515. getBounds: function(el, viewport) {
  11516. var doc = el.ownerDocument,
  11517. body = doc.body,
  11518. html = doc.documentElement,
  11519. rect;
  11520. try {
  11521. rect = el.getBoundingClientRect();
  11522. } catch (e) {
  11523. rect = { left: 0, top: 0, width: 0, height: 0 };
  11524. }
  11525. var x = rect.left - (html.clientLeft || body.clientLeft || 0),
  11526. y = rect.top - (html.clientTop || body.clientTop || 0);
  11527. if (!viewport) {
  11528. var view = doc.defaultView;
  11529. x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
  11530. y += view.pageYOffset || html.scrollTop || body.scrollTop;
  11531. }
  11532. return new Rectangle(x, y, rect.width, rect.height);
  11533. },
  11534. getViewportBounds: function(el) {
  11535. var doc = el.ownerDocument,
  11536. view = doc.defaultView,
  11537. html = doc.documentElement;
  11538. return new Rectangle(0, 0,
  11539. view.innerWidth || html.clientWidth,
  11540. view.innerHeight || html.clientHeight
  11541. );
  11542. },
  11543. getOffset: function(el, viewport) {
  11544. return DomElement.getBounds(el, viewport).getPoint();
  11545. },
  11546. getSize: function(el) {
  11547. return DomElement.getBounds(el, true).getSize();
  11548. },
  11549. isInvisible: function(el) {
  11550. return DomElement.getSize(el).equals(new Size(0, 0));
  11551. },
  11552. isInView: function(el) {
  11553. return !DomElement.isInvisible(el)
  11554. && DomElement.getViewportBounds(el).intersects(
  11555. DomElement.getBounds(el, true));
  11556. },
  11557. isInserted: function(el) {
  11558. return document.body.contains(el);
  11559. },
  11560. getPrefixed: function(el, name) {
  11561. return el && handlePrefix(el, name);
  11562. },
  11563. setPrefixed: function(el, name, value) {
  11564. if (typeof name === 'object') {
  11565. for (var key in name)
  11566. handlePrefix(el, key, true, name[key]);
  11567. } else {
  11568. handlePrefix(el, name, true, value);
  11569. }
  11570. }
  11571. };
  11572. };
  11573. var DomEvent = {
  11574. add: function(el, events) {
  11575. if (el) {
  11576. for (var type in events) {
  11577. var func = events[type],
  11578. parts = type.split(/[\s,]+/g);
  11579. for (var i = 0, l = parts.length; i < l; i++) {
  11580. var name = parts[i];
  11581. var options = (
  11582. el === document
  11583. && (name === 'touchstart' || name === 'touchmove')
  11584. ) ? { passive: false } : false;
  11585. el.addEventListener(name, func, options);
  11586. }
  11587. }
  11588. }
  11589. },
  11590. remove: function(el, events) {
  11591. if (el) {
  11592. for (var type in events) {
  11593. var func = events[type],
  11594. parts = type.split(/[\s,]+/g);
  11595. for (var i = 0, l = parts.length; i < l; i++)
  11596. el.removeEventListener(parts[i], func, false);
  11597. }
  11598. }
  11599. },
  11600. getPoint: function(event) {
  11601. var pos = event.targetTouches
  11602. ? event.targetTouches.length
  11603. ? event.targetTouches[0]
  11604. : event.changedTouches[0]
  11605. : event;
  11606. return new Point(
  11607. pos.pageX || pos.clientX + document.documentElement.scrollLeft,
  11608. pos.pageY || pos.clientY + document.documentElement.scrollTop
  11609. );
  11610. },
  11611. getTarget: function(event) {
  11612. return event.target || event.srcElement;
  11613. },
  11614. getRelatedTarget: function(event) {
  11615. return event.relatedTarget || event.toElement;
  11616. },
  11617. getOffset: function(event, target) {
  11618. return DomEvent.getPoint(event).subtract(DomElement.getOffset(
  11619. target || DomEvent.getTarget(event)));
  11620. }
  11621. };
  11622. DomEvent.requestAnimationFrame = new function() {
  11623. var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),
  11624. requested = false,
  11625. callbacks = [],
  11626. timer;
  11627. function handleCallbacks() {
  11628. var functions = callbacks;
  11629. callbacks = [];
  11630. for (var i = 0, l = functions.length; i < l; i++)
  11631. functions[i]();
  11632. requested = nativeRequest && callbacks.length;
  11633. if (requested)
  11634. nativeRequest(handleCallbacks);
  11635. }
  11636. return function(callback) {
  11637. callbacks.push(callback);
  11638. if (nativeRequest) {
  11639. if (!requested) {
  11640. nativeRequest(handleCallbacks);
  11641. requested = true;
  11642. }
  11643. } else if (!timer) {
  11644. timer = setInterval(handleCallbacks, 1000 / 60);
  11645. }
  11646. };
  11647. };
  11648. var View = Base.extend(Emitter, {
  11649. _class: 'View',
  11650. initialize: function View(project, element) {
  11651. function getSize(name) {
  11652. return element[name] || parseInt(element.getAttribute(name), 10);
  11653. }
  11654. function getCanvasSize() {
  11655. var size = DomElement.getSize(element);
  11656. return size.isNaN() || size.isZero()
  11657. ? new Size(getSize('width'), getSize('height'))
  11658. : size;
  11659. }
  11660. var size;
  11661. if (window && element) {
  11662. this._id = element.getAttribute('id');
  11663. if (this._id == null)
  11664. element.setAttribute('id', this._id = 'paper-view-' + View._id++);
  11665. DomEvent.add(element, this._viewEvents);
  11666. var none = 'none';
  11667. DomElement.setPrefixed(element.style, {
  11668. userDrag: none,
  11669. userSelect: none,
  11670. touchCallout: none,
  11671. contentZooming: none,
  11672. tapHighlightColor: 'rgba(0,0,0,0)'
  11673. });
  11674. if (PaperScope.hasAttribute(element, 'resize')) {
  11675. var that = this;
  11676. DomEvent.add(window, this._windowEvents = {
  11677. resize: function() {
  11678. that.setViewSize(getCanvasSize());
  11679. }
  11680. });
  11681. }
  11682. size = getCanvasSize();
  11683. if (PaperScope.hasAttribute(element, 'stats')
  11684. && typeof Stats !== 'undefined') {
  11685. this._stats = new Stats();
  11686. var stats = this._stats.domElement,
  11687. style = stats.style,
  11688. offset = DomElement.getOffset(element);
  11689. style.position = 'absolute';
  11690. style.left = offset.x + 'px';
  11691. style.top = offset.y + 'px';
  11692. document.body.appendChild(stats);
  11693. }
  11694. } else {
  11695. size = new Size(element);
  11696. element = null;
  11697. }
  11698. this._project = project;
  11699. this._scope = project._scope;
  11700. this._element = element;
  11701. if (!this._pixelRatio)
  11702. this._pixelRatio = window && window.devicePixelRatio || 1;
  11703. this._setElementSize(size.width, size.height);
  11704. this._viewSize = size;
  11705. View._views.push(this);
  11706. View._viewsById[this._id] = this;
  11707. (this._matrix = new Matrix())._owner = this;
  11708. if (!View._focused)
  11709. View._focused = this;
  11710. this._frameItems = {};
  11711. this._frameItemCount = 0;
  11712. this._itemEvents = { native: {}, virtual: {} };
  11713. this._autoUpdate = !paper.agent.node;
  11714. this._needsUpdate = false;
  11715. },
  11716. remove: function() {
  11717. if (!this._project)
  11718. return false;
  11719. if (View._focused === this)
  11720. View._focused = null;
  11721. View._views.splice(View._views.indexOf(this), 1);
  11722. delete View._viewsById[this._id];
  11723. var project = this._project;
  11724. if (project._view === this)
  11725. project._view = null;
  11726. DomEvent.remove(this._element, this._viewEvents);
  11727. DomEvent.remove(window, this._windowEvents);
  11728. this._element = this._project = null;
  11729. this.off('frame');
  11730. this._animate = false;
  11731. this._frameItems = {};
  11732. return true;
  11733. },
  11734. _events: Base.each(
  11735. Item._itemHandlers.concat(['onResize', 'onKeyDown', 'onKeyUp']),
  11736. function(name) {
  11737. this[name] = {};
  11738. }, {
  11739. onFrame: {
  11740. install: function() {
  11741. this.play();
  11742. },
  11743. uninstall: function() {
  11744. this.pause();
  11745. }
  11746. }
  11747. }
  11748. ),
  11749. _animate: false,
  11750. _time: 0,
  11751. _count: 0,
  11752. getAutoUpdate: function() {
  11753. return this._autoUpdate;
  11754. },
  11755. setAutoUpdate: function(autoUpdate) {
  11756. this._autoUpdate = autoUpdate;
  11757. if (autoUpdate)
  11758. this.requestUpdate();
  11759. },
  11760. update: function() {
  11761. },
  11762. draw: function() {
  11763. this.update();
  11764. },
  11765. requestUpdate: function() {
  11766. if (!this._requested) {
  11767. var that = this;
  11768. DomEvent.requestAnimationFrame(function() {
  11769. that._requested = false;
  11770. if (that._animate) {
  11771. that.requestUpdate();
  11772. var element = that._element;
  11773. if ((!DomElement.getPrefixed(document, 'hidden')
  11774. || PaperScope.getAttribute(element, 'keepalive')
  11775. === 'true') && DomElement.isInView(element)) {
  11776. that._handleFrame();
  11777. }
  11778. }
  11779. if (that._autoUpdate)
  11780. that.update();
  11781. });
  11782. this._requested = true;
  11783. }
  11784. },
  11785. play: function() {
  11786. this._animate = true;
  11787. this.requestUpdate();
  11788. },
  11789. pause: function() {
  11790. this._animate = false;
  11791. },
  11792. _handleFrame: function() {
  11793. paper = this._scope;
  11794. var now = Date.now() / 1000,
  11795. delta = this._last ? now - this._last : 0;
  11796. this._last = now;
  11797. this.emit('frame', new Base({
  11798. delta: delta,
  11799. time: this._time += delta,
  11800. count: this._count++
  11801. }));
  11802. if (this._stats)
  11803. this._stats.update();
  11804. },
  11805. _animateItem: function(item, animate) {
  11806. var items = this._frameItems;
  11807. if (animate) {
  11808. items[item._id] = {
  11809. item: item,
  11810. time: 0,
  11811. count: 0
  11812. };
  11813. if (++this._frameItemCount === 1)
  11814. this.on('frame', this._handleFrameItems);
  11815. } else {
  11816. delete items[item._id];
  11817. if (--this._frameItemCount === 0) {
  11818. this.off('frame', this._handleFrameItems);
  11819. }
  11820. }
  11821. },
  11822. _handleFrameItems: function(event) {
  11823. for (var i in this._frameItems) {
  11824. var entry = this._frameItems[i];
  11825. entry.item.emit('frame', new Base(event, {
  11826. time: entry.time += event.delta,
  11827. count: entry.count++
  11828. }));
  11829. }
  11830. },
  11831. _changed: function() {
  11832. this._project._changed(4097);
  11833. this._bounds = this._decomposed = undefined;
  11834. },
  11835. getElement: function() {
  11836. return this._element;
  11837. },
  11838. getPixelRatio: function() {
  11839. return this._pixelRatio;
  11840. },
  11841. getResolution: function() {
  11842. return this._pixelRatio * 72;
  11843. },
  11844. getViewSize: function() {
  11845. var size = this._viewSize;
  11846. return new LinkedSize(size.width, size.height, this, 'setViewSize');
  11847. },
  11848. setViewSize: function() {
  11849. var size = Size.read(arguments),
  11850. delta = size.subtract(this._viewSize);
  11851. if (delta.isZero())
  11852. return;
  11853. this._setElementSize(size.width, size.height);
  11854. this._viewSize.set(size);
  11855. this._changed();
  11856. this.emit('resize', { size: size, delta: delta });
  11857. if (this._autoUpdate) {
  11858. this.update();
  11859. }
  11860. },
  11861. _setElementSize: function(width, height) {
  11862. var element = this._element;
  11863. if (element) {
  11864. if (element.width !== width)
  11865. element.width = width;
  11866. if (element.height !== height)
  11867. element.height = height;
  11868. }
  11869. },
  11870. getBounds: function() {
  11871. if (!this._bounds)
  11872. this._bounds = this._matrix.inverted()._transformBounds(
  11873. new Rectangle(new Point(), this._viewSize));
  11874. return this._bounds;
  11875. },
  11876. getSize: function() {
  11877. return this.getBounds().getSize();
  11878. },
  11879. isVisible: function() {
  11880. return DomElement.isInView(this._element);
  11881. },
  11882. isInserted: function() {
  11883. return DomElement.isInserted(this._element);
  11884. },
  11885. getPixelSize: function(size) {
  11886. var element = this._element,
  11887. pixels;
  11888. if (element) {
  11889. var parent = element.parentNode,
  11890. temp = document.createElement('div');
  11891. temp.style.fontSize = size;
  11892. parent.appendChild(temp);
  11893. pixels = parseFloat(DomElement.getStyles(temp).fontSize);
  11894. parent.removeChild(temp);
  11895. } else {
  11896. pixels = parseFloat(pixels);
  11897. }
  11898. return pixels;
  11899. },
  11900. getTextWidth: function(font, lines) {
  11901. return 0;
  11902. }
  11903. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  11904. var rotate = key === 'rotate';
  11905. this[key] = function() {
  11906. var args = arguments,
  11907. value = (rotate ? Base : Point).read(args),
  11908. center = Point.read(args, 0, { readNull: true });
  11909. return this.transform(new Matrix()[key](value,
  11910. center || this.getCenter(true)));
  11911. };
  11912. }, {
  11913. _decompose: function() {
  11914. return this._decomposed || (this._decomposed = this._matrix.decompose());
  11915. },
  11916. translate: function() {
  11917. var mx = new Matrix();
  11918. return this.transform(mx.translate.apply(mx, arguments));
  11919. },
  11920. getCenter: function() {
  11921. return this.getBounds().getCenter();
  11922. },
  11923. setCenter: function() {
  11924. var center = Point.read(arguments);
  11925. this.translate(this.getCenter().subtract(center));
  11926. },
  11927. getZoom: function() {
  11928. var scaling = this._decompose().scaling;
  11929. return (scaling.x + scaling.y) / 2;
  11930. },
  11931. setZoom: function(zoom) {
  11932. this.transform(new Matrix().scale(zoom / this.getZoom(),
  11933. this.getCenter()));
  11934. },
  11935. getRotation: function() {
  11936. return this._decompose().rotation;
  11937. },
  11938. setRotation: function(rotation) {
  11939. var current = this.getRotation();
  11940. if (current != null && rotation != null) {
  11941. this.rotate(rotation - current);
  11942. }
  11943. },
  11944. getScaling: function() {
  11945. var scaling = this._decompose().scaling;
  11946. return new LinkedPoint(scaling.x, scaling.y, this, 'setScaling');
  11947. },
  11948. setScaling: function() {
  11949. var current = this.getScaling(),
  11950. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  11951. if (current && scaling) {
  11952. this.scale(scaling.x / current.x, scaling.y / current.y);
  11953. }
  11954. },
  11955. getMatrix: function() {
  11956. return this._matrix;
  11957. },
  11958. setMatrix: function() {
  11959. var matrix = this._matrix;
  11960. matrix.set.apply(matrix, arguments);
  11961. },
  11962. transform: function(matrix) {
  11963. this._matrix.append(matrix);
  11964. },
  11965. scrollBy: function() {
  11966. this.translate(Point.read(arguments).negate());
  11967. }
  11968. }), {
  11969. projectToView: function() {
  11970. return this._matrix._transformPoint(Point.read(arguments));
  11971. },
  11972. viewToProject: function() {
  11973. return this._matrix._inverseTransform(Point.read(arguments));
  11974. },
  11975. getEventPoint: function(event) {
  11976. return this.viewToProject(DomEvent.getOffset(event, this._element));
  11977. },
  11978. }, {
  11979. statics: {
  11980. _views: [],
  11981. _viewsById: {},
  11982. _id: 0,
  11983. create: function(project, element) {
  11984. if (document && typeof element === 'string')
  11985. element = document.getElementById(element);
  11986. var ctor = window ? CanvasView : View;
  11987. return new ctor(project, element);
  11988. }
  11989. }
  11990. },
  11991. new function() {
  11992. if (!window)
  11993. return;
  11994. var prevFocus,
  11995. tempFocus,
  11996. dragging = false,
  11997. mouseDown = false;
  11998. function getView(event) {
  11999. var target = DomEvent.getTarget(event);
  12000. return target.getAttribute && View._viewsById[
  12001. target.getAttribute('id')];
  12002. }
  12003. function updateFocus() {
  12004. var view = View._focused;
  12005. if (!view || !view.isVisible()) {
  12006. for (var i = 0, l = View._views.length; i < l; i++) {
  12007. if ((view = View._views[i]).isVisible()) {
  12008. View._focused = tempFocus = view;
  12009. break;
  12010. }
  12011. }
  12012. }
  12013. }
  12014. function handleMouseMove(view, event, point) {
  12015. view._handleMouseEvent('mousemove', event, point);
  12016. }
  12017. var navigator = window.navigator,
  12018. mousedown, mousemove, mouseup;
  12019. if (navigator.pointerEnabled || navigator.msPointerEnabled) {
  12020. mousedown = 'pointerdown MSPointerDown';
  12021. mousemove = 'pointermove MSPointerMove';
  12022. mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';
  12023. } else {
  12024. mousedown = 'touchstart';
  12025. mousemove = 'touchmove';
  12026. mouseup = 'touchend touchcancel';
  12027. if (!('ontouchstart' in window && navigator.userAgent.match(
  12028. /mobile|tablet|ip(ad|hone|od)|android|silk/i))) {
  12029. mousedown += ' mousedown';
  12030. mousemove += ' mousemove';
  12031. mouseup += ' mouseup';
  12032. }
  12033. }
  12034. var viewEvents = {},
  12035. docEvents = {
  12036. mouseout: function(event) {
  12037. var view = View._focused,
  12038. target = DomEvent.getRelatedTarget(event);
  12039. if (view && (!target || target.nodeName === 'HTML')) {
  12040. var offset = DomEvent.getOffset(event, view._element),
  12041. x = offset.x,
  12042. abs = Math.abs,
  12043. ax = abs(x),
  12044. max = 1 << 25,
  12045. diff = ax - max;
  12046. offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x;
  12047. handleMouseMove(view, event, view.viewToProject(offset));
  12048. }
  12049. },
  12050. scroll: updateFocus
  12051. };
  12052. viewEvents[mousedown] = function(event) {
  12053. var view = View._focused = getView(event);
  12054. if (!dragging) {
  12055. dragging = true;
  12056. view._handleMouseEvent('mousedown', event);
  12057. }
  12058. };
  12059. docEvents[mousemove] = function(event) {
  12060. var view = View._focused;
  12061. if (!mouseDown) {
  12062. var target = getView(event);
  12063. if (target) {
  12064. if (view !== target) {
  12065. if (view)
  12066. handleMouseMove(view, event);
  12067. if (!prevFocus)
  12068. prevFocus = view;
  12069. view = View._focused = tempFocus = target;
  12070. }
  12071. } else if (tempFocus && tempFocus === view) {
  12072. if (prevFocus && !prevFocus.isInserted())
  12073. prevFocus = null;
  12074. view = View._focused = prevFocus;
  12075. prevFocus = null;
  12076. updateFocus();
  12077. }
  12078. }
  12079. if (view)
  12080. handleMouseMove(view, event);
  12081. };
  12082. docEvents[mousedown] = function() {
  12083. mouseDown = true;
  12084. };
  12085. docEvents[mouseup] = function(event) {
  12086. var view = View._focused;
  12087. if (view && dragging)
  12088. view._handleMouseEvent('mouseup', event);
  12089. mouseDown = dragging = false;
  12090. };
  12091. DomEvent.add(document, docEvents);
  12092. DomEvent.add(window, {
  12093. load: updateFocus
  12094. });
  12095. var called = false,
  12096. prevented = false,
  12097. fallbacks = {
  12098. doubleclick: 'click',
  12099. mousedrag: 'mousemove'
  12100. },
  12101. wasInView = false,
  12102. overView,
  12103. downPoint,
  12104. lastPoint,
  12105. downItem,
  12106. overItem,
  12107. dragItem,
  12108. clickItem,
  12109. clickTime,
  12110. dblClick;
  12111. function emitMouseEvent(obj, target, type, event, point, prevPoint,
  12112. stopItem) {
  12113. var stopped = false,
  12114. mouseEvent;
  12115. function emit(obj, type) {
  12116. if (obj.responds(type)) {
  12117. if (!mouseEvent) {
  12118. mouseEvent = new MouseEvent(type, event, point,
  12119. target || obj,
  12120. prevPoint ? point.subtract(prevPoint) : null);
  12121. }
  12122. if (obj.emit(type, mouseEvent)) {
  12123. called = true;
  12124. if (mouseEvent.prevented)
  12125. prevented = true;
  12126. if (mouseEvent.stopped)
  12127. return stopped = true;
  12128. }
  12129. } else {
  12130. var fallback = fallbacks[type];
  12131. if (fallback)
  12132. return emit(obj, fallback);
  12133. }
  12134. }
  12135. while (obj && obj !== stopItem) {
  12136. if (emit(obj, type))
  12137. break;
  12138. obj = obj._parent;
  12139. }
  12140. return stopped;
  12141. }
  12142. function emitMouseEvents(view, hitItem, type, event, point, prevPoint) {
  12143. view._project.removeOn(type);
  12144. prevented = called = false;
  12145. return (dragItem && emitMouseEvent(dragItem, null, type, event,
  12146. point, prevPoint)
  12147. || hitItem && hitItem !== dragItem
  12148. && !hitItem.isDescendant(dragItem)
  12149. && emitMouseEvent(hitItem, null, type === 'mousedrag' ?
  12150. 'mousemove' : type, event, point, prevPoint, dragItem)
  12151. || emitMouseEvent(view, dragItem || hitItem || view, type, event,
  12152. point, prevPoint));
  12153. }
  12154. var itemEventsMap = {
  12155. mousedown: {
  12156. mousedown: 1,
  12157. mousedrag: 1,
  12158. click: 1,
  12159. doubleclick: 1
  12160. },
  12161. mouseup: {
  12162. mouseup: 1,
  12163. mousedrag: 1,
  12164. click: 1,
  12165. doubleclick: 1
  12166. },
  12167. mousemove: {
  12168. mousedrag: 1,
  12169. mousemove: 1,
  12170. mouseenter: 1,
  12171. mouseleave: 1
  12172. }
  12173. };
  12174. return {
  12175. _viewEvents: viewEvents,
  12176. _handleMouseEvent: function(type, event, point) {
  12177. var itemEvents = this._itemEvents,
  12178. hitItems = itemEvents.native[type],
  12179. nativeMove = type === 'mousemove',
  12180. tool = this._scope.tool,
  12181. view = this;
  12182. function responds(type) {
  12183. return itemEvents.virtual[type] || view.responds(type)
  12184. || tool && tool.responds(type);
  12185. }
  12186. if (nativeMove && dragging && responds('mousedrag'))
  12187. type = 'mousedrag';
  12188. if (!point)
  12189. point = this.getEventPoint(event);
  12190. var inView = this.getBounds().contains(point),
  12191. hit = hitItems && inView && view._project.hitTest(point, {
  12192. tolerance: 0,
  12193. fill: true,
  12194. stroke: true
  12195. }),
  12196. hitItem = hit && hit.item || null,
  12197. handle = false,
  12198. mouse = {};
  12199. mouse[type.substr(5)] = true;
  12200. if (hitItems && hitItem !== overItem) {
  12201. if (overItem) {
  12202. emitMouseEvent(overItem, null, 'mouseleave', event, point);
  12203. }
  12204. if (hitItem) {
  12205. emitMouseEvent(hitItem, null, 'mouseenter', event, point);
  12206. }
  12207. overItem = hitItem;
  12208. }
  12209. if (wasInView ^ inView) {
  12210. emitMouseEvent(this, null, inView ? 'mouseenter' : 'mouseleave',
  12211. event, point);
  12212. overView = inView ? this : null;
  12213. handle = true;
  12214. }
  12215. if ((inView || mouse.drag) && !point.equals(lastPoint)) {
  12216. emitMouseEvents(this, hitItem, nativeMove ? type : 'mousemove',
  12217. event, point, lastPoint);
  12218. handle = true;
  12219. }
  12220. wasInView = inView;
  12221. if (mouse.down && inView || mouse.up && downPoint) {
  12222. emitMouseEvents(this, hitItem, type, event, point, downPoint);
  12223. if (mouse.down) {
  12224. dblClick = hitItem === clickItem
  12225. && (Date.now() - clickTime < 300);
  12226. downItem = clickItem = hitItem;
  12227. if (!prevented && hitItem) {
  12228. var item = hitItem;
  12229. while (item && !item.responds('mousedrag'))
  12230. item = item._parent;
  12231. if (item)
  12232. dragItem = hitItem;
  12233. }
  12234. downPoint = point;
  12235. } else if (mouse.up) {
  12236. if (!prevented && hitItem === downItem) {
  12237. clickTime = Date.now();
  12238. emitMouseEvents(this, hitItem, dblClick ? 'doubleclick'
  12239. : 'click', event, point, downPoint);
  12240. dblClick = false;
  12241. }
  12242. downItem = dragItem = null;
  12243. }
  12244. wasInView = false;
  12245. handle = true;
  12246. }
  12247. lastPoint = point;
  12248. if (handle && tool) {
  12249. called = tool._handleMouseEvent(type, event, point, mouse)
  12250. || called;
  12251. }
  12252. if (
  12253. event.cancelable !== false
  12254. && (called && !mouse.move || mouse.down && responds('mouseup'))
  12255. ) {
  12256. event.preventDefault();
  12257. }
  12258. },
  12259. _handleKeyEvent: function(type, event, key, character) {
  12260. var scope = this._scope,
  12261. tool = scope.tool,
  12262. keyEvent;
  12263. function emit(obj) {
  12264. if (obj.responds(type)) {
  12265. paper = scope;
  12266. obj.emit(type, keyEvent = keyEvent
  12267. || new KeyEvent(type, event, key, character));
  12268. }
  12269. }
  12270. if (this.isVisible()) {
  12271. emit(this);
  12272. if (tool && tool.responds(type))
  12273. emit(tool);
  12274. }
  12275. },
  12276. _countItemEvent: function(type, sign) {
  12277. var itemEvents = this._itemEvents,
  12278. native = itemEvents.native,
  12279. virtual = itemEvents.virtual;
  12280. for (var key in itemEventsMap) {
  12281. native[key] = (native[key] || 0)
  12282. + (itemEventsMap[key][type] || 0) * sign;
  12283. }
  12284. virtual[type] = (virtual[type] || 0) + sign;
  12285. },
  12286. statics: {
  12287. updateFocus: updateFocus,
  12288. _resetState: function() {
  12289. dragging = mouseDown = called = wasInView = false;
  12290. prevFocus = tempFocus = overView = downPoint = lastPoint =
  12291. downItem = overItem = dragItem = clickItem = clickTime =
  12292. dblClick = null;
  12293. }
  12294. }
  12295. };
  12296. });
  12297. var CanvasView = View.extend({
  12298. _class: 'CanvasView',
  12299. initialize: function CanvasView(project, canvas) {
  12300. if (!(canvas instanceof window.HTMLCanvasElement)) {
  12301. var size = Size.read(arguments, 1);
  12302. if (size.isZero())
  12303. throw new Error(
  12304. 'Cannot create CanvasView with the provided argument: '
  12305. + Base.slice(arguments, 1));
  12306. canvas = CanvasProvider.getCanvas(size);
  12307. }
  12308. var ctx = this._context = canvas.getContext('2d');
  12309. ctx.save();
  12310. this._pixelRatio = 1;
  12311. if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) {
  12312. var deviceRatio = window.devicePixelRatio || 1,
  12313. backingStoreRatio = DomElement.getPrefixed(ctx,
  12314. 'backingStorePixelRatio') || 1;
  12315. this._pixelRatio = deviceRatio / backingStoreRatio;
  12316. }
  12317. View.call(this, project, canvas);
  12318. this._needsUpdate = true;
  12319. },
  12320. remove: function remove() {
  12321. this._context.restore();
  12322. return remove.base.call(this);
  12323. },
  12324. _setElementSize: function _setElementSize(width, height) {
  12325. var pixelRatio = this._pixelRatio;
  12326. _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio);
  12327. if (pixelRatio !== 1) {
  12328. var element = this._element,
  12329. ctx = this._context;
  12330. if (!PaperScope.hasAttribute(element, 'resize')) {
  12331. var style = element.style;
  12332. style.width = width + 'px';
  12333. style.height = height + 'px';
  12334. }
  12335. ctx.restore();
  12336. ctx.save();
  12337. ctx.scale(pixelRatio, pixelRatio);
  12338. }
  12339. },
  12340. getContext: function() {
  12341. return this._context;
  12342. },
  12343. getPixelSize: function getPixelSize(size) {
  12344. var agent = paper.agent,
  12345. pixels;
  12346. if (agent && agent.firefox) {
  12347. pixels = getPixelSize.base.call(this, size);
  12348. } else {
  12349. var ctx = this._context,
  12350. prevFont = ctx.font;
  12351. ctx.font = size + ' serif';
  12352. pixels = parseFloat(ctx.font);
  12353. ctx.font = prevFont;
  12354. }
  12355. return pixels;
  12356. },
  12357. getTextWidth: function(font, lines) {
  12358. var ctx = this._context,
  12359. prevFont = ctx.font,
  12360. width = 0;
  12361. ctx.font = font;
  12362. for (var i = 0, l = lines.length; i < l; i++)
  12363. width = Math.max(width, ctx.measureText(lines[i]).width);
  12364. ctx.font = prevFont;
  12365. return width;
  12366. },
  12367. update: function() {
  12368. if (!this._needsUpdate)
  12369. return false;
  12370. var project = this._project,
  12371. ctx = this._context,
  12372. size = this._viewSize;
  12373. ctx.clearRect(0, 0, size.width + 1, size.height + 1);
  12374. if (project)
  12375. project.draw(ctx, this._matrix, this._pixelRatio);
  12376. this._needsUpdate = false;
  12377. return true;
  12378. }
  12379. });
  12380. var Event = Base.extend({
  12381. _class: 'Event',
  12382. initialize: function Event(event) {
  12383. this.event = event;
  12384. this.type = event && event.type;
  12385. },
  12386. prevented: false,
  12387. stopped: false,
  12388. preventDefault: function() {
  12389. this.prevented = true;
  12390. this.event.preventDefault();
  12391. },
  12392. stopPropagation: function() {
  12393. this.stopped = true;
  12394. this.event.stopPropagation();
  12395. },
  12396. stop: function() {
  12397. this.stopPropagation();
  12398. this.preventDefault();
  12399. },
  12400. getTimeStamp: function() {
  12401. return this.event.timeStamp;
  12402. },
  12403. getModifiers: function() {
  12404. return Key.modifiers;
  12405. }
  12406. });
  12407. var KeyEvent = Event.extend({
  12408. _class: 'KeyEvent',
  12409. initialize: function KeyEvent(type, event, key, character) {
  12410. this.type = type;
  12411. this.event = event;
  12412. this.key = key;
  12413. this.character = character;
  12414. },
  12415. toString: function() {
  12416. return "{ type: '" + this.type
  12417. + "', key: '" + this.key
  12418. + "', character: '" + this.character
  12419. + "', modifiers: " + this.getModifiers()
  12420. + " }";
  12421. }
  12422. });
  12423. var Key = new function() {
  12424. var keyLookup = {
  12425. '\t': 'tab',
  12426. ' ': 'space',
  12427. '\b': 'backspace',
  12428. '\x7f': 'delete',
  12429. 'Spacebar': 'space',
  12430. 'Del': 'delete',
  12431. 'Win': 'meta',
  12432. 'Esc': 'escape'
  12433. },
  12434. charLookup = {
  12435. 'tab': '\t',
  12436. 'space': ' ',
  12437. 'enter': '\r'
  12438. },
  12439. keyMap = {},
  12440. charMap = {},
  12441. metaFixMap,
  12442. downKey,
  12443. modifiers = new Base({
  12444. shift: false,
  12445. control: false,
  12446. alt: false,
  12447. meta: false,
  12448. capsLock: false,
  12449. space: false
  12450. }).inject({
  12451. option: {
  12452. get: function() {
  12453. return this.alt;
  12454. }
  12455. },
  12456. command: {
  12457. get: function() {
  12458. var agent = paper && paper.agent;
  12459. return agent && agent.mac ? this.meta : this.control;
  12460. }
  12461. }
  12462. });
  12463. function getKey(event) {
  12464. var key = event.key || event.keyIdentifier;
  12465. key = /^U\+/.test(key)
  12466. ? String.fromCharCode(parseInt(key.substr(2), 16))
  12467. : /^Arrow[A-Z]/.test(key) ? key.substr(5)
  12468. : key === 'Unidentified' || key === undefined
  12469. ? String.fromCharCode(event.keyCode)
  12470. : key;
  12471. return keyLookup[key] ||
  12472. (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase());
  12473. }
  12474. function handleKey(down, key, character, event) {
  12475. var type = down ? 'keydown' : 'keyup',
  12476. view = View._focused,
  12477. name;
  12478. keyMap[key] = down;
  12479. if (down) {
  12480. charMap[key] = character;
  12481. } else {
  12482. delete charMap[key];
  12483. }
  12484. if (key.length > 1 && (name = Base.camelize(key)) in modifiers) {
  12485. modifiers[name] = down;
  12486. var agent = paper && paper.agent;
  12487. if (name === 'meta' && agent && agent.mac) {
  12488. if (down) {
  12489. metaFixMap = {};
  12490. } else {
  12491. for (var k in metaFixMap) {
  12492. if (k in charMap)
  12493. handleKey(false, k, metaFixMap[k], event);
  12494. }
  12495. metaFixMap = null;
  12496. }
  12497. }
  12498. } else if (down && metaFixMap) {
  12499. metaFixMap[key] = character;
  12500. }
  12501. if (view) {
  12502. view._handleKeyEvent(down ? 'keydown' : 'keyup', event, key,
  12503. character);
  12504. }
  12505. }
  12506. DomEvent.add(document, {
  12507. keydown: function(event) {
  12508. var key = getKey(event),
  12509. agent = paper && paper.agent;
  12510. if (key.length > 1 || agent && (agent.chrome && (event.altKey
  12511. || agent.mac && event.metaKey
  12512. || !agent.mac && event.ctrlKey))) {
  12513. handleKey(true, key,
  12514. charLookup[key] || (key.length > 1 ? '' : key), event);
  12515. } else {
  12516. downKey = key;
  12517. }
  12518. },
  12519. keypress: function(event) {
  12520. if (downKey) {
  12521. var key = getKey(event),
  12522. code = event.charCode,
  12523. character = code >= 32 ? String.fromCharCode(code)
  12524. : key.length > 1 ? '' : key;
  12525. if (key !== downKey) {
  12526. key = character.toLowerCase();
  12527. }
  12528. handleKey(true, key, character, event);
  12529. downKey = null;
  12530. }
  12531. },
  12532. keyup: function(event) {
  12533. var key = getKey(event);
  12534. if (key in charMap)
  12535. handleKey(false, key, charMap[key], event);
  12536. }
  12537. });
  12538. DomEvent.add(window, {
  12539. blur: function(event) {
  12540. for (var key in charMap)
  12541. handleKey(false, key, charMap[key], event);
  12542. }
  12543. });
  12544. return {
  12545. modifiers: modifiers,
  12546. isDown: function(key) {
  12547. return !!keyMap[key];
  12548. }
  12549. };
  12550. };
  12551. var MouseEvent = Event.extend({
  12552. _class: 'MouseEvent',
  12553. initialize: function MouseEvent(type, event, point, target, delta) {
  12554. this.type = type;
  12555. this.event = event;
  12556. this.point = point;
  12557. this.target = target;
  12558. this.delta = delta;
  12559. },
  12560. toString: function() {
  12561. return "{ type: '" + this.type
  12562. + "', point: " + this.point
  12563. + ', target: ' + this.target
  12564. + (this.delta ? ', delta: ' + this.delta : '')
  12565. + ', modifiers: ' + this.getModifiers()
  12566. + ' }';
  12567. }
  12568. });
  12569. var ToolEvent = Event.extend({
  12570. _class: 'ToolEvent',
  12571. _item: null,
  12572. initialize: function ToolEvent(tool, type, event) {
  12573. this.tool = tool;
  12574. this.type = type;
  12575. this.event = event;
  12576. },
  12577. _choosePoint: function(point, toolPoint) {
  12578. return point ? point : toolPoint ? toolPoint.clone() : null;
  12579. },
  12580. getPoint: function() {
  12581. return this._choosePoint(this._point, this.tool._point);
  12582. },
  12583. setPoint: function(point) {
  12584. this._point = point;
  12585. },
  12586. getLastPoint: function() {
  12587. return this._choosePoint(this._lastPoint, this.tool._lastPoint);
  12588. },
  12589. setLastPoint: function(lastPoint) {
  12590. this._lastPoint = lastPoint;
  12591. },
  12592. getDownPoint: function() {
  12593. return this._choosePoint(this._downPoint, this.tool._downPoint);
  12594. },
  12595. setDownPoint: function(downPoint) {
  12596. this._downPoint = downPoint;
  12597. },
  12598. getMiddlePoint: function() {
  12599. if (!this._middlePoint && this.tool._lastPoint) {
  12600. return this.tool._point.add(this.tool._lastPoint).divide(2);
  12601. }
  12602. return this._middlePoint;
  12603. },
  12604. setMiddlePoint: function(middlePoint) {
  12605. this._middlePoint = middlePoint;
  12606. },
  12607. getDelta: function() {
  12608. return !this._delta && this.tool._lastPoint
  12609. ? this.tool._point.subtract(this.tool._lastPoint)
  12610. : this._delta;
  12611. },
  12612. setDelta: function(delta) {
  12613. this._delta = delta;
  12614. },
  12615. getCount: function() {
  12616. return this.tool[/^mouse(down|up)$/.test(this.type)
  12617. ? '_downCount' : '_moveCount'];
  12618. },
  12619. setCount: function(count) {
  12620. this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
  12621. = count;
  12622. },
  12623. getItem: function() {
  12624. if (!this._item) {
  12625. var result = this.tool._scope.project.hitTest(this.getPoint());
  12626. if (result) {
  12627. var item = result.item,
  12628. parent = item._parent;
  12629. while (/^(Group|CompoundPath)$/.test(parent._class)) {
  12630. item = parent;
  12631. parent = parent._parent;
  12632. }
  12633. this._item = item;
  12634. }
  12635. }
  12636. return this._item;
  12637. },
  12638. setItem: function(item) {
  12639. this._item = item;
  12640. },
  12641. toString: function() {
  12642. return '{ type: ' + this.type
  12643. + ', point: ' + this.getPoint()
  12644. + ', count: ' + this.getCount()
  12645. + ', modifiers: ' + this.getModifiers()
  12646. + ' }';
  12647. }
  12648. });
  12649. var Tool = PaperScopeItem.extend({
  12650. _class: 'Tool',
  12651. _list: 'tools',
  12652. _reference: 'tool',
  12653. _events: ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
  12654. 'onActivate', 'onDeactivate', 'onEditOptions', 'onKeyDown',
  12655. 'onKeyUp'],
  12656. initialize: function Tool(props) {
  12657. PaperScopeItem.call(this);
  12658. this._moveCount = -1;
  12659. this._downCount = -1;
  12660. this.set(props);
  12661. },
  12662. getMinDistance: function() {
  12663. return this._minDistance;
  12664. },
  12665. setMinDistance: function(minDistance) {
  12666. this._minDistance = minDistance;
  12667. if (minDistance != null && this._maxDistance != null
  12668. && minDistance > this._maxDistance) {
  12669. this._maxDistance = minDistance;
  12670. }
  12671. },
  12672. getMaxDistance: function() {
  12673. return this._maxDistance;
  12674. },
  12675. setMaxDistance: function(maxDistance) {
  12676. this._maxDistance = maxDistance;
  12677. if (this._minDistance != null && maxDistance != null
  12678. && maxDistance < this._minDistance) {
  12679. this._minDistance = maxDistance;
  12680. }
  12681. },
  12682. getFixedDistance: function() {
  12683. return this._minDistance == this._maxDistance
  12684. ? this._minDistance : null;
  12685. },
  12686. setFixedDistance: function(distance) {
  12687. this._minDistance = this._maxDistance = distance;
  12688. },
  12689. _handleMouseEvent: function(type, event, point, mouse) {
  12690. paper = this._scope;
  12691. if (mouse.drag && !this.responds(type))
  12692. type = 'mousemove';
  12693. var move = mouse.move || mouse.drag,
  12694. responds = this.responds(type),
  12695. minDistance = this.minDistance,
  12696. maxDistance = this.maxDistance,
  12697. called = false,
  12698. tool = this;
  12699. function update(minDistance, maxDistance) {
  12700. var pt = point,
  12701. toolPoint = move ? tool._point : (tool._downPoint || pt);
  12702. if (move) {
  12703. if (tool._moveCount >= 0 && pt.equals(toolPoint)) {
  12704. return false;
  12705. }
  12706. if (toolPoint && (minDistance != null || maxDistance != null)) {
  12707. var vector = pt.subtract(toolPoint),
  12708. distance = vector.getLength();
  12709. if (distance < (minDistance || 0))
  12710. return false;
  12711. if (maxDistance) {
  12712. pt = toolPoint.add(vector.normalize(
  12713. Math.min(distance, maxDistance)));
  12714. }
  12715. }
  12716. tool._moveCount++;
  12717. }
  12718. tool._point = pt;
  12719. tool._lastPoint = toolPoint || pt;
  12720. if (mouse.down) {
  12721. tool._moveCount = -1;
  12722. tool._downPoint = pt;
  12723. tool._downCount++;
  12724. }
  12725. return true;
  12726. }
  12727. function emit() {
  12728. if (responds) {
  12729. called = tool.emit(type, new ToolEvent(tool, type, event))
  12730. || called;
  12731. }
  12732. }
  12733. if (mouse.down) {
  12734. update();
  12735. emit();
  12736. } else if (mouse.up) {
  12737. update(null, maxDistance);
  12738. emit();
  12739. } else if (responds) {
  12740. while (update(minDistance, maxDistance))
  12741. emit();
  12742. }
  12743. return called;
  12744. }
  12745. });
  12746. var Tween = Base.extend(Emitter, {
  12747. _class: 'Tween',
  12748. statics: {
  12749. easings: new Base({
  12750. linear: function(t) {
  12751. return t;
  12752. },
  12753. easeInQuad: function(t) {
  12754. return t * t;
  12755. },
  12756. easeOutQuad: function(t) {
  12757. return t * (2 - t);
  12758. },
  12759. easeInOutQuad: function(t) {
  12760. return t < 0.5
  12761. ? 2 * t * t
  12762. : -1 + 2 * (2 - t) * t;
  12763. },
  12764. easeInCubic: function(t) {
  12765. return t * t * t;
  12766. },
  12767. easeOutCubic: function(t) {
  12768. return --t * t * t + 1;
  12769. },
  12770. easeInOutCubic: function(t) {
  12771. return t < 0.5
  12772. ? 4 * t * t * t
  12773. : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  12774. },
  12775. easeInQuart: function(t) {
  12776. return t * t * t * t;
  12777. },
  12778. easeOutQuart: function(t) {
  12779. return 1 - (--t) * t * t * t;
  12780. },
  12781. easeInOutQuart: function(t) {
  12782. return t < 0.5
  12783. ? 8 * t * t * t * t
  12784. : 1 - 8 * (--t) * t * t * t;
  12785. },
  12786. easeInQuint: function(t) {
  12787. return t * t * t * t * t;
  12788. },
  12789. easeOutQuint: function(t) {
  12790. return 1 + --t * t * t * t * t;
  12791. },
  12792. easeInOutQuint: function(t) {
  12793. return t < 0.5
  12794. ? 16 * t * t * t * t * t
  12795. : 1 + 16 * (--t) * t * t * t * t;
  12796. }
  12797. })
  12798. },
  12799. initialize: function Tween(object, from, to, duration, easing, start) {
  12800. this.object = object;
  12801. var type = typeof easing;
  12802. var isFunction = type === 'function';
  12803. this.type = isFunction
  12804. ? type
  12805. : type === 'string'
  12806. ? easing
  12807. : 'linear';
  12808. this.easing = isFunction ? easing : Tween.easings[this.type];
  12809. this.duration = duration;
  12810. this.running = false;
  12811. this._then = null;
  12812. this._startTime = null;
  12813. var state = from || to;
  12814. this._keys = state ? Object.keys(state) : [];
  12815. this._parsedKeys = this._parseKeys(this._keys);
  12816. this._from = state && this._getState(from);
  12817. this._to = state && this._getState(to);
  12818. if (start !== false) {
  12819. this.start();
  12820. }
  12821. },
  12822. then: function(then) {
  12823. this._then = then;
  12824. return this;
  12825. },
  12826. start: function() {
  12827. this._startTime = null;
  12828. this.running = true;
  12829. return this;
  12830. },
  12831. stop: function() {
  12832. this.running = false;
  12833. return this;
  12834. },
  12835. update: function(progress) {
  12836. if (this.running) {
  12837. if (progress >= 1) {
  12838. progress = 1;
  12839. this.running = false;
  12840. }
  12841. var factor = this.easing(progress),
  12842. keys = this._keys,
  12843. getValue = function(value) {
  12844. return typeof value === 'function'
  12845. ? value(factor, progress)
  12846. : value;
  12847. };
  12848. for (var i = 0, l = keys && keys.length; i < l; i++) {
  12849. var key = keys[i],
  12850. from = getValue(this._from[key]),
  12851. to = getValue(this._to[key]),
  12852. value = (from && to && from.__add && to.__add)
  12853. ? to.__subtract(from).__multiply(factor).__add(from)
  12854. : ((to - from) * factor) + from;
  12855. this._setProperty(this._parsedKeys[key], value);
  12856. }
  12857. if (this.responds('update')) {
  12858. this.emit('update', new Base({
  12859. progress: progress,
  12860. factor: factor
  12861. }));
  12862. }
  12863. if (!this.running && this._then) {
  12864. this._then(this.object);
  12865. }
  12866. }
  12867. return this;
  12868. },
  12869. _events: {
  12870. onUpdate: {}
  12871. },
  12872. _handleFrame: function(time) {
  12873. var startTime = this._startTime,
  12874. progress = startTime
  12875. ? (time - startTime) / this.duration
  12876. : 0;
  12877. if (!startTime) {
  12878. this._startTime = time;
  12879. }
  12880. this.update(progress);
  12881. },
  12882. _getState: function(state) {
  12883. var keys = this._keys,
  12884. result = {};
  12885. for (var i = 0, l = keys.length; i < l; i++) {
  12886. var key = keys[i],
  12887. path = this._parsedKeys[key],
  12888. current = this._getProperty(path),
  12889. value;
  12890. if (state) {
  12891. var resolved = this._resolveValue(current, state[key]);
  12892. this._setProperty(path, resolved);
  12893. value = this._getProperty(path);
  12894. value = value && value.clone ? value.clone() : value;
  12895. this._setProperty(path, current);
  12896. } else {
  12897. value = current && current.clone ? current.clone() : current;
  12898. }
  12899. result[key] = value;
  12900. }
  12901. return result;
  12902. },
  12903. _resolveValue: function(current, value) {
  12904. if (value) {
  12905. if (Array.isArray(value) && value.length === 2) {
  12906. var operator = value[0];
  12907. return (
  12908. operator &&
  12909. operator.match &&
  12910. operator.match(/^[+\-\*\/]=/)
  12911. )
  12912. ? this._calculate(current, operator[0], value[1])
  12913. : value;
  12914. } else if (typeof value === 'string') {
  12915. var match = value.match(/^[+\-*/]=(.*)/);
  12916. if (match) {
  12917. var parsed = JSON.parse(match[1].replace(
  12918. /(['"])?([a-zA-Z0-9_]+)(['"])?:/g,
  12919. '"$2": '
  12920. ));
  12921. return this._calculate(current, value[0], parsed);
  12922. }
  12923. }
  12924. }
  12925. return value;
  12926. },
  12927. _calculate: function(left, operator, right) {
  12928. return paper.PaperScript.calculateBinary(left, operator, right);
  12929. },
  12930. _parseKeys: function(keys) {
  12931. var parsed = {};
  12932. for (var i = 0, l = keys.length; i < l; i++) {
  12933. var key = keys[i],
  12934. path = key
  12935. .replace(/\.([^.]*)/g, '/$1')
  12936. .replace(/\[['"]?([^'"\]]*)['"]?\]/g, '/$1');
  12937. parsed[key] = path.split('/');
  12938. }
  12939. return parsed;
  12940. },
  12941. _getProperty: function(path, offset) {
  12942. var obj = this.object;
  12943. for (var i = 0, l = path.length - (offset || 0); i < l && obj; i++) {
  12944. obj = obj[path[i]];
  12945. }
  12946. return obj;
  12947. },
  12948. _setProperty: function(path, value) {
  12949. var dest = this._getProperty(path, 1);
  12950. if (dest) {
  12951. dest[path[path.length - 1]] = value;
  12952. }
  12953. }
  12954. });
  12955. var Http = {
  12956. request: function(options) {
  12957. var xhr = new self.XMLHttpRequest();
  12958. xhr.open((options.method || 'get').toUpperCase(), options.url,
  12959. Base.pick(options.async, true));
  12960. if (options.mimeType)
  12961. xhr.overrideMimeType(options.mimeType);
  12962. xhr.onload = function() {
  12963. var status = xhr.status;
  12964. if (status === 0 || status === 200) {
  12965. if (options.onLoad) {
  12966. options.onLoad.call(xhr, xhr.responseText);
  12967. }
  12968. } else {
  12969. xhr.onerror();
  12970. }
  12971. };
  12972. xhr.onerror = function() {
  12973. var status = xhr.status,
  12974. message = 'Could not load "' + options.url + '" (Status: '
  12975. + status + ')';
  12976. if (options.onError) {
  12977. options.onError(message, status);
  12978. } else {
  12979. throw new Error(message);
  12980. }
  12981. };
  12982. return xhr.send(null);
  12983. }
  12984. };
  12985. var CanvasProvider = Base.exports.CanvasProvider = {
  12986. canvases: [],
  12987. getCanvas: function(width, height) {
  12988. if (!window)
  12989. return null;
  12990. var canvas,
  12991. clear = true;
  12992. if (typeof width === 'object') {
  12993. height = width.height;
  12994. width = width.width;
  12995. }
  12996. if (this.canvases.length) {
  12997. canvas = this.canvases.pop();
  12998. } else {
  12999. canvas = document.createElement('canvas');
  13000. clear = false;
  13001. }
  13002. var ctx = canvas.getContext('2d');
  13003. if (!ctx) {
  13004. throw new Error('Canvas ' + canvas +
  13005. ' is unable to provide a 2D context.');
  13006. }
  13007. if (canvas.width === width && canvas.height === height) {
  13008. if (clear)
  13009. ctx.clearRect(0, 0, width + 1, height + 1);
  13010. } else {
  13011. canvas.width = width;
  13012. canvas.height = height;
  13013. }
  13014. ctx.save();
  13015. return canvas;
  13016. },
  13017. getContext: function(width, height) {
  13018. var canvas = this.getCanvas(width, height);
  13019. return canvas ? canvas.getContext('2d') : null;
  13020. },
  13021. release: function(obj) {
  13022. var canvas = obj && obj.canvas ? obj.canvas : obj;
  13023. if (canvas && canvas.getContext) {
  13024. canvas.getContext('2d').restore();
  13025. this.canvases.push(canvas);
  13026. }
  13027. }
  13028. };
  13029. var BlendMode = new function() {
  13030. var min = Math.min,
  13031. max = Math.max,
  13032. abs = Math.abs,
  13033. sr, sg, sb, sa,
  13034. br, bg, bb, ba,
  13035. dr, dg, db;
  13036. function getLum(r, g, b) {
  13037. return 0.2989 * r + 0.587 * g + 0.114 * b;
  13038. }
  13039. function setLum(r, g, b, l) {
  13040. var d = l - getLum(r, g, b);
  13041. dr = r + d;
  13042. dg = g + d;
  13043. db = b + d;
  13044. var l = getLum(dr, dg, db),
  13045. mn = min(dr, dg, db),
  13046. mx = max(dr, dg, db);
  13047. if (mn < 0) {
  13048. var lmn = l - mn;
  13049. dr = l + (dr - l) * l / lmn;
  13050. dg = l + (dg - l) * l / lmn;
  13051. db = l + (db - l) * l / lmn;
  13052. }
  13053. if (mx > 255) {
  13054. var ln = 255 - l,
  13055. mxl = mx - l;
  13056. dr = l + (dr - l) * ln / mxl;
  13057. dg = l + (dg - l) * ln / mxl;
  13058. db = l + (db - l) * ln / mxl;
  13059. }
  13060. }
  13061. function getSat(r, g, b) {
  13062. return max(r, g, b) - min(r, g, b);
  13063. }
  13064. function setSat(r, g, b, s) {
  13065. var col = [r, g, b],
  13066. mx = max(r, g, b),
  13067. mn = min(r, g, b),
  13068. md;
  13069. mn = mn === r ? 0 : mn === g ? 1 : 2;
  13070. mx = mx === r ? 0 : mx === g ? 1 : 2;
  13071. md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
  13072. if (col[mx] > col[mn]) {
  13073. col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
  13074. col[mx] = s;
  13075. } else {
  13076. col[md] = col[mx] = 0;
  13077. }
  13078. col[mn] = 0;
  13079. dr = col[0];
  13080. dg = col[1];
  13081. db = col[2];
  13082. }
  13083. var modes = {
  13084. multiply: function() {
  13085. dr = br * sr / 255;
  13086. dg = bg * sg / 255;
  13087. db = bb * sb / 255;
  13088. },
  13089. screen: function() {
  13090. dr = br + sr - (br * sr / 255);
  13091. dg = bg + sg - (bg * sg / 255);
  13092. db = bb + sb - (bb * sb / 255);
  13093. },
  13094. overlay: function() {
  13095. dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
  13096. dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
  13097. db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
  13098. },
  13099. 'soft-light': function() {
  13100. var t = sr * br / 255;
  13101. dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
  13102. t = sg * bg / 255;
  13103. dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
  13104. t = sb * bb / 255;
  13105. db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
  13106. },
  13107. 'hard-light': function() {
  13108. dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
  13109. dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
  13110. db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
  13111. },
  13112. 'color-dodge': function() {
  13113. dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
  13114. dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
  13115. db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
  13116. },
  13117. 'color-burn': function() {
  13118. dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
  13119. dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
  13120. db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
  13121. },
  13122. darken: function() {
  13123. dr = br < sr ? br : sr;
  13124. dg = bg < sg ? bg : sg;
  13125. db = bb < sb ? bb : sb;
  13126. },
  13127. lighten: function() {
  13128. dr = br > sr ? br : sr;
  13129. dg = bg > sg ? bg : sg;
  13130. db = bb > sb ? bb : sb;
  13131. },
  13132. difference: function() {
  13133. dr = br - sr;
  13134. if (dr < 0)
  13135. dr = -dr;
  13136. dg = bg - sg;
  13137. if (dg < 0)
  13138. dg = -dg;
  13139. db = bb - sb;
  13140. if (db < 0)
  13141. db = -db;
  13142. },
  13143. exclusion: function() {
  13144. dr = br + sr * (255 - br - br) / 255;
  13145. dg = bg + sg * (255 - bg - bg) / 255;
  13146. db = bb + sb * (255 - bb - bb) / 255;
  13147. },
  13148. hue: function() {
  13149. setSat(sr, sg, sb, getSat(br, bg, bb));
  13150. setLum(dr, dg, db, getLum(br, bg, bb));
  13151. },
  13152. saturation: function() {
  13153. setSat(br, bg, bb, getSat(sr, sg, sb));
  13154. setLum(dr, dg, db, getLum(br, bg, bb));
  13155. },
  13156. luminosity: function() {
  13157. setLum(br, bg, bb, getLum(sr, sg, sb));
  13158. },
  13159. color: function() {
  13160. setLum(sr, sg, sb, getLum(br, bg, bb));
  13161. },
  13162. add: function() {
  13163. dr = min(br + sr, 255);
  13164. dg = min(bg + sg, 255);
  13165. db = min(bb + sb, 255);
  13166. },
  13167. subtract: function() {
  13168. dr = max(br - sr, 0);
  13169. dg = max(bg - sg, 0);
  13170. db = max(bb - sb, 0);
  13171. },
  13172. average: function() {
  13173. dr = (br + sr) / 2;
  13174. dg = (bg + sg) / 2;
  13175. db = (bb + sb) / 2;
  13176. },
  13177. negation: function() {
  13178. dr = 255 - abs(255 - sr - br);
  13179. dg = 255 - abs(255 - sg - bg);
  13180. db = 255 - abs(255 - sb - bb);
  13181. }
  13182. };
  13183. var nativeModes = this.nativeModes = Base.each([
  13184. 'source-over', 'source-in', 'source-out', 'source-atop',
  13185. 'destination-over', 'destination-in', 'destination-out',
  13186. 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
  13187. ], function(mode) {
  13188. this[mode] = true;
  13189. }, {});
  13190. var ctx = CanvasProvider.getContext(1, 1);
  13191. if (ctx) {
  13192. Base.each(modes, function(func, mode) {
  13193. var darken = mode === 'darken',
  13194. ok = false;
  13195. ctx.save();
  13196. try {
  13197. ctx.fillStyle = darken ? '#300' : '#a00';
  13198. ctx.fillRect(0, 0, 1, 1);
  13199. ctx.globalCompositeOperation = mode;
  13200. if (ctx.globalCompositeOperation === mode) {
  13201. ctx.fillStyle = darken ? '#a00' : '#300';
  13202. ctx.fillRect(0, 0, 1, 1);
  13203. ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken
  13204. ? 170 : 51;
  13205. }
  13206. } catch (e) {}
  13207. ctx.restore();
  13208. nativeModes[mode] = ok;
  13209. });
  13210. CanvasProvider.release(ctx);
  13211. }
  13212. this.process = function(mode, srcContext, dstContext, alpha, offset) {
  13213. var srcCanvas = srcContext.canvas,
  13214. normal = mode === 'normal';
  13215. if (normal || nativeModes[mode]) {
  13216. dstContext.save();
  13217. dstContext.setTransform(1, 0, 0, 1, 0, 0);
  13218. dstContext.globalAlpha = alpha;
  13219. if (!normal)
  13220. dstContext.globalCompositeOperation = mode;
  13221. dstContext.drawImage(srcCanvas, offset.x, offset.y);
  13222. dstContext.restore();
  13223. } else {
  13224. var process = modes[mode];
  13225. if (!process)
  13226. return;
  13227. var dstData = dstContext.getImageData(offset.x, offset.y,
  13228. srcCanvas.width, srcCanvas.height),
  13229. dst = dstData.data,
  13230. src = srcContext.getImageData(0, 0,
  13231. srcCanvas.width, srcCanvas.height).data;
  13232. for (var i = 0, l = dst.length; i < l; i += 4) {
  13233. sr = src[i];
  13234. br = dst[i];
  13235. sg = src[i + 1];
  13236. bg = dst[i + 1];
  13237. sb = src[i + 2];
  13238. bb = dst[i + 2];
  13239. sa = src[i + 3];
  13240. ba = dst[i + 3];
  13241. process();
  13242. var a1 = sa * alpha / 255,
  13243. a2 = 1 - a1;
  13244. dst[i] = a1 * dr + a2 * br;
  13245. dst[i + 1] = a1 * dg + a2 * bg;
  13246. dst[i + 2] = a1 * db + a2 * bb;
  13247. dst[i + 3] = sa * alpha + a2 * ba;
  13248. }
  13249. dstContext.putImageData(dstData, offset.x, offset.y);
  13250. }
  13251. };
  13252. };
  13253. var SvgElement = new function() {
  13254. var svg = 'http://www.w3.org/2000/svg',
  13255. xmlns = 'http://www.w3.org/2000/xmlns',
  13256. xlink = 'http://www.w3.org/1999/xlink',
  13257. attributeNamespace = {
  13258. href: xlink,
  13259. xlink: xmlns,
  13260. xmlns: xmlns + '/',
  13261. 'xmlns:xlink': xmlns + '/'
  13262. };
  13263. function create(tag, attributes, formatter) {
  13264. return set(document.createElementNS(svg, tag), attributes, formatter);
  13265. }
  13266. function get(node, name) {
  13267. var namespace = attributeNamespace[name],
  13268. value = namespace
  13269. ? node.getAttributeNS(namespace, name)
  13270. : node.getAttribute(name);
  13271. return value === 'null' ? null : value;
  13272. }
  13273. function set(node, attributes, formatter) {
  13274. for (var name in attributes) {
  13275. var value = attributes[name],
  13276. namespace = attributeNamespace[name];
  13277. if (typeof value === 'number' && formatter)
  13278. value = formatter.number(value);
  13279. if (namespace) {
  13280. node.setAttributeNS(namespace, name, value);
  13281. } else {
  13282. node.setAttribute(name, value);
  13283. }
  13284. }
  13285. return node;
  13286. }
  13287. return {
  13288. svg: svg,
  13289. xmlns: xmlns,
  13290. xlink: xlink,
  13291. create: create,
  13292. get: get,
  13293. set: set
  13294. };
  13295. };
  13296. var SvgStyles = Base.each({
  13297. fillColor: ['fill', 'color'],
  13298. fillRule: ['fill-rule', 'string'],
  13299. strokeColor: ['stroke', 'color'],
  13300. strokeWidth: ['stroke-width', 'number'],
  13301. strokeCap: ['stroke-linecap', 'string'],
  13302. strokeJoin: ['stroke-linejoin', 'string'],
  13303. strokeScaling: ['vector-effect', 'lookup', {
  13304. true: 'none',
  13305. false: 'non-scaling-stroke'
  13306. }, function(item, value) {
  13307. return !value
  13308. && (item instanceof PathItem
  13309. || item instanceof Shape
  13310. || item instanceof TextItem);
  13311. }],
  13312. miterLimit: ['stroke-miterlimit', 'number'],
  13313. dashArray: ['stroke-dasharray', 'array'],
  13314. dashOffset: ['stroke-dashoffset', 'number'],
  13315. fontFamily: ['font-family', 'string'],
  13316. fontWeight: ['font-weight', 'string'],
  13317. fontSize: ['font-size', 'number'],
  13318. justification: ['text-anchor', 'lookup', {
  13319. left: 'start',
  13320. center: 'middle',
  13321. right: 'end'
  13322. }],
  13323. opacity: ['opacity', 'number'],
  13324. blendMode: ['mix-blend-mode', 'style']
  13325. }, function(entry, key) {
  13326. var part = Base.capitalize(key),
  13327. lookup = entry[2];
  13328. this[key] = {
  13329. type: entry[1],
  13330. property: key,
  13331. attribute: entry[0],
  13332. toSVG: lookup,
  13333. fromSVG: lookup && Base.each(lookup, function(value, name) {
  13334. this[value] = name;
  13335. }, {}),
  13336. exportFilter: entry[3],
  13337. get: 'get' + part,
  13338. set: 'set' + part
  13339. };
  13340. }, {});
  13341. new function() {
  13342. var formatter;
  13343. function getTransform(matrix, coordinates, center) {
  13344. var attrs = new Base(),
  13345. trans = matrix.getTranslation();
  13346. if (coordinates) {
  13347. var point;
  13348. if (matrix.isInvertible()) {
  13349. matrix = matrix._shiftless();
  13350. point = matrix._inverseTransform(trans);
  13351. trans = null;
  13352. } else {
  13353. point = new Point();
  13354. }
  13355. attrs[center ? 'cx' : 'x'] = point.x;
  13356. attrs[center ? 'cy' : 'y'] = point.y;
  13357. }
  13358. if (!matrix.isIdentity()) {
  13359. var decomposed = matrix.decompose();
  13360. if (decomposed) {
  13361. var parts = [],
  13362. angle = decomposed.rotation,
  13363. scale = decomposed.scaling,
  13364. skew = decomposed.skewing;
  13365. if (trans && !trans.isZero())
  13366. parts.push('translate(' + formatter.point(trans) + ')');
  13367. if (angle)
  13368. parts.push('rotate(' + formatter.number(angle) + ')');
  13369. if (!Numerical.isZero(scale.x - 1)
  13370. || !Numerical.isZero(scale.y - 1))
  13371. parts.push('scale(' + formatter.point(scale) +')');
  13372. if (skew.x)
  13373. parts.push('skewX(' + formatter.number(skew.x) + ')');
  13374. if (skew.y)
  13375. parts.push('skewY(' + formatter.number(skew.y) + ')');
  13376. attrs.transform = parts.join(' ');
  13377. } else {
  13378. attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
  13379. }
  13380. }
  13381. return attrs;
  13382. }
  13383. function exportGroup(item, options) {
  13384. var attrs = getTransform(item._matrix),
  13385. children = item._children;
  13386. var node = SvgElement.create('g', attrs, formatter);
  13387. for (var i = 0, l = children.length; i < l; i++) {
  13388. var child = children[i];
  13389. var childNode = exportSVG(child, options);
  13390. if (childNode) {
  13391. if (child.isClipMask()) {
  13392. var clip = SvgElement.create('clipPath');
  13393. clip.appendChild(childNode);
  13394. setDefinition(child, clip, 'clip');
  13395. SvgElement.set(node, {
  13396. 'clip-path': 'url(#' + clip.id + ')'
  13397. });
  13398. } else {
  13399. node.appendChild(childNode);
  13400. }
  13401. }
  13402. }
  13403. return node;
  13404. }
  13405. function exportRaster(item, options) {
  13406. var attrs = getTransform(item._matrix, true),
  13407. size = item.getSize(),
  13408. image = item.getImage();
  13409. attrs.x -= size.width / 2;
  13410. attrs.y -= size.height / 2;
  13411. attrs.width = size.width;
  13412. attrs.height = size.height;
  13413. attrs.href = options.embedImages == false && image && image.src
  13414. || item.toDataURL();
  13415. return SvgElement.create('image', attrs, formatter);
  13416. }
  13417. function exportPath(item, options) {
  13418. var matchShapes = options.matchShapes;
  13419. if (matchShapes) {
  13420. var shape = item.toShape(false);
  13421. if (shape)
  13422. return exportShape(shape, options);
  13423. }
  13424. var segments = item._segments,
  13425. length = segments.length,
  13426. type,
  13427. attrs = getTransform(item._matrix);
  13428. if (matchShapes && length >= 2 && !item.hasHandles()) {
  13429. if (length > 2) {
  13430. type = item._closed ? 'polygon' : 'polyline';
  13431. var parts = [];
  13432. for (var i = 0; i < length; i++) {
  13433. parts.push(formatter.point(segments[i]._point));
  13434. }
  13435. attrs.points = parts.join(' ');
  13436. } else {
  13437. type = 'line';
  13438. var start = segments[0]._point,
  13439. end = segments[1]._point;
  13440. attrs.set({
  13441. x1: start.x,
  13442. y1: start.y,
  13443. x2: end.x,
  13444. y2: end.y
  13445. });
  13446. }
  13447. } else {
  13448. type = 'path';
  13449. attrs.d = item.getPathData(null, options.precision);
  13450. }
  13451. return SvgElement.create(type, attrs, formatter);
  13452. }
  13453. function exportShape(item) {
  13454. var type = item._type,
  13455. radius = item._radius,
  13456. attrs = getTransform(item._matrix, true, type !== 'rectangle');
  13457. if (type === 'rectangle') {
  13458. type = 'rect';
  13459. var size = item._size,
  13460. width = size.width,
  13461. height = size.height;
  13462. attrs.x -= width / 2;
  13463. attrs.y -= height / 2;
  13464. attrs.width = width;
  13465. attrs.height = height;
  13466. if (radius.isZero())
  13467. radius = null;
  13468. }
  13469. if (radius) {
  13470. if (type === 'circle') {
  13471. attrs.r = radius;
  13472. } else {
  13473. attrs.rx = radius.width;
  13474. attrs.ry = radius.height;
  13475. }
  13476. }
  13477. return SvgElement.create(type, attrs, formatter);
  13478. }
  13479. function exportCompoundPath(item, options) {
  13480. var attrs = getTransform(item._matrix);
  13481. var data = item.getPathData(null, options.precision);
  13482. if (data)
  13483. attrs.d = data;
  13484. return SvgElement.create('path', attrs, formatter);
  13485. }
  13486. function exportSymbolItem(item, options) {
  13487. var attrs = getTransform(item._matrix, true),
  13488. definition = item._definition,
  13489. node = getDefinition(definition, 'symbol'),
  13490. definitionItem = definition._item,
  13491. bounds = definitionItem.getStrokeBounds();
  13492. if (!node) {
  13493. node = SvgElement.create('symbol', {
  13494. viewBox: formatter.rectangle(bounds)
  13495. });
  13496. node.appendChild(exportSVG(definitionItem, options));
  13497. setDefinition(definition, node, 'symbol');
  13498. }
  13499. attrs.href = '#' + node.id;
  13500. attrs.x += bounds.x;
  13501. attrs.y += bounds.y;
  13502. attrs.width = bounds.width;
  13503. attrs.height = bounds.height;
  13504. attrs.overflow = 'visible';
  13505. return SvgElement.create('use', attrs, formatter);
  13506. }
  13507. function exportGradient(color) {
  13508. var gradientNode = getDefinition(color, 'color');
  13509. if (!gradientNode) {
  13510. var gradient = color.getGradient(),
  13511. radial = gradient._radial,
  13512. origin = color.getOrigin(),
  13513. destination = color.getDestination(),
  13514. attrs;
  13515. if (radial) {
  13516. attrs = {
  13517. cx: origin.x,
  13518. cy: origin.y,
  13519. r: origin.getDistance(destination)
  13520. };
  13521. var highlight = color.getHighlight();
  13522. if (highlight) {
  13523. attrs.fx = highlight.x;
  13524. attrs.fy = highlight.y;
  13525. }
  13526. } else {
  13527. attrs = {
  13528. x1: origin.x,
  13529. y1: origin.y,
  13530. x2: destination.x,
  13531. y2: destination.y
  13532. };
  13533. }
  13534. attrs.gradientUnits = 'userSpaceOnUse';
  13535. gradientNode = SvgElement.create((radial ? 'radial' : 'linear')
  13536. + 'Gradient', attrs, formatter);
  13537. var stops = gradient._stops;
  13538. for (var i = 0, l = stops.length; i < l; i++) {
  13539. var stop = stops[i],
  13540. stopColor = stop._color,
  13541. alpha = stopColor.getAlpha(),
  13542. offset = stop._offset;
  13543. attrs = {
  13544. offset: offset == null ? i / (l - 1) : offset
  13545. };
  13546. if (stopColor)
  13547. attrs['stop-color'] = stopColor.toCSS(true);
  13548. if (alpha < 1)
  13549. attrs['stop-opacity'] = alpha;
  13550. gradientNode.appendChild(
  13551. SvgElement.create('stop', attrs, formatter));
  13552. }
  13553. setDefinition(color, gradientNode, 'color');
  13554. }
  13555. return 'url(#' + gradientNode.id + ')';
  13556. }
  13557. function exportText(item) {
  13558. var node = SvgElement.create('text', getTransform(item._matrix, true),
  13559. formatter);
  13560. node.textContent = item._content;
  13561. return node;
  13562. }
  13563. var exporters = {
  13564. Group: exportGroup,
  13565. Layer: exportGroup,
  13566. Raster: exportRaster,
  13567. Path: exportPath,
  13568. Shape: exportShape,
  13569. CompoundPath: exportCompoundPath,
  13570. SymbolItem: exportSymbolItem,
  13571. PointText: exportText
  13572. };
  13573. function applyStyle(item, node, isRoot) {
  13574. var attrs = {},
  13575. parent = !isRoot && item.getParent(),
  13576. style = [];
  13577. if (item._name != null)
  13578. attrs.id = item._name;
  13579. Base.each(SvgStyles, function(entry) {
  13580. var get = entry.get,
  13581. type = entry.type,
  13582. value = item[get]();
  13583. if (entry.exportFilter
  13584. ? entry.exportFilter(item, value)
  13585. : !parent || !Base.equals(parent[get](), value)) {
  13586. if (type === 'color' && value != null) {
  13587. var alpha = value.getAlpha();
  13588. if (alpha < 1)
  13589. attrs[entry.attribute + '-opacity'] = alpha;
  13590. }
  13591. if (type === 'style') {
  13592. style.push(entry.attribute + ': ' + value);
  13593. } else {
  13594. attrs[entry.attribute] = value == null ? 'none'
  13595. : type === 'color' ? value.gradient
  13596. ? exportGradient(value, item)
  13597. : value.toCSS(true)
  13598. : type === 'array' ? value.join(',')
  13599. : type === 'lookup' ? entry.toSVG[value]
  13600. : value;
  13601. }
  13602. }
  13603. });
  13604. if (style.length)
  13605. attrs.style = style.join(';');
  13606. if (attrs.opacity === 1)
  13607. delete attrs.opacity;
  13608. if (!item._visible)
  13609. attrs.visibility = 'hidden';
  13610. return SvgElement.set(node, attrs, formatter);
  13611. }
  13612. var definitions;
  13613. function getDefinition(item, type) {
  13614. if (!definitions)
  13615. definitions = { ids: {}, svgs: {} };
  13616. return item && definitions.svgs[type + '-'
  13617. + (item._id || item.__id || (item.__id = UID.get('svg')))];
  13618. }
  13619. function setDefinition(item, node, type) {
  13620. if (!definitions)
  13621. getDefinition();
  13622. var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
  13623. node.id = type + '-' + typeId;
  13624. definitions.svgs[type + '-' + (item._id || item.__id)] = node;
  13625. }
  13626. function exportDefinitions(node, options) {
  13627. var svg = node,
  13628. defs = null;
  13629. if (definitions) {
  13630. svg = node.nodeName.toLowerCase() === 'svg' && node;
  13631. for (var i in definitions.svgs) {
  13632. if (!defs) {
  13633. if (!svg) {
  13634. svg = SvgElement.create('svg');
  13635. svg.appendChild(node);
  13636. }
  13637. defs = svg.insertBefore(SvgElement.create('defs'),
  13638. svg.firstChild);
  13639. }
  13640. defs.appendChild(definitions.svgs[i]);
  13641. }
  13642. definitions = null;
  13643. }
  13644. return options.asString
  13645. ? new self.XMLSerializer().serializeToString(svg)
  13646. : svg;
  13647. }
  13648. function exportSVG(item, options, isRoot) {
  13649. var exporter = exporters[item._class],
  13650. node = exporter && exporter(item, options);
  13651. if (node) {
  13652. var onExport = options.onExport;
  13653. if (onExport)
  13654. node = onExport(item, node, options) || node;
  13655. var data = JSON.stringify(item._data);
  13656. if (data && data !== '{}' && data !== 'null')
  13657. node.setAttribute('data-paper-data', data);
  13658. }
  13659. return node && applyStyle(item, node, isRoot);
  13660. }
  13661. function setOptions(options) {
  13662. if (!options)
  13663. options = {};
  13664. formatter = new Formatter(options.precision);
  13665. return options;
  13666. }
  13667. Item.inject({
  13668. exportSVG: function(options) {
  13669. options = setOptions(options);
  13670. return exportDefinitions(exportSVG(this, options, true), options);
  13671. }
  13672. });
  13673. Project.inject({
  13674. exportSVG: function(options) {
  13675. options = setOptions(options);
  13676. var children = this._children,
  13677. view = this.getView(),
  13678. bounds = Base.pick(options.bounds, 'view'),
  13679. mx = options.matrix || bounds === 'view' && view._matrix,
  13680. matrix = mx && Matrix.read([mx]),
  13681. rect = bounds === 'view'
  13682. ? new Rectangle([0, 0], view.getViewSize())
  13683. : bounds === 'content'
  13684. ? Item._getBounds(children, matrix, { stroke: true })
  13685. .rect
  13686. : Rectangle.read([bounds], 0, { readNull: true }),
  13687. attrs = {
  13688. version: '1.1',
  13689. xmlns: SvgElement.svg,
  13690. 'xmlns:xlink': SvgElement.xlink,
  13691. };
  13692. if (rect) {
  13693. attrs.width = rect.width;
  13694. attrs.height = rect.height;
  13695. if (rect.x || rect.x === 0 || rect.y || rect.y === 0)
  13696. attrs.viewBox = formatter.rectangle(rect);
  13697. }
  13698. var node = SvgElement.create('svg', attrs, formatter),
  13699. parent = node;
  13700. if (matrix && !matrix.isIdentity()) {
  13701. parent = node.appendChild(SvgElement.create('g',
  13702. getTransform(matrix), formatter));
  13703. }
  13704. for (var i = 0, l = children.length; i < l; i++) {
  13705. parent.appendChild(exportSVG(children[i], options, true));
  13706. }
  13707. return exportDefinitions(node, options);
  13708. }
  13709. });
  13710. };
  13711. new function() {
  13712. var definitions = {},
  13713. rootSize;
  13714. function getValue(node, name, isString, allowNull, allowPercent,
  13715. defaultValue) {
  13716. var value = SvgElement.get(node, name) || defaultValue,
  13717. res = value == null
  13718. ? allowNull
  13719. ? null
  13720. : isString ? '' : 0
  13721. : isString
  13722. ? value
  13723. : parseFloat(value);
  13724. return /%\s*$/.test(value)
  13725. ? (res / 100) * (allowPercent ? 1
  13726. : rootSize[/x|^width/.test(name) ? 'width' : 'height'])
  13727. : res;
  13728. }
  13729. function getPoint(node, x, y, allowNull, allowPercent, defaultX, defaultY) {
  13730. x = getValue(node, x || 'x', false, allowNull, allowPercent, defaultX);
  13731. y = getValue(node, y || 'y', false, allowNull, allowPercent, defaultY);
  13732. return allowNull && (x == null || y == null) ? null
  13733. : new Point(x, y);
  13734. }
  13735. function getSize(node, w, h, allowNull, allowPercent) {
  13736. w = getValue(node, w || 'width', false, allowNull, allowPercent);
  13737. h = getValue(node, h || 'height', false, allowNull, allowPercent);
  13738. return allowNull && (w == null || h == null) ? null
  13739. : new Size(w, h);
  13740. }
  13741. function convertValue(value, type, lookup) {
  13742. return value === 'none' ? null
  13743. : type === 'number' ? parseFloat(value)
  13744. : type === 'array' ?
  13745. value ? value.split(/[\s,]+/g).map(parseFloat) : []
  13746. : type === 'color' ? getDefinition(value) || value
  13747. : type === 'lookup' ? lookup[value]
  13748. : value;
  13749. }
  13750. function importGroup(node, type, options, isRoot) {
  13751. var nodes = node.childNodes,
  13752. isClip = type === 'clippath',
  13753. isDefs = type === 'defs',
  13754. item = new Group(),
  13755. project = item._project,
  13756. currentStyle = project._currentStyle,
  13757. children = [];
  13758. if (!isClip && !isDefs) {
  13759. item = applyAttributes(item, node, isRoot);
  13760. project._currentStyle = item._style.clone();
  13761. }
  13762. if (isRoot) {
  13763. var defs = node.querySelectorAll('defs');
  13764. for (var i = 0, l = defs.length; i < l; i++) {
  13765. importNode(defs[i], options, false);
  13766. }
  13767. }
  13768. for (var i = 0, l = nodes.length; i < l; i++) {
  13769. var childNode = nodes[i],
  13770. child;
  13771. if (childNode.nodeType === 1
  13772. && !/^defs$/i.test(childNode.nodeName)
  13773. && (child = importNode(childNode, options, false))
  13774. && !(child instanceof SymbolDefinition))
  13775. children.push(child);
  13776. }
  13777. item.addChildren(children);
  13778. if (isClip)
  13779. item = applyAttributes(item.reduce(), node, isRoot);
  13780. project._currentStyle = currentStyle;
  13781. if (isClip || isDefs) {
  13782. item.remove();
  13783. item = null;
  13784. }
  13785. return item;
  13786. }
  13787. function importPoly(node, type) {
  13788. var coords = node.getAttribute('points').match(
  13789. /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),
  13790. points = [];
  13791. for (var i = 0, l = coords.length; i < l; i += 2)
  13792. points.push(new Point(
  13793. parseFloat(coords[i]),
  13794. parseFloat(coords[i + 1])));
  13795. var path = new Path(points);
  13796. if (type === 'polygon')
  13797. path.closePath();
  13798. return path;
  13799. }
  13800. function importPath(node) {
  13801. return PathItem.create(node.getAttribute('d'));
  13802. }
  13803. function importGradient(node, type) {
  13804. var id = (getValue(node, 'href', true) || '').substring(1),
  13805. radial = type === 'radialgradient',
  13806. gradient;
  13807. if (id) {
  13808. gradient = definitions[id].getGradient();
  13809. if (gradient._radial ^ radial) {
  13810. gradient = gradient.clone();
  13811. gradient._radial = radial;
  13812. }
  13813. } else {
  13814. var nodes = node.childNodes,
  13815. stops = [];
  13816. for (var i = 0, l = nodes.length; i < l; i++) {
  13817. var child = nodes[i];
  13818. if (child.nodeType === 1)
  13819. stops.push(applyAttributes(new GradientStop(), child));
  13820. }
  13821. gradient = new Gradient(stops, radial);
  13822. }
  13823. var origin, destination, highlight,
  13824. scaleToBounds = getValue(node, 'gradientUnits', true) !==
  13825. 'userSpaceOnUse';
  13826. if (radial) {
  13827. origin = getPoint(node, 'cx', 'cy', false, scaleToBounds,
  13828. '50%', '50%');
  13829. destination = origin.add(
  13830. getValue(node, 'r', false, false, scaleToBounds, '50%'), 0);
  13831. highlight = getPoint(node, 'fx', 'fy', true, scaleToBounds);
  13832. } else {
  13833. origin = getPoint(node, 'x1', 'y1', false, scaleToBounds,
  13834. '0%', '0%');
  13835. destination = getPoint(node, 'x2', 'y2', false, scaleToBounds,
  13836. '100%', '0%');
  13837. }
  13838. var color = applyAttributes(
  13839. new Color(gradient, origin, destination, highlight), node);
  13840. color._scaleToBounds = scaleToBounds;
  13841. return null;
  13842. }
  13843. var importers = {
  13844. '#document': function (node, type, options, isRoot) {
  13845. var nodes = node.childNodes;
  13846. for (var i = 0, l = nodes.length; i < l; i++) {
  13847. var child = nodes[i];
  13848. if (child.nodeType === 1)
  13849. return importNode(child, options, isRoot);
  13850. }
  13851. },
  13852. g: importGroup,
  13853. svg: importGroup,
  13854. clippath: importGroup,
  13855. polygon: importPoly,
  13856. polyline: importPoly,
  13857. path: importPath,
  13858. lineargradient: importGradient,
  13859. radialgradient: importGradient,
  13860. image: function (node) {
  13861. var raster = new Raster(getValue(node, 'href', true));
  13862. raster.on('load', function() {
  13863. var size = getSize(node);
  13864. this.setSize(size);
  13865. var center = getPoint(node).add(size.divide(2));
  13866. this._matrix.append(new Matrix().translate(center));
  13867. });
  13868. return raster;
  13869. },
  13870. symbol: function(node, type, options, isRoot) {
  13871. return new SymbolDefinition(
  13872. importGroup(node, type, options, isRoot), true);
  13873. },
  13874. defs: importGroup,
  13875. use: function(node) {
  13876. var id = (getValue(node, 'href', true) || '').substring(1),
  13877. definition = definitions[id],
  13878. point = getPoint(node);
  13879. return definition
  13880. ? definition instanceof SymbolDefinition
  13881. ? definition.place(point)
  13882. : definition.clone().translate(point)
  13883. : null;
  13884. },
  13885. circle: function(node) {
  13886. return new Shape.Circle(
  13887. getPoint(node, 'cx', 'cy'),
  13888. getValue(node, 'r'));
  13889. },
  13890. ellipse: function(node) {
  13891. return new Shape.Ellipse({
  13892. center: getPoint(node, 'cx', 'cy'),
  13893. radius: getSize(node, 'rx', 'ry')
  13894. });
  13895. },
  13896. rect: function(node) {
  13897. return new Shape.Rectangle(new Rectangle(
  13898. getPoint(node),
  13899. getSize(node)
  13900. ), getSize(node, 'rx', 'ry'));
  13901. },
  13902. line: function(node) {
  13903. return new Path.Line(
  13904. getPoint(node, 'x1', 'y1'),
  13905. getPoint(node, 'x2', 'y2'));
  13906. },
  13907. text: function(node) {
  13908. var text = new PointText(getPoint(node).add(
  13909. getPoint(node, 'dx', 'dy')));
  13910. text.setContent(node.textContent.trim() || '');
  13911. return text;
  13912. },
  13913. switch: importGroup
  13914. };
  13915. function applyTransform(item, value, name, node) {
  13916. if (item.transform) {
  13917. var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
  13918. matrix = new Matrix();
  13919. for (var i = 0, l = transforms.length; i < l; i++) {
  13920. var transform = transforms[i];
  13921. if (!transform)
  13922. break;
  13923. var parts = transform.split(/\(\s*/),
  13924. command = parts[0],
  13925. v = parts[1].split(/[\s,]+/g);
  13926. for (var j = 0, m = v.length; j < m; j++)
  13927. v[j] = parseFloat(v[j]);
  13928. switch (command) {
  13929. case 'matrix':
  13930. matrix.append(
  13931. new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
  13932. break;
  13933. case 'rotate':
  13934. matrix.rotate(v[0], v[1] || 0, v[2] || 0);
  13935. break;
  13936. case 'translate':
  13937. matrix.translate(v[0], v[1] || 0);
  13938. break;
  13939. case 'scale':
  13940. matrix.scale(v);
  13941. break;
  13942. case 'skewX':
  13943. matrix.skew(v[0], 0);
  13944. break;
  13945. case 'skewY':
  13946. matrix.skew(0, v[0]);
  13947. break;
  13948. }
  13949. }
  13950. item.transform(matrix);
  13951. }
  13952. }
  13953. function applyOpacity(item, value, name) {
  13954. var key = name === 'fill-opacity' ? 'getFillColor' : 'getStrokeColor',
  13955. color = item[key] && item[key]();
  13956. if (color)
  13957. color.setAlpha(parseFloat(value));
  13958. }
  13959. var attributes = Base.set(Base.each(SvgStyles, function(entry) {
  13960. this[entry.attribute] = function(item, value) {
  13961. if (item[entry.set]) {
  13962. item[entry.set](convertValue(value, entry.type, entry.fromSVG));
  13963. if (entry.type === 'color') {
  13964. var color = item[entry.get]();
  13965. if (color) {
  13966. if (color._scaleToBounds) {
  13967. var bounds = item.getBounds();
  13968. color.transform(new Matrix()
  13969. .translate(bounds.getPoint())
  13970. .scale(bounds.getSize()));
  13971. }
  13972. }
  13973. }
  13974. }
  13975. };
  13976. }, {}), {
  13977. id: function(item, value) {
  13978. definitions[value] = item;
  13979. if (item.setName)
  13980. item.setName(value);
  13981. },
  13982. 'clip-path': function(item, value) {
  13983. var clip = getDefinition(value);
  13984. if (clip) {
  13985. clip = clip.clone();
  13986. clip.setClipMask(true);
  13987. if (item instanceof Group) {
  13988. item.insertChild(0, clip);
  13989. } else {
  13990. return new Group(clip, item);
  13991. }
  13992. }
  13993. },
  13994. gradientTransform: applyTransform,
  13995. transform: applyTransform,
  13996. 'fill-opacity': applyOpacity,
  13997. 'stroke-opacity': applyOpacity,
  13998. visibility: function(item, value) {
  13999. if (item.setVisible)
  14000. item.setVisible(value === 'visible');
  14001. },
  14002. display: function(item, value) {
  14003. if (item.setVisible)
  14004. item.setVisible(value !== null);
  14005. },
  14006. 'stop-color': function(item, value) {
  14007. if (item.setColor)
  14008. item.setColor(value);
  14009. },
  14010. 'stop-opacity': function(item, value) {
  14011. if (item._color)
  14012. item._color.setAlpha(parseFloat(value));
  14013. },
  14014. offset: function(item, value) {
  14015. if (item.setOffset) {
  14016. var percent = value.match(/(.*)%$/);
  14017. item.setOffset(percent ? percent[1] / 100 : parseFloat(value));
  14018. }
  14019. },
  14020. viewBox: function(item, value, name, node, styles) {
  14021. var rect = new Rectangle(convertValue(value, 'array')),
  14022. size = getSize(node, null, null, true),
  14023. group,
  14024. matrix;
  14025. if (item instanceof Group) {
  14026. var scale = size ? size.divide(rect.getSize()) : 1,
  14027. matrix = new Matrix().scale(scale)
  14028. .translate(rect.getPoint().negate());
  14029. group = item;
  14030. } else if (item instanceof SymbolDefinition) {
  14031. if (size)
  14032. rect.setSize(size);
  14033. group = item._item;
  14034. }
  14035. if (group) {
  14036. if (getAttribute(node, 'overflow', styles) !== 'visible') {
  14037. var clip = new Shape.Rectangle(rect);
  14038. clip.setClipMask(true);
  14039. group.addChild(clip);
  14040. }
  14041. if (matrix)
  14042. group.transform(matrix);
  14043. }
  14044. }
  14045. });
  14046. function getAttribute(node, name, styles) {
  14047. var attr = node.attributes[name],
  14048. value = attr && attr.value;
  14049. if (!value && node.style) {
  14050. var style = Base.camelize(name);
  14051. value = node.style[style];
  14052. if (!value && styles.node[style] !== styles.parent[style])
  14053. value = styles.node[style];
  14054. }
  14055. return !value ? undefined
  14056. : value === 'none' ? null
  14057. : value;
  14058. }
  14059. function applyAttributes(item, node, isRoot) {
  14060. var parent = node.parentNode,
  14061. styles = {
  14062. node: DomElement.getStyles(node) || {},
  14063. parent: !isRoot && !/^defs$/i.test(parent.tagName)
  14064. && DomElement.getStyles(parent) || {}
  14065. };
  14066. Base.each(attributes, function(apply, name) {
  14067. var value = getAttribute(node, name, styles);
  14068. item = value !== undefined
  14069. && apply(item, value, name, node, styles) || item;
  14070. });
  14071. return item;
  14072. }
  14073. function getDefinition(value) {
  14074. var match = value && value.match(/\((?:["'#]*)([^"')]+)/),
  14075. name = match && match[1],
  14076. res = name && definitions[window
  14077. ? name.replace(window.location.href.split('#')[0] + '#', '')
  14078. : name];
  14079. if (res && res._scaleToBounds) {
  14080. res = res.clone();
  14081. res._scaleToBounds = true;
  14082. }
  14083. return res;
  14084. }
  14085. function importNode(node, options, isRoot) {
  14086. var type = node.nodeName.toLowerCase(),
  14087. isElement = type !== '#document',
  14088. body = document.body,
  14089. container,
  14090. parent,
  14091. next;
  14092. if (isRoot && isElement) {
  14093. rootSize = paper.getView().getSize();
  14094. rootSize = getSize(node, null, null, true) || rootSize;
  14095. container = SvgElement.create('svg', {
  14096. style: 'stroke-width: 1px; stroke-miterlimit: 10'
  14097. });
  14098. parent = node.parentNode;
  14099. next = node.nextSibling;
  14100. container.appendChild(node);
  14101. body.appendChild(container);
  14102. }
  14103. var settings = paper.settings,
  14104. applyMatrix = settings.applyMatrix,
  14105. insertItems = settings.insertItems;
  14106. settings.applyMatrix = false;
  14107. settings.insertItems = false;
  14108. var importer = importers[type],
  14109. item = importer && importer(node, type, options, isRoot) || null;
  14110. settings.insertItems = insertItems;
  14111. settings.applyMatrix = applyMatrix;
  14112. if (item) {
  14113. if (isElement && !(item instanceof Group))
  14114. item = applyAttributes(item, node, isRoot);
  14115. var onImport = options.onImport,
  14116. data = isElement && node.getAttribute('data-paper-data');
  14117. if (onImport)
  14118. item = onImport(node, item, options) || item;
  14119. if (options.expandShapes && item instanceof Shape) {
  14120. item.remove();
  14121. item = item.toPath();
  14122. }
  14123. if (data)
  14124. item._data = JSON.parse(data);
  14125. }
  14126. if (container) {
  14127. body.removeChild(container);
  14128. if (parent) {
  14129. if (next) {
  14130. parent.insertBefore(node, next);
  14131. } else {
  14132. parent.appendChild(node);
  14133. }
  14134. }
  14135. }
  14136. if (isRoot) {
  14137. definitions = {};
  14138. if (item && Base.pick(options.applyMatrix, applyMatrix))
  14139. item.matrix.apply(true, true);
  14140. }
  14141. return item;
  14142. }
  14143. function importSVG(source, options, owner) {
  14144. if (!source)
  14145. return null;
  14146. options = typeof options === 'function' ? { onLoad: options }
  14147. : options || {};
  14148. var scope = paper,
  14149. item = null;
  14150. function onLoad(svg) {
  14151. try {
  14152. var node = typeof svg === 'object'
  14153. ? svg
  14154. : new self.DOMParser().parseFromString(
  14155. svg.trim(),
  14156. 'image/svg+xml'
  14157. );
  14158. if (!node.nodeName) {
  14159. node = null;
  14160. throw new Error('Unsupported SVG source: ' + source);
  14161. }
  14162. paper = scope;
  14163. item = importNode(node, options, true);
  14164. if (!options || options.insert !== false) {
  14165. owner._insertItem(undefined, item);
  14166. }
  14167. var onLoad = options.onLoad;
  14168. if (onLoad)
  14169. onLoad(item, svg);
  14170. } catch (e) {
  14171. onError(e);
  14172. }
  14173. }
  14174. function onError(message, status) {
  14175. var onError = options.onError;
  14176. if (onError) {
  14177. onError(message, status);
  14178. } else {
  14179. throw new Error(message);
  14180. }
  14181. }
  14182. if (typeof source === 'string' && !/^[\s\S]*</.test(source)) {
  14183. var node = document.getElementById(source);
  14184. if (node) {
  14185. onLoad(node);
  14186. } else {
  14187. Http.request({
  14188. url: source,
  14189. async: true,
  14190. onLoad: onLoad,
  14191. onError: onError
  14192. });
  14193. }
  14194. } else if (typeof File !== 'undefined' && source instanceof File) {
  14195. var reader = new FileReader();
  14196. reader.onload = function() {
  14197. onLoad(reader.result);
  14198. };
  14199. reader.onerror = function() {
  14200. onError(reader.error);
  14201. };
  14202. return reader.readAsText(source);
  14203. } else {
  14204. onLoad(source);
  14205. }
  14206. return item;
  14207. }
  14208. Item.inject({
  14209. importSVG: function(node, options) {
  14210. return importSVG(node, options, this);
  14211. }
  14212. });
  14213. Project.inject({
  14214. importSVG: function(node, options) {
  14215. this.activate();
  14216. return importSVG(node, options, this);
  14217. }
  14218. });
  14219. };
  14220. Base.exports.PaperScript = function() {
  14221. var global = this,
  14222. acorn = global.acorn;
  14223. if (!acorn && typeof require !== 'undefined') {
  14224. try { acorn = require('acorn'); } catch(e) {}
  14225. }
  14226. if (!acorn) {
  14227. var exports, module;
  14228. acorn = exports = module = {};
  14229. (function(root, mod) {
  14230. if (typeof exports == "object" && typeof module == "object") return mod(exports);
  14231. if (typeof define == "function" && define.amd) return define(["exports"], mod);
  14232. mod(root.acorn || (root.acorn = {}));
  14233. })(this, function(exports) {
  14234. "use strict";
  14235. exports.version = "0.5.0";
  14236. var options, input, inputLen, sourceFile;
  14237. exports.parse = function(inpt, opts) {
  14238. input = String(inpt); inputLen = input.length;
  14239. setOptions(opts);
  14240. initTokenState();
  14241. return parseTopLevel(options.program);
  14242. };
  14243. var defaultOptions = exports.defaultOptions = {
  14244. ecmaVersion: 5,
  14245. strictSemicolons: false,
  14246. allowTrailingCommas: true,
  14247. forbidReserved: false,
  14248. allowReturnOutsideFunction: false,
  14249. locations: false,
  14250. onComment: null,
  14251. ranges: false,
  14252. program: null,
  14253. sourceFile: null,
  14254. directSourceFile: null
  14255. };
  14256. function setOptions(opts) {
  14257. options = opts || {};
  14258. for (var opt in defaultOptions) if (!Object.prototype.hasOwnProperty.call(options, opt))
  14259. options[opt] = defaultOptions[opt];
  14260. sourceFile = options.sourceFile || null;
  14261. }
  14262. var getLineInfo = exports.getLineInfo = function(input, offset) {
  14263. for (var line = 1, cur = 0;;) {
  14264. lineBreak.lastIndex = cur;
  14265. var match = lineBreak.exec(input);
  14266. if (match && match.index < offset) {
  14267. ++line;
  14268. cur = match.index + match[0].length;
  14269. } else break;
  14270. }
  14271. return {line: line, column: offset - cur};
  14272. };
  14273. exports.tokenize = function(inpt, opts) {
  14274. input = String(inpt); inputLen = input.length;
  14275. setOptions(opts);
  14276. initTokenState();
  14277. var t = {};
  14278. function getToken(forceRegexp) {
  14279. lastEnd = tokEnd;
  14280. readToken(forceRegexp);
  14281. t.start = tokStart; t.end = tokEnd;
  14282. t.startLoc = tokStartLoc; t.endLoc = tokEndLoc;
  14283. t.type = tokType; t.value = tokVal;
  14284. return t;
  14285. }
  14286. getToken.jumpTo = function(pos, reAllowed) {
  14287. tokPos = pos;
  14288. if (options.locations) {
  14289. tokCurLine = 1;
  14290. tokLineStart = lineBreak.lastIndex = 0;
  14291. var match;
  14292. while ((match = lineBreak.exec(input)) && match.index < pos) {
  14293. ++tokCurLine;
  14294. tokLineStart = match.index + match[0].length;
  14295. }
  14296. }
  14297. tokRegexpAllowed = reAllowed;
  14298. skipSpace();
  14299. };
  14300. return getToken;
  14301. };
  14302. var tokPos;
  14303. var tokStart, tokEnd;
  14304. var tokStartLoc, tokEndLoc;
  14305. var tokType, tokVal;
  14306. var tokRegexpAllowed;
  14307. var tokCurLine, tokLineStart;
  14308. var lastStart, lastEnd, lastEndLoc;
  14309. var inFunction, labels, strict;
  14310. function raise(pos, message) {
  14311. var loc = getLineInfo(input, pos);
  14312. message += " (" + loc.line + ":" + loc.column + ")";
  14313. var err = new SyntaxError(message);
  14314. err.pos = pos; err.loc = loc; err.raisedAt = tokPos;
  14315. throw err;
  14316. }
  14317. var empty = [];
  14318. var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"};
  14319. var _name = {type: "name"}, _eof = {type: "eof"};
  14320. var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"};
  14321. var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"};
  14322. var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true};
  14323. var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"};
  14324. var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"};
  14325. var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"};
  14326. var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true};
  14327. var _this = {keyword: "this"};
  14328. var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true};
  14329. var _false = {keyword: "false", atomValue: false};
  14330. var _in = {keyword: "in", binop: 7, beforeExpr: true};
  14331. var keywordTypes = {"break": _break, "case": _case, "catch": _catch,
  14332. "continue": _continue, "debugger": _debugger, "default": _default,
  14333. "do": _do, "else": _else, "finally": _finally, "for": _for,
  14334. "function": _function, "if": _if, "return": _return, "switch": _switch,
  14335. "throw": _throw, "try": _try, "var": _var, "while": _while, "with": _with,
  14336. "null": _null, "true": _true, "false": _false, "new": _new, "in": _in,
  14337. "instanceof": {keyword: "instanceof", binop: 7, beforeExpr: true}, "this": _this,
  14338. "typeof": {keyword: "typeof", prefix: true, beforeExpr: true},
  14339. "void": {keyword: "void", prefix: true, beforeExpr: true},
  14340. "delete": {keyword: "delete", prefix: true, beforeExpr: true}};
  14341. var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true};
  14342. var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"};
  14343. var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true};
  14344. var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true};
  14345. var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true};
  14346. var _assign = {isAssign: true, beforeExpr: true};
  14347. var _incDec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true};
  14348. var _logicalOR = {binop: 1, beforeExpr: true};
  14349. var _logicalAND = {binop: 2, beforeExpr: true};
  14350. var _bitwiseOR = {binop: 3, beforeExpr: true};
  14351. var _bitwiseXOR = {binop: 4, beforeExpr: true};
  14352. var _bitwiseAND = {binop: 5, beforeExpr: true};
  14353. var _equality = {binop: 6, beforeExpr: true};
  14354. var _relational = {binop: 7, beforeExpr: true};
  14355. var _bitShift = {binop: 8, beforeExpr: true};
  14356. var _plusMin = {binop: 9, prefix: true, beforeExpr: true};
  14357. var _multiplyModulo = {binop: 10, beforeExpr: true};
  14358. exports.tokTypes = {bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR,
  14359. parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon,
  14360. dot: _dot, question: _question, slash: _slash, eq: _eq, name: _name, eof: _eof,
  14361. num: _num, regexp: _regexp, string: _string};
  14362. for (var kw in keywordTypes) exports.tokTypes["_" + kw] = keywordTypes[kw];
  14363. function makePredicate(words) {
  14364. words = words.split(" ");
  14365. var f = "", cats = [];
  14366. out: for (var i = 0; i < words.length; ++i) {
  14367. for (var j = 0; j < cats.length; ++j)
  14368. if (cats[j][0].length == words[i].length) {
  14369. cats[j].push(words[i]);
  14370. continue out;
  14371. }
  14372. cats.push([words[i]]);
  14373. }
  14374. function compareTo(arr) {
  14375. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  14376. f += "switch(str){";
  14377. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  14378. f += "return true}return false;";
  14379. }
  14380. if (cats.length > 3) {
  14381. cats.sort(function(a, b) {return b.length - a.length;});
  14382. f += "switch(str.length){";
  14383. for (var i = 0; i < cats.length; ++i) {
  14384. var cat = cats[i];
  14385. f += "case " + cat[0].length + ":";
  14386. compareTo(cat);
  14387. }
  14388. f += "}";
  14389. } else {
  14390. compareTo(words);
  14391. }
  14392. return new Function("str", f);
  14393. }
  14394. var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");
  14395. var isReservedWord5 = makePredicate("class enum extends super const export import");
  14396. var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield");
  14397. var isStrictBadIdWord = makePredicate("eval arguments");
  14398. var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this");
  14399. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  14400. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd
  14401. var nonASCIIidentifierChars = "\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  14402. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  14403. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  14404. var newline = /[\n\r\u2028\u2029]/;
  14405. var lineBreak = /\r\n|[\n\r\u2028\u2029]/g;
  14406. var isIdentifierStart = exports.isIdentifierStart = function(code) {
  14407. if (code < 65) return code === 36;
  14408. if (code < 91) return true;
  14409. if (code < 97) return code === 95;
  14410. if (code < 123)return true;
  14411. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  14412. };
  14413. var isIdentifierChar = exports.isIdentifierChar = function(code) {
  14414. if (code < 48) return code === 36;
  14415. if (code < 58) return true;
  14416. if (code < 65) return false;
  14417. if (code < 91) return true;
  14418. if (code < 97) return code === 95;
  14419. if (code < 123)return true;
  14420. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  14421. };
  14422. function line_loc_t() {
  14423. this.line = tokCurLine;
  14424. this.column = tokPos - tokLineStart;
  14425. }
  14426. function initTokenState() {
  14427. tokCurLine = 1;
  14428. tokPos = tokLineStart = 0;
  14429. tokRegexpAllowed = true;
  14430. skipSpace();
  14431. }
  14432. function finishToken(type, val) {
  14433. tokEnd = tokPos;
  14434. if (options.locations) tokEndLoc = new line_loc_t;
  14435. tokType = type;
  14436. skipSpace();
  14437. tokVal = val;
  14438. tokRegexpAllowed = type.beforeExpr;
  14439. }
  14440. function skipBlockComment() {
  14441. var startLoc = options.onComment && options.locations && new line_loc_t;
  14442. var start = tokPos, end = input.indexOf("*/", tokPos += 2);
  14443. if (end === -1) raise(tokPos - 2, "Unterminated comment");
  14444. tokPos = end + 2;
  14445. if (options.locations) {
  14446. lineBreak.lastIndex = start;
  14447. var match;
  14448. while ((match = lineBreak.exec(input)) && match.index < tokPos) {
  14449. ++tokCurLine;
  14450. tokLineStart = match.index + match[0].length;
  14451. }
  14452. }
  14453. if (options.onComment)
  14454. options.onComment(true, input.slice(start + 2, end), start, tokPos,
  14455. startLoc, options.locations && new line_loc_t);
  14456. }
  14457. function skipLineComment() {
  14458. var start = tokPos;
  14459. var startLoc = options.onComment && options.locations && new line_loc_t;
  14460. var ch = input.charCodeAt(tokPos+=2);
  14461. while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
  14462. ++tokPos;
  14463. ch = input.charCodeAt(tokPos);
  14464. }
  14465. if (options.onComment)
  14466. options.onComment(false, input.slice(start + 2, tokPos), start, tokPos,
  14467. startLoc, options.locations && new line_loc_t);
  14468. }
  14469. function skipSpace() {
  14470. while (tokPos < inputLen) {
  14471. var ch = input.charCodeAt(tokPos);
  14472. if (ch === 32) {
  14473. ++tokPos;
  14474. } else if (ch === 13) {
  14475. ++tokPos;
  14476. var next = input.charCodeAt(tokPos);
  14477. if (next === 10) {
  14478. ++tokPos;
  14479. }
  14480. if (options.locations) {
  14481. ++tokCurLine;
  14482. tokLineStart = tokPos;
  14483. }
  14484. } else if (ch === 10 || ch === 8232 || ch === 8233) {
  14485. ++tokPos;
  14486. if (options.locations) {
  14487. ++tokCurLine;
  14488. tokLineStart = tokPos;
  14489. }
  14490. } else if (ch > 8 && ch < 14) {
  14491. ++tokPos;
  14492. } else if (ch === 47) {
  14493. var next = input.charCodeAt(tokPos + 1);
  14494. if (next === 42) {
  14495. skipBlockComment();
  14496. } else if (next === 47) {
  14497. skipLineComment();
  14498. } else break;
  14499. } else if (ch === 160) {
  14500. ++tokPos;
  14501. } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  14502. ++tokPos;
  14503. } else {
  14504. break;
  14505. }
  14506. }
  14507. }
  14508. function readToken_dot() {
  14509. var next = input.charCodeAt(tokPos + 1);
  14510. if (next >= 48 && next <= 57) return readNumber(true);
  14511. ++tokPos;
  14512. return finishToken(_dot);
  14513. }
  14514. function readToken_slash() {
  14515. var next = input.charCodeAt(tokPos + 1);
  14516. if (tokRegexpAllowed) {++tokPos; return readRegexp();}
  14517. if (next === 61) return finishOp(_assign, 2);
  14518. return finishOp(_slash, 1);
  14519. }
  14520. function readToken_mult_modulo() {
  14521. var next = input.charCodeAt(tokPos + 1);
  14522. if (next === 61) return finishOp(_assign, 2);
  14523. return finishOp(_multiplyModulo, 1);
  14524. }
  14525. function readToken_pipe_amp(code) {
  14526. var next = input.charCodeAt(tokPos + 1);
  14527. if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2);
  14528. if (next === 61) return finishOp(_assign, 2);
  14529. return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1);
  14530. }
  14531. function readToken_caret() {
  14532. var next = input.charCodeAt(tokPos + 1);
  14533. if (next === 61) return finishOp(_assign, 2);
  14534. return finishOp(_bitwiseXOR, 1);
  14535. }
  14536. function readToken_plus_min(code) {
  14537. var next = input.charCodeAt(tokPos + 1);
  14538. if (next === code) {
  14539. if (next == 45 && input.charCodeAt(tokPos + 2) == 62 &&
  14540. newline.test(input.slice(lastEnd, tokPos))) {
  14541. tokPos += 3;
  14542. skipLineComment();
  14543. skipSpace();
  14544. return readToken();
  14545. }
  14546. return finishOp(_incDec, 2);
  14547. }
  14548. if (next === 61) return finishOp(_assign, 2);
  14549. return finishOp(_plusMin, 1);
  14550. }
  14551. function readToken_lt_gt(code) {
  14552. var next = input.charCodeAt(tokPos + 1);
  14553. var size = 1;
  14554. if (next === code) {
  14555. size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2;
  14556. if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1);
  14557. return finishOp(_bitShift, size);
  14558. }
  14559. if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 &&
  14560. input.charCodeAt(tokPos + 3) == 45) {
  14561. tokPos += 4;
  14562. skipLineComment();
  14563. skipSpace();
  14564. return readToken();
  14565. }
  14566. if (next === 61)
  14567. size = input.charCodeAt(tokPos + 2) === 61 ? 3 : 2;
  14568. return finishOp(_relational, size);
  14569. }
  14570. function readToken_eq_excl(code) {
  14571. var next = input.charCodeAt(tokPos + 1);
  14572. if (next === 61) return finishOp(_equality, input.charCodeAt(tokPos + 2) === 61 ? 3 : 2);
  14573. return finishOp(code === 61 ? _eq : _prefix, 1);
  14574. }
  14575. function getTokenFromCode(code) {
  14576. switch(code) {
  14577. case 46:
  14578. return readToken_dot();
  14579. case 40: ++tokPos; return finishToken(_parenL);
  14580. case 41: ++tokPos; return finishToken(_parenR);
  14581. case 59: ++tokPos; return finishToken(_semi);
  14582. case 44: ++tokPos; return finishToken(_comma);
  14583. case 91: ++tokPos; return finishToken(_bracketL);
  14584. case 93: ++tokPos; return finishToken(_bracketR);
  14585. case 123: ++tokPos; return finishToken(_braceL);
  14586. case 125: ++tokPos; return finishToken(_braceR);
  14587. case 58: ++tokPos; return finishToken(_colon);
  14588. case 63: ++tokPos; return finishToken(_question);
  14589. case 48:
  14590. var next = input.charCodeAt(tokPos + 1);
  14591. if (next === 120 || next === 88) return readHexNumber();
  14592. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57:
  14593. return readNumber(false);
  14594. case 34: case 39:
  14595. return readString(code);
  14596. case 47:
  14597. return readToken_slash(code);
  14598. case 37: case 42:
  14599. return readToken_mult_modulo();
  14600. case 124: case 38:
  14601. return readToken_pipe_amp(code);
  14602. case 94:
  14603. return readToken_caret();
  14604. case 43: case 45:
  14605. return readToken_plus_min(code);
  14606. case 60: case 62:
  14607. return readToken_lt_gt(code);
  14608. case 61: case 33:
  14609. return readToken_eq_excl(code);
  14610. case 126:
  14611. return finishOp(_prefix, 1);
  14612. }
  14613. return false;
  14614. }
  14615. function readToken(forceRegexp) {
  14616. if (!forceRegexp) tokStart = tokPos;
  14617. else tokPos = tokStart + 1;
  14618. if (options.locations) tokStartLoc = new line_loc_t;
  14619. if (forceRegexp) return readRegexp();
  14620. if (tokPos >= inputLen) return finishToken(_eof);
  14621. var code = input.charCodeAt(tokPos);
  14622. if (isIdentifierStart(code) || code === 92 ) return readWord();
  14623. var tok = getTokenFromCode(code);
  14624. if (tok === false) {
  14625. var ch = String.fromCharCode(code);
  14626. if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord();
  14627. raise(tokPos, "Unexpected character '" + ch + "'");
  14628. }
  14629. return tok;
  14630. }
  14631. function finishOp(type, size) {
  14632. var str = input.slice(tokPos, tokPos + size);
  14633. tokPos += size;
  14634. finishToken(type, str);
  14635. }
  14636. function readRegexp() {
  14637. var content = "", escaped, inClass, start = tokPos;
  14638. for (;;) {
  14639. if (tokPos >= inputLen) raise(start, "Unterminated regular expression");
  14640. var ch = input.charAt(tokPos);
  14641. if (newline.test(ch)) raise(start, "Unterminated regular expression");
  14642. if (!escaped) {
  14643. if (ch === "[") inClass = true;
  14644. else if (ch === "]" && inClass) inClass = false;
  14645. else if (ch === "/" && !inClass) break;
  14646. escaped = ch === "\\";
  14647. } else escaped = false;
  14648. ++tokPos;
  14649. }
  14650. var content = input.slice(start, tokPos);
  14651. ++tokPos;
  14652. var mods = readWord1();
  14653. if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag");
  14654. try {
  14655. var value = new RegExp(content, mods);
  14656. } catch (e) {
  14657. if (e instanceof SyntaxError) raise(start, e.message);
  14658. raise(e);
  14659. }
  14660. return finishToken(_regexp, value);
  14661. }
  14662. function readInt(radix, len) {
  14663. var start = tokPos, total = 0;
  14664. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  14665. var code = input.charCodeAt(tokPos), val;
  14666. if (code >= 97) val = code - 97 + 10;
  14667. else if (code >= 65) val = code - 65 + 10;
  14668. else if (code >= 48 && code <= 57) val = code - 48;
  14669. else val = Infinity;
  14670. if (val >= radix) break;
  14671. ++tokPos;
  14672. total = total * radix + val;
  14673. }
  14674. if (tokPos === start || len != null && tokPos - start !== len) return null;
  14675. return total;
  14676. }
  14677. function readHexNumber() {
  14678. tokPos += 2;
  14679. var val = readInt(16);
  14680. if (val == null) raise(tokStart + 2, "Expected hexadecimal number");
  14681. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  14682. return finishToken(_num, val);
  14683. }
  14684. function readNumber(startsWithDot) {
  14685. var start = tokPos, isFloat = false, octal = input.charCodeAt(tokPos) === 48;
  14686. if (!startsWithDot && readInt(10) === null) raise(start, "Invalid number");
  14687. if (input.charCodeAt(tokPos) === 46) {
  14688. ++tokPos;
  14689. readInt(10);
  14690. isFloat = true;
  14691. }
  14692. var next = input.charCodeAt(tokPos);
  14693. if (next === 69 || next === 101) {
  14694. next = input.charCodeAt(++tokPos);
  14695. if (next === 43 || next === 45) ++tokPos;
  14696. if (readInt(10) === null) raise(start, "Invalid number");
  14697. isFloat = true;
  14698. }
  14699. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  14700. var str = input.slice(start, tokPos), val;
  14701. if (isFloat) val = parseFloat(str);
  14702. else if (!octal || str.length === 1) val = parseInt(str, 10);
  14703. else if (/[89]/.test(str) || strict) raise(start, "Invalid number");
  14704. else val = parseInt(str, 8);
  14705. return finishToken(_num, val);
  14706. }
  14707. function readString(quote) {
  14708. tokPos++;
  14709. var out = "";
  14710. for (;;) {
  14711. if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");
  14712. var ch = input.charCodeAt(tokPos);
  14713. if (ch === quote) {
  14714. ++tokPos;
  14715. return finishToken(_string, out);
  14716. }
  14717. if (ch === 92) {
  14718. ch = input.charCodeAt(++tokPos);
  14719. var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));
  14720. if (octal) octal = octal[0];
  14721. while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);
  14722. if (octal === "0") octal = null;
  14723. ++tokPos;
  14724. if (octal) {
  14725. if (strict) raise(tokPos - 2, "Octal literal in strict mode");
  14726. out += String.fromCharCode(parseInt(octal, 8));
  14727. tokPos += octal.length - 1;
  14728. } else {
  14729. switch (ch) {
  14730. case 110: out += "\n"; break;
  14731. case 114: out += "\r"; break;
  14732. case 120: out += String.fromCharCode(readHexChar(2)); break;
  14733. case 117: out += String.fromCharCode(readHexChar(4)); break;
  14734. case 85: out += String.fromCharCode(readHexChar(8)); break;
  14735. case 116: out += "\t"; break;
  14736. case 98: out += "\b"; break;
  14737. case 118: out += "\u000b"; break;
  14738. case 102: out += "\f"; break;
  14739. case 48: out += "\0"; break;
  14740. case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos;
  14741. case 10:
  14742. if (options.locations) { tokLineStart = tokPos; ++tokCurLine; }
  14743. break;
  14744. default: out += String.fromCharCode(ch); break;
  14745. }
  14746. }
  14747. } else {
  14748. if (ch === 13 || ch === 10 || ch === 8232 || ch === 8233) raise(tokStart, "Unterminated string constant");
  14749. out += String.fromCharCode(ch);
  14750. ++tokPos;
  14751. }
  14752. }
  14753. }
  14754. function readHexChar(len) {
  14755. var n = readInt(16, len);
  14756. if (n === null) raise(tokStart, "Bad character escape sequence");
  14757. return n;
  14758. }
  14759. var containsEsc;
  14760. function readWord1() {
  14761. containsEsc = false;
  14762. var word, first = true, start = tokPos;
  14763. for (;;) {
  14764. var ch = input.charCodeAt(tokPos);
  14765. if (isIdentifierChar(ch)) {
  14766. if (containsEsc) word += input.charAt(tokPos);
  14767. ++tokPos;
  14768. } else if (ch === 92) {
  14769. if (!containsEsc) word = input.slice(start, tokPos);
  14770. containsEsc = true;
  14771. if (input.charCodeAt(++tokPos) != 117)
  14772. raise(tokPos, "Expecting Unicode escape sequence \\uXXXX");
  14773. ++tokPos;
  14774. var esc = readHexChar(4);
  14775. var escStr = String.fromCharCode(esc);
  14776. if (!escStr) raise(tokPos - 1, "Invalid Unicode escape");
  14777. if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc)))
  14778. raise(tokPos - 4, "Invalid Unicode escape");
  14779. word += escStr;
  14780. } else {
  14781. break;
  14782. }
  14783. first = false;
  14784. }
  14785. return containsEsc ? word : input.slice(start, tokPos);
  14786. }
  14787. function readWord() {
  14788. var word = readWord1();
  14789. var type = _name;
  14790. if (!containsEsc && isKeyword(word))
  14791. type = keywordTypes[word];
  14792. return finishToken(type, word);
  14793. }
  14794. function next() {
  14795. lastStart = tokStart;
  14796. lastEnd = tokEnd;
  14797. lastEndLoc = tokEndLoc;
  14798. readToken();
  14799. }
  14800. function setStrict(strct) {
  14801. strict = strct;
  14802. tokPos = tokStart;
  14803. if (options.locations) {
  14804. while (tokPos < tokLineStart) {
  14805. tokLineStart = input.lastIndexOf("\n", tokLineStart - 2) + 1;
  14806. --tokCurLine;
  14807. }
  14808. }
  14809. skipSpace();
  14810. readToken();
  14811. }
  14812. function node_t() {
  14813. this.type = null;
  14814. this.start = tokStart;
  14815. this.end = null;
  14816. }
  14817. function node_loc_t() {
  14818. this.start = tokStartLoc;
  14819. this.end = null;
  14820. if (sourceFile !== null) this.source = sourceFile;
  14821. }
  14822. function startNode() {
  14823. var node = new node_t();
  14824. if (options.locations)
  14825. node.loc = new node_loc_t();
  14826. if (options.directSourceFile)
  14827. node.sourceFile = options.directSourceFile;
  14828. if (options.ranges)
  14829. node.range = [tokStart, 0];
  14830. return node;
  14831. }
  14832. function startNodeFrom(other) {
  14833. var node = new node_t();
  14834. node.start = other.start;
  14835. if (options.locations) {
  14836. node.loc = new node_loc_t();
  14837. node.loc.start = other.loc.start;
  14838. }
  14839. if (options.ranges)
  14840. node.range = [other.range[0], 0];
  14841. return node;
  14842. }
  14843. function finishNode(node, type) {
  14844. node.type = type;
  14845. node.end = lastEnd;
  14846. if (options.locations)
  14847. node.loc.end = lastEndLoc;
  14848. if (options.ranges)
  14849. node.range[1] = lastEnd;
  14850. return node;
  14851. }
  14852. function isUseStrict(stmt) {
  14853. return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
  14854. stmt.expression.type === "Literal" && stmt.expression.value === "use strict";
  14855. }
  14856. function eat(type) {
  14857. if (tokType === type) {
  14858. next();
  14859. return true;
  14860. }
  14861. }
  14862. function canInsertSemicolon() {
  14863. return !options.strictSemicolons &&
  14864. (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart)));
  14865. }
  14866. function semicolon() {
  14867. if (!eat(_semi) && !canInsertSemicolon()) unexpected();
  14868. }
  14869. function expect(type) {
  14870. if (tokType === type) next();
  14871. else unexpected();
  14872. }
  14873. function unexpected() {
  14874. raise(tokStart, "Unexpected token");
  14875. }
  14876. function checkLVal(expr) {
  14877. if (expr.type !== "Identifier" && expr.type !== "MemberExpression")
  14878. raise(expr.start, "Assigning to rvalue");
  14879. if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name))
  14880. raise(expr.start, "Assigning to " + expr.name + " in strict mode");
  14881. }
  14882. function parseTopLevel(program) {
  14883. lastStart = lastEnd = tokPos;
  14884. if (options.locations) lastEndLoc = new line_loc_t;
  14885. inFunction = strict = null;
  14886. labels = [];
  14887. readToken();
  14888. var node = program || startNode(), first = true;
  14889. if (!program) node.body = [];
  14890. while (tokType !== _eof) {
  14891. var stmt = parseStatement();
  14892. node.body.push(stmt);
  14893. if (first && isUseStrict(stmt)) setStrict(true);
  14894. first = false;
  14895. }
  14896. return finishNode(node, "Program");
  14897. }
  14898. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  14899. function parseStatement() {
  14900. if (tokType === _slash || tokType === _assign && tokVal == "/=")
  14901. readToken(true);
  14902. var starttype = tokType, node = startNode();
  14903. switch (starttype) {
  14904. case _break: case _continue:
  14905. next();
  14906. var isBreak = starttype === _break;
  14907. if (eat(_semi) || canInsertSemicolon()) node.label = null;
  14908. else if (tokType !== _name) unexpected();
  14909. else {
  14910. node.label = parseIdent();
  14911. semicolon();
  14912. }
  14913. for (var i = 0; i < labels.length; ++i) {
  14914. var lab = labels[i];
  14915. if (node.label == null || lab.name === node.label.name) {
  14916. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  14917. if (node.label && isBreak) break;
  14918. }
  14919. }
  14920. if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword);
  14921. return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  14922. case _debugger:
  14923. next();
  14924. semicolon();
  14925. return finishNode(node, "DebuggerStatement");
  14926. case _do:
  14927. next();
  14928. labels.push(loopLabel);
  14929. node.body = parseStatement();
  14930. labels.pop();
  14931. expect(_while);
  14932. node.test = parseParenExpression();
  14933. semicolon();
  14934. return finishNode(node, "DoWhileStatement");
  14935. case _for:
  14936. next();
  14937. labels.push(loopLabel);
  14938. expect(_parenL);
  14939. if (tokType === _semi) return parseFor(node, null);
  14940. if (tokType === _var) {
  14941. var init = startNode();
  14942. next();
  14943. parseVar(init, true);
  14944. finishNode(init, "VariableDeclaration");
  14945. if (init.declarations.length === 1 && eat(_in))
  14946. return parseForIn(node, init);
  14947. return parseFor(node, init);
  14948. }
  14949. var init = parseExpression(false, true);
  14950. if (eat(_in)) {checkLVal(init); return parseForIn(node, init);}
  14951. return parseFor(node, init);
  14952. case _function:
  14953. next();
  14954. return parseFunction(node, true);
  14955. case _if:
  14956. next();
  14957. node.test = parseParenExpression();
  14958. node.consequent = parseStatement();
  14959. node.alternate = eat(_else) ? parseStatement() : null;
  14960. return finishNode(node, "IfStatement");
  14961. case _return:
  14962. if (!inFunction && !options.allowReturnOutsideFunction)
  14963. raise(tokStart, "'return' outside of function");
  14964. next();
  14965. if (eat(_semi) || canInsertSemicolon()) node.argument = null;
  14966. else { node.argument = parseExpression(); semicolon(); }
  14967. return finishNode(node, "ReturnStatement");
  14968. case _switch:
  14969. next();
  14970. node.discriminant = parseParenExpression();
  14971. node.cases = [];
  14972. expect(_braceL);
  14973. labels.push(switchLabel);
  14974. for (var cur, sawDefault; tokType != _braceR;) {
  14975. if (tokType === _case || tokType === _default) {
  14976. var isCase = tokType === _case;
  14977. if (cur) finishNode(cur, "SwitchCase");
  14978. node.cases.push(cur = startNode());
  14979. cur.consequent = [];
  14980. next();
  14981. if (isCase) cur.test = parseExpression();
  14982. else {
  14983. if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true;
  14984. cur.test = null;
  14985. }
  14986. expect(_colon);
  14987. } else {
  14988. if (!cur) unexpected();
  14989. cur.consequent.push(parseStatement());
  14990. }
  14991. }
  14992. if (cur) finishNode(cur, "SwitchCase");
  14993. next();
  14994. labels.pop();
  14995. return finishNode(node, "SwitchStatement");
  14996. case _throw:
  14997. next();
  14998. if (newline.test(input.slice(lastEnd, tokStart)))
  14999. raise(lastEnd, "Illegal newline after throw");
  15000. node.argument = parseExpression();
  15001. semicolon();
  15002. return finishNode(node, "ThrowStatement");
  15003. case _try:
  15004. next();
  15005. node.block = parseBlock();
  15006. node.handler = null;
  15007. if (tokType === _catch) {
  15008. var clause = startNode();
  15009. next();
  15010. expect(_parenL);
  15011. clause.param = parseIdent();
  15012. if (strict && isStrictBadIdWord(clause.param.name))
  15013. raise(clause.param.start, "Binding " + clause.param.name + " in strict mode");
  15014. expect(_parenR);
  15015. clause.guard = null;
  15016. clause.body = parseBlock();
  15017. node.handler = finishNode(clause, "CatchClause");
  15018. }
  15019. node.guardedHandlers = empty;
  15020. node.finalizer = eat(_finally) ? parseBlock() : null;
  15021. if (!node.handler && !node.finalizer)
  15022. raise(node.start, "Missing catch or finally clause");
  15023. return finishNode(node, "TryStatement");
  15024. case _var:
  15025. next();
  15026. parseVar(node);
  15027. semicolon();
  15028. return finishNode(node, "VariableDeclaration");
  15029. case _while:
  15030. next();
  15031. node.test = parseParenExpression();
  15032. labels.push(loopLabel);
  15033. node.body = parseStatement();
  15034. labels.pop();
  15035. return finishNode(node, "WhileStatement");
  15036. case _with:
  15037. if (strict) raise(tokStart, "'with' in strict mode");
  15038. next();
  15039. node.object = parseParenExpression();
  15040. node.body = parseStatement();
  15041. return finishNode(node, "WithStatement");
  15042. case _braceL:
  15043. return parseBlock();
  15044. case _semi:
  15045. next();
  15046. return finishNode(node, "EmptyStatement");
  15047. default:
  15048. var maybeName = tokVal, expr = parseExpression();
  15049. if (starttype === _name && expr.type === "Identifier" && eat(_colon)) {
  15050. for (var i = 0; i < labels.length; ++i)
  15051. if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared");
  15052. var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null;
  15053. labels.push({name: maybeName, kind: kind});
  15054. node.body = parseStatement();
  15055. labels.pop();
  15056. node.label = expr;
  15057. return finishNode(node, "LabeledStatement");
  15058. } else {
  15059. node.expression = expr;
  15060. semicolon();
  15061. return finishNode(node, "ExpressionStatement");
  15062. }
  15063. }
  15064. }
  15065. function parseParenExpression() {
  15066. expect(_parenL);
  15067. var val = parseExpression();
  15068. expect(_parenR);
  15069. return val;
  15070. }
  15071. function parseBlock(allowStrict) {
  15072. var node = startNode(), first = true, strict = false, oldStrict;
  15073. node.body = [];
  15074. expect(_braceL);
  15075. while (!eat(_braceR)) {
  15076. var stmt = parseStatement();
  15077. node.body.push(stmt);
  15078. if (first && allowStrict && isUseStrict(stmt)) {
  15079. oldStrict = strict;
  15080. setStrict(strict = true);
  15081. }
  15082. first = false;
  15083. }
  15084. if (strict && !oldStrict) setStrict(false);
  15085. return finishNode(node, "BlockStatement");
  15086. }
  15087. function parseFor(node, init) {
  15088. node.init = init;
  15089. expect(_semi);
  15090. node.test = tokType === _semi ? null : parseExpression();
  15091. expect(_semi);
  15092. node.update = tokType === _parenR ? null : parseExpression();
  15093. expect(_parenR);
  15094. node.body = parseStatement();
  15095. labels.pop();
  15096. return finishNode(node, "ForStatement");
  15097. }
  15098. function parseForIn(node, init) {
  15099. node.left = init;
  15100. node.right = parseExpression();
  15101. expect(_parenR);
  15102. node.body = parseStatement();
  15103. labels.pop();
  15104. return finishNode(node, "ForInStatement");
  15105. }
  15106. function parseVar(node, noIn) {
  15107. node.declarations = [];
  15108. node.kind = "var";
  15109. for (;;) {
  15110. var decl = startNode();
  15111. decl.id = parseIdent();
  15112. if (strict && isStrictBadIdWord(decl.id.name))
  15113. raise(decl.id.start, "Binding " + decl.id.name + " in strict mode");
  15114. decl.init = eat(_eq) ? parseExpression(true, noIn) : null;
  15115. node.declarations.push(finishNode(decl, "VariableDeclarator"));
  15116. if (!eat(_comma)) break;
  15117. }
  15118. return node;
  15119. }
  15120. function parseExpression(noComma, noIn) {
  15121. var expr = parseMaybeAssign(noIn);
  15122. if (!noComma && tokType === _comma) {
  15123. var node = startNodeFrom(expr);
  15124. node.expressions = [expr];
  15125. while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn));
  15126. return finishNode(node, "SequenceExpression");
  15127. }
  15128. return expr;
  15129. }
  15130. function parseMaybeAssign(noIn) {
  15131. var left = parseMaybeConditional(noIn);
  15132. if (tokType.isAssign) {
  15133. var node = startNodeFrom(left);
  15134. node.operator = tokVal;
  15135. node.left = left;
  15136. next();
  15137. node.right = parseMaybeAssign(noIn);
  15138. checkLVal(left);
  15139. return finishNode(node, "AssignmentExpression");
  15140. }
  15141. return left;
  15142. }
  15143. function parseMaybeConditional(noIn) {
  15144. var expr = parseExprOps(noIn);
  15145. if (eat(_question)) {
  15146. var node = startNodeFrom(expr);
  15147. node.test = expr;
  15148. node.consequent = parseExpression(true);
  15149. expect(_colon);
  15150. node.alternate = parseExpression(true, noIn);
  15151. return finishNode(node, "ConditionalExpression");
  15152. }
  15153. return expr;
  15154. }
  15155. function parseExprOps(noIn) {
  15156. return parseExprOp(parseMaybeUnary(), -1, noIn);
  15157. }
  15158. function parseExprOp(left, minPrec, noIn) {
  15159. var prec = tokType.binop;
  15160. if (prec != null && (!noIn || tokType !== _in)) {
  15161. if (prec > minPrec) {
  15162. var node = startNodeFrom(left);
  15163. node.left = left;
  15164. node.operator = tokVal;
  15165. var op = tokType;
  15166. next();
  15167. node.right = parseExprOp(parseMaybeUnary(), prec, noIn);
  15168. var exprNode = finishNode(node, (op === _logicalOR || op === _logicalAND) ? "LogicalExpression" : "BinaryExpression");
  15169. return parseExprOp(exprNode, minPrec, noIn);
  15170. }
  15171. }
  15172. return left;
  15173. }
  15174. function parseMaybeUnary() {
  15175. if (tokType.prefix) {
  15176. var node = startNode(), update = tokType.isUpdate;
  15177. node.operator = tokVal;
  15178. node.prefix = true;
  15179. tokRegexpAllowed = true;
  15180. next();
  15181. node.argument = parseMaybeUnary();
  15182. if (update) checkLVal(node.argument);
  15183. else if (strict && node.operator === "delete" &&
  15184. node.argument.type === "Identifier")
  15185. raise(node.start, "Deleting local variable in strict mode");
  15186. return finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  15187. }
  15188. var expr = parseExprSubscripts();
  15189. while (tokType.postfix && !canInsertSemicolon()) {
  15190. var node = startNodeFrom(expr);
  15191. node.operator = tokVal;
  15192. node.prefix = false;
  15193. node.argument = expr;
  15194. checkLVal(expr);
  15195. next();
  15196. expr = finishNode(node, "UpdateExpression");
  15197. }
  15198. return expr;
  15199. }
  15200. function parseExprSubscripts() {
  15201. return parseSubscripts(parseExprAtom());
  15202. }
  15203. function parseSubscripts(base, noCalls) {
  15204. if (eat(_dot)) {
  15205. var node = startNodeFrom(base);
  15206. node.object = base;
  15207. node.property = parseIdent(true);
  15208. node.computed = false;
  15209. return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
  15210. } else if (eat(_bracketL)) {
  15211. var node = startNodeFrom(base);
  15212. node.object = base;
  15213. node.property = parseExpression();
  15214. node.computed = true;
  15215. expect(_bracketR);
  15216. return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
  15217. } else if (!noCalls && eat(_parenL)) {
  15218. var node = startNodeFrom(base);
  15219. node.callee = base;
  15220. node.arguments = parseExprList(_parenR, false);
  15221. return parseSubscripts(finishNode(node, "CallExpression"), noCalls);
  15222. } else return base;
  15223. }
  15224. function parseExprAtom() {
  15225. switch (tokType) {
  15226. case _this:
  15227. var node = startNode();
  15228. next();
  15229. return finishNode(node, "ThisExpression");
  15230. case _name:
  15231. return parseIdent();
  15232. case _num: case _string: case _regexp:
  15233. var node = startNode();
  15234. node.value = tokVal;
  15235. node.raw = input.slice(tokStart, tokEnd);
  15236. next();
  15237. return finishNode(node, "Literal");
  15238. case _null: case _true: case _false:
  15239. var node = startNode();
  15240. node.value = tokType.atomValue;
  15241. node.raw = tokType.keyword;
  15242. next();
  15243. return finishNode(node, "Literal");
  15244. case _parenL:
  15245. var tokStartLoc1 = tokStartLoc, tokStart1 = tokStart;
  15246. next();
  15247. var val = parseExpression();
  15248. val.start = tokStart1;
  15249. val.end = tokEnd;
  15250. if (options.locations) {
  15251. val.loc.start = tokStartLoc1;
  15252. val.loc.end = tokEndLoc;
  15253. }
  15254. if (options.ranges)
  15255. val.range = [tokStart1, tokEnd];
  15256. expect(_parenR);
  15257. return val;
  15258. case _bracketL:
  15259. var node = startNode();
  15260. next();
  15261. node.elements = parseExprList(_bracketR, true, true);
  15262. return finishNode(node, "ArrayExpression");
  15263. case _braceL:
  15264. return parseObj();
  15265. case _function:
  15266. var node = startNode();
  15267. next();
  15268. return parseFunction(node, false);
  15269. case _new:
  15270. return parseNew();
  15271. default:
  15272. unexpected();
  15273. }
  15274. }
  15275. function parseNew() {
  15276. var node = startNode();
  15277. next();
  15278. node.callee = parseSubscripts(parseExprAtom(), true);
  15279. if (eat(_parenL)) node.arguments = parseExprList(_parenR, false);
  15280. else node.arguments = empty;
  15281. return finishNode(node, "NewExpression");
  15282. }
  15283. function parseObj() {
  15284. var node = startNode(), first = true, sawGetSet = false;
  15285. node.properties = [];
  15286. next();
  15287. while (!eat(_braceR)) {
  15288. if (!first) {
  15289. expect(_comma);
  15290. if (options.allowTrailingCommas && eat(_braceR)) break;
  15291. } else first = false;
  15292. var prop = {key: parsePropertyName()}, isGetSet = false, kind;
  15293. if (eat(_colon)) {
  15294. prop.value = parseExpression(true);
  15295. kind = prop.kind = "init";
  15296. } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
  15297. (prop.key.name === "get" || prop.key.name === "set")) {
  15298. isGetSet = sawGetSet = true;
  15299. kind = prop.kind = prop.key.name;
  15300. prop.key = parsePropertyName();
  15301. if (tokType !== _parenL) unexpected();
  15302. prop.value = parseFunction(startNode(), false);
  15303. } else unexpected();
  15304. if (prop.key.type === "Identifier" && (strict || sawGetSet)) {
  15305. for (var i = 0; i < node.properties.length; ++i) {
  15306. var other = node.properties[i];
  15307. if (other.key.name === prop.key.name) {
  15308. var conflict = kind == other.kind || isGetSet && other.kind === "init" ||
  15309. kind === "init" && (other.kind === "get" || other.kind === "set");
  15310. if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false;
  15311. if (conflict) raise(prop.key.start, "Redefinition of property");
  15312. }
  15313. }
  15314. }
  15315. node.properties.push(prop);
  15316. }
  15317. return finishNode(node, "ObjectExpression");
  15318. }
  15319. function parsePropertyName() {
  15320. if (tokType === _num || tokType === _string) return parseExprAtom();
  15321. return parseIdent(true);
  15322. }
  15323. function parseFunction(node, isStatement) {
  15324. if (tokType === _name) node.id = parseIdent();
  15325. else if (isStatement) unexpected();
  15326. else node.id = null;
  15327. node.params = [];
  15328. var first = true;
  15329. expect(_parenL);
  15330. while (!eat(_parenR)) {
  15331. if (!first) expect(_comma); else first = false;
  15332. node.params.push(parseIdent());
  15333. }
  15334. var oldInFunc = inFunction, oldLabels = labels;
  15335. inFunction = true; labels = [];
  15336. node.body = parseBlock(true);
  15337. inFunction = oldInFunc; labels = oldLabels;
  15338. if (strict || node.body.body.length && isUseStrict(node.body.body[0])) {
  15339. for (var i = node.id ? -1 : 0; i < node.params.length; ++i) {
  15340. var id = i < 0 ? node.id : node.params[i];
  15341. if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name))
  15342. raise(id.start, "Defining '" + id.name + "' in strict mode");
  15343. if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name)
  15344. raise(id.start, "Argument name clash in strict mode");
  15345. }
  15346. }
  15347. return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  15348. }
  15349. function parseExprList(close, allowTrailingComma, allowEmpty) {
  15350. var elts = [], first = true;
  15351. while (!eat(close)) {
  15352. if (!first) {
  15353. expect(_comma);
  15354. if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break;
  15355. } else first = false;
  15356. if (allowEmpty && tokType === _comma) elts.push(null);
  15357. else elts.push(parseExpression(true));
  15358. }
  15359. return elts;
  15360. }
  15361. function parseIdent(liberal) {
  15362. var node = startNode();
  15363. if (liberal && options.forbidReserved == "everywhere") liberal = false;
  15364. if (tokType === _name) {
  15365. if (!liberal &&
  15366. (options.forbidReserved &&
  15367. (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(tokVal) ||
  15368. strict && isStrictReservedWord(tokVal)) &&
  15369. input.slice(tokStart, tokEnd).indexOf("\\") == -1)
  15370. raise(tokStart, "The keyword '" + tokVal + "' is reserved");
  15371. node.name = tokVal;
  15372. } else if (liberal && tokType.keyword) {
  15373. node.name = tokType.keyword;
  15374. } else {
  15375. unexpected();
  15376. }
  15377. tokRegexpAllowed = false;
  15378. next();
  15379. return finishNode(node, "Identifier");
  15380. }
  15381. });
  15382. if (!acorn.version)
  15383. acorn = null;
  15384. }
  15385. function parse(code, options) {
  15386. return (global.acorn || acorn).parse(code, options);
  15387. }
  15388. var binaryOperators = {
  15389. '+': '__add',
  15390. '-': '__subtract',
  15391. '*': '__multiply',
  15392. '/': '__divide',
  15393. '%': '__modulo',
  15394. '==': '__equals',
  15395. '!=': '__equals'
  15396. };
  15397. var unaryOperators = {
  15398. '-': '__negate',
  15399. '+': '__self'
  15400. };
  15401. var fields = Base.each(
  15402. ['add', 'subtract', 'multiply', 'divide', 'modulo', 'equals', 'negate'],
  15403. function(name) {
  15404. this['__' + name] = '#' + name;
  15405. },
  15406. {
  15407. __self: function() {
  15408. return this;
  15409. }
  15410. }
  15411. );
  15412. Point.inject(fields);
  15413. Size.inject(fields);
  15414. Color.inject(fields);
  15415. function __$__(left, operator, right) {
  15416. var handler = binaryOperators[operator];
  15417. if (left && left[handler]) {
  15418. var res = left[handler](right);
  15419. return operator === '!=' ? !res : res;
  15420. }
  15421. switch (operator) {
  15422. case '+': return left + right;
  15423. case '-': return left - right;
  15424. case '*': return left * right;
  15425. case '/': return left / right;
  15426. case '%': return left % right;
  15427. case '==': return left == right;
  15428. case '!=': return left != right;
  15429. }
  15430. }
  15431. function $__(operator, value) {
  15432. var handler = unaryOperators[operator];
  15433. if (value && value[handler])
  15434. return value[handler]();
  15435. switch (operator) {
  15436. case '+': return +value;
  15437. case '-': return -value;
  15438. }
  15439. }
  15440. function compile(code, options) {
  15441. if (!code)
  15442. return '';
  15443. options = options || {};
  15444. var insertions = [];
  15445. function getOffset(offset) {
  15446. for (var i = 0, l = insertions.length; i < l; i++) {
  15447. var insertion = insertions[i];
  15448. if (insertion[0] >= offset)
  15449. break;
  15450. offset += insertion[1];
  15451. }
  15452. return offset;
  15453. }
  15454. function getCode(node) {
  15455. return code.substring(getOffset(node.range[0]),
  15456. getOffset(node.range[1]));
  15457. }
  15458. function getBetween(left, right) {
  15459. return code.substring(getOffset(left.range[1]),
  15460. getOffset(right.range[0]));
  15461. }
  15462. function replaceCode(node, str) {
  15463. var start = getOffset(node.range[0]),
  15464. end = getOffset(node.range[1]),
  15465. insert = 0;
  15466. for (var i = insertions.length - 1; i >= 0; i--) {
  15467. if (start > insertions[i][0]) {
  15468. insert = i + 1;
  15469. break;
  15470. }
  15471. }
  15472. insertions.splice(insert, 0, [start, str.length - end + start]);
  15473. code = code.substring(0, start) + str + code.substring(end);
  15474. }
  15475. function handleOverloading(node, parent) {
  15476. switch (node.type) {
  15477. case 'UnaryExpression':
  15478. if (node.operator in unaryOperators
  15479. && node.argument.type !== 'Literal') {
  15480. var arg = getCode(node.argument);
  15481. replaceCode(node, '$__("' + node.operator + '", '
  15482. + arg + ')');
  15483. }
  15484. break;
  15485. case 'BinaryExpression':
  15486. if (node.operator in binaryOperators
  15487. && node.left.type !== 'Literal') {
  15488. var left = getCode(node.left),
  15489. right = getCode(node.right),
  15490. between = getBetween(node.left, node.right),
  15491. operator = node.operator;
  15492. replaceCode(node, '__$__(' + left + ','
  15493. + between.replace(new RegExp('\\' + operator),
  15494. '"' + operator + '"')
  15495. + ', ' + right + ')');
  15496. }
  15497. break;
  15498. case 'UpdateExpression':
  15499. case 'AssignmentExpression':
  15500. var parentType = parent && parent.type;
  15501. if (!(
  15502. parentType === 'ForStatement'
  15503. || parentType === 'BinaryExpression'
  15504. && /^[=!<>]/.test(parent.operator)
  15505. || parentType === 'MemberExpression' && parent.computed
  15506. )) {
  15507. if (node.type === 'UpdateExpression') {
  15508. var arg = getCode(node.argument),
  15509. exp = '__$__(' + arg + ', "' + node.operator[0]
  15510. + '", 1)',
  15511. str = arg + ' = ' + exp;
  15512. if (node.prefix) {
  15513. str = '(' + str + ')';
  15514. } else if (
  15515. parentType === 'AssignmentExpression' ||
  15516. parentType === 'VariableDeclarator' ||
  15517. parentType === 'BinaryExpression'
  15518. ) {
  15519. if (getCode(parent.left || parent.id) === arg)
  15520. str = exp;
  15521. str = arg + '; ' + str;
  15522. }
  15523. replaceCode(node, str);
  15524. } else {
  15525. if (/^.=$/.test(node.operator)
  15526. && node.left.type !== 'Literal') {
  15527. var left = getCode(node.left),
  15528. right = getCode(node.right),
  15529. exp = left + ' = __$__(' + left + ', "'
  15530. + node.operator[0] + '", ' + right + ')';
  15531. replaceCode(node, /^\(.*\)$/.test(getCode(node))
  15532. ? '(' + exp + ')' : exp);
  15533. }
  15534. }
  15535. }
  15536. break;
  15537. }
  15538. }
  15539. function handleExports(node) {
  15540. switch (node.type) {
  15541. case 'ExportDefaultDeclaration':
  15542. replaceCode({
  15543. range: [node.start, node.declaration.start]
  15544. }, 'module.exports = ');
  15545. break;
  15546. case 'ExportNamedDeclaration':
  15547. var declaration = node.declaration;
  15548. var specifiers = node.specifiers;
  15549. if (declaration) {
  15550. var declarations = declaration.declarations;
  15551. if (declarations) {
  15552. declarations.forEach(function(dec) {
  15553. replaceCode(dec, 'module.exports.' + getCode(dec));
  15554. });
  15555. replaceCode({
  15556. range: [
  15557. node.start,
  15558. declaration.start + declaration.kind.length
  15559. ]
  15560. }, '');
  15561. }
  15562. } else if (specifiers) {
  15563. var exports = specifiers.map(function(specifier) {
  15564. var name = getCode(specifier);
  15565. return 'module.exports.' + name + ' = ' + name + '; ';
  15566. }).join('');
  15567. if (exports) {
  15568. replaceCode(node, exports);
  15569. }
  15570. }
  15571. break;
  15572. }
  15573. }
  15574. function walkAST(node, parent, paperFeatures) {
  15575. if (node) {
  15576. for (var key in node) {
  15577. if (key !== 'range' && key !== 'loc') {
  15578. var value = node[key];
  15579. if (Array.isArray(value)) {
  15580. for (var i = 0, l = value.length; i < l; i++) {
  15581. walkAST(value[i], node, paperFeatures);
  15582. }
  15583. } else if (value && typeof value === 'object') {
  15584. walkAST(value, node, paperFeatures);
  15585. }
  15586. }
  15587. }
  15588. if (paperFeatures.operatorOverloading !== false) {
  15589. handleOverloading(node, parent);
  15590. }
  15591. if (paperFeatures.moduleExports !== false) {
  15592. handleExports(node);
  15593. }
  15594. }
  15595. }
  15596. function encodeVLQ(value) {
  15597. var res = '',
  15598. base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  15599. value = (Math.abs(value) << 1) + (value < 0 ? 1 : 0);
  15600. while (value || !res) {
  15601. var next = value & (32 - 1);
  15602. value >>= 5;
  15603. if (value)
  15604. next |= 32;
  15605. res += base64[next];
  15606. }
  15607. return res;
  15608. }
  15609. var url = options.url || '',
  15610. sourceMaps = options.sourceMaps,
  15611. paperFeatures = options.paperFeatures || {},
  15612. source = options.source || code,
  15613. offset = options.offset || 0,
  15614. agent = paper.agent,
  15615. version = agent.versionNumber,
  15616. offsetCode = false,
  15617. lineBreaks = /\r\n|\n|\r/mg,
  15618. map;
  15619. if (sourceMaps && (agent.chrome && version >= 30
  15620. || agent.webkit && version >= 537.76
  15621. || agent.firefox && version >= 23
  15622. || agent.node)) {
  15623. if (agent.node) {
  15624. offset -= 2;
  15625. } else if (window && url && !window.location.href.indexOf(url)) {
  15626. var html = document.getElementsByTagName('html')[0].innerHTML;
  15627. offset = html.substr(0, html.indexOf(code) + 1).match(
  15628. lineBreaks).length + 1;
  15629. }
  15630. offsetCode = offset > 0 && !(
  15631. agent.chrome && version >= 36 ||
  15632. agent.safari && version >= 600 ||
  15633. agent.firefox && version >= 40 ||
  15634. agent.node);
  15635. var mappings = ['AA' + encodeVLQ(offsetCode ? 0 : offset) + 'A'];
  15636. mappings.length = (code.match(lineBreaks) || []).length + 1
  15637. + (offsetCode ? offset : 0);
  15638. map = {
  15639. version: 3,
  15640. file: url,
  15641. names:[],
  15642. mappings: mappings.join(';AACA'),
  15643. sourceRoot: '',
  15644. sources: [url],
  15645. sourcesContent: [source]
  15646. };
  15647. }
  15648. if (
  15649. paperFeatures.operatorOverloading !== false ||
  15650. paperFeatures.moduleExports !== false
  15651. ) {
  15652. walkAST(parse(code, {
  15653. ranges: true,
  15654. preserveParens: true,
  15655. sourceType: 'module'
  15656. }), null, paperFeatures);
  15657. }
  15658. if (map) {
  15659. if (offsetCode) {
  15660. code = new Array(offset + 1).join('\n') + code;
  15661. }
  15662. if (/^(inline|both)$/.test(sourceMaps)) {
  15663. code += "\n//# sourceMappingURL=data:application/json;base64,"
  15664. + self.btoa(unescape(encodeURIComponent(
  15665. JSON.stringify(map))));
  15666. }
  15667. code += "\n//# sourceURL=" + (url || 'paperscript');
  15668. }
  15669. return {
  15670. url: url,
  15671. source: source,
  15672. code: code,
  15673. map: map
  15674. };
  15675. }
  15676. function execute(code, scope, options) {
  15677. paper = scope;
  15678. var view = scope.getView(),
  15679. tool = /\btool\.\w+|\s+on(?:Key|Mouse)(?:Up|Down|Move|Drag)\b/
  15680. .test(code) && !/\bnew\s+Tool\b/.test(code)
  15681. ? new Tool() : null,
  15682. toolHandlers = tool ? tool._events : [],
  15683. handlers = ['onFrame', 'onResize'].concat(toolHandlers),
  15684. params = [],
  15685. args = [],
  15686. func,
  15687. compiled = typeof code === 'object' ? code : compile(code, options);
  15688. code = compiled.code;
  15689. function expose(scope, hidden) {
  15690. for (var key in scope) {
  15691. if ((hidden || !/^_/.test(key)) && new RegExp('([\\b\\s\\W]|^)'
  15692. + key.replace(/\$/g, '\\$') + '\\b').test(code)) {
  15693. params.push(key);
  15694. args.push(scope[key]);
  15695. }
  15696. }
  15697. }
  15698. expose({ __$__: __$__, $__: $__, paper: scope, tool: tool },
  15699. true);
  15700. expose(scope);
  15701. code = 'var module = { exports: {} }; ' + code;
  15702. var exports = Base.each(handlers, function(key) {
  15703. if (new RegExp('\\s+' + key + '\\b').test(code)) {
  15704. params.push(key);
  15705. this.push('module.exports.' + key + ' = ' + key + ';');
  15706. }
  15707. }, []).join('\n');
  15708. if (exports) {
  15709. code += '\n' + exports;
  15710. }
  15711. code += '\nreturn module.exports;';
  15712. var agent = paper.agent;
  15713. if (document && (agent.chrome
  15714. || agent.firefox && agent.versionNumber < 40)) {
  15715. var script = document.createElement('script'),
  15716. head = document.head || document.getElementsByTagName('head')[0];
  15717. if (agent.firefox)
  15718. code = '\n' + code;
  15719. script.appendChild(document.createTextNode(
  15720. 'document.__paperscript__ = function(' + params + ') {' +
  15721. code +
  15722. '\n}'
  15723. ));
  15724. head.appendChild(script);
  15725. func = document.__paperscript__;
  15726. delete document.__paperscript__;
  15727. head.removeChild(script);
  15728. } else {
  15729. func = Function(params, code);
  15730. }
  15731. var exports = func && func.apply(scope, args);
  15732. var obj = exports || {};
  15733. Base.each(toolHandlers, function(key) {
  15734. var value = obj[key];
  15735. if (value)
  15736. tool[key] = value;
  15737. });
  15738. if (view) {
  15739. if (obj.onResize)
  15740. view.setOnResize(obj.onResize);
  15741. view.emit('resize', {
  15742. size: view.size,
  15743. delta: new Point()
  15744. });
  15745. if (obj.onFrame)
  15746. view.setOnFrame(obj.onFrame);
  15747. view.requestUpdate();
  15748. }
  15749. return exports;
  15750. }
  15751. function loadScript(script) {
  15752. if (/^text\/(?:x-|)paperscript$/.test(script.type)
  15753. && PaperScope.getAttribute(script, 'ignore') !== 'true') {
  15754. var canvasId = PaperScope.getAttribute(script, 'canvas'),
  15755. canvas = document.getElementById(canvasId),
  15756. src = script.src || script.getAttribute('data-src'),
  15757. async = PaperScope.hasAttribute(script, 'async'),
  15758. scopeAttribute = 'data-paper-scope';
  15759. if (!canvas)
  15760. throw new Error('Unable to find canvas with id "'
  15761. + canvasId + '"');
  15762. var scope = PaperScope.get(canvas.getAttribute(scopeAttribute))
  15763. || new PaperScope().setup(canvas);
  15764. canvas.setAttribute(scopeAttribute, scope._id);
  15765. if (src) {
  15766. Http.request({
  15767. url: src,
  15768. async: async,
  15769. mimeType: 'text/plain',
  15770. onLoad: function(code) {
  15771. execute(code, scope, src);
  15772. }
  15773. });
  15774. } else {
  15775. execute(script.innerHTML, scope, script.baseURI);
  15776. }
  15777. script.setAttribute('data-paper-ignore', 'true');
  15778. return scope;
  15779. }
  15780. }
  15781. function loadAll() {
  15782. Base.each(document && document.getElementsByTagName('script'),
  15783. loadScript);
  15784. }
  15785. function load(script) {
  15786. return script ? loadScript(script) : loadAll();
  15787. }
  15788. if (window) {
  15789. if (document.readyState === 'complete') {
  15790. setTimeout(loadAll);
  15791. } else {
  15792. DomEvent.add(window, { load: loadAll });
  15793. }
  15794. }
  15795. return {
  15796. compile: compile,
  15797. execute: execute,
  15798. load: load,
  15799. parse: parse,
  15800. calculateBinary: __$__,
  15801. calculateUnary: $__
  15802. };
  15803. }.call(this);
  15804. var paper = new (PaperScope.inject(Base.exports, {
  15805. Base: Base,
  15806. Numerical: Numerical,
  15807. Key: Key,
  15808. DomEvent: DomEvent,
  15809. DomElement: DomElement,
  15810. document: document,
  15811. window: window,
  15812. Symbol: SymbolDefinition,
  15813. PlacedSymbol: SymbolItem
  15814. }))();
  15815. if (paper.agent.node) {
  15816. require('./node/extend.js')(paper);
  15817. }
  15818. if (typeof define === 'function' && define.amd) {
  15819. define('paper', paper);
  15820. } else if (typeof module === 'object' && module) {
  15821. module.exports = paper;
  15822. }
  15823. return paper;
  15824. }.call(this, typeof self === 'object' ? self : null);