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.

15690 lines
384 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. },
  765. install: function(scope) {
  766. var that = this;
  767. Base.each(['project', 'view', 'tool'], function(key) {
  768. Base.define(scope, key, {
  769. configurable: true,
  770. get: function() {
  771. return that[key];
  772. }
  773. });
  774. });
  775. for (var key in this)
  776. if (!/^_/.test(key) && this[key])
  777. scope[key] = this[key];
  778. },
  779. setup: function(element) {
  780. paper = this;
  781. this.project = new Project(element);
  782. return this;
  783. },
  784. createCanvas: function(width, height) {
  785. return CanvasProvider.getCanvas(width, height);
  786. },
  787. activate: function() {
  788. paper = this;
  789. },
  790. clear: function() {
  791. var projects = this.projects,
  792. tools = this.tools;
  793. for (var i = projects.length - 1; i >= 0; i--)
  794. projects[i].remove();
  795. for (var i = tools.length - 1; i >= 0; i--)
  796. tools[i].remove();
  797. },
  798. remove: function() {
  799. this.clear();
  800. delete PaperScope._scopes[this._id];
  801. },
  802. statics: new function() {
  803. function handleAttribute(name) {
  804. name += 'Attribute';
  805. return function(el, attr) {
  806. return el[name](attr) || el[name]('data-paper-' + attr);
  807. };
  808. }
  809. return {
  810. _scopes: {},
  811. _id: 0,
  812. get: function(id) {
  813. return this._scopes[id] || null;
  814. },
  815. getAttribute: handleAttribute('get'),
  816. hasAttribute: handleAttribute('has')
  817. };
  818. }
  819. });
  820. var PaperScopeItem = Base.extend(Emitter, {
  821. initialize: function(activate) {
  822. this._scope = paper;
  823. this._index = this._scope[this._list].push(this) - 1;
  824. if (activate || !this._scope[this._reference])
  825. this.activate();
  826. },
  827. activate: function() {
  828. if (!this._scope)
  829. return false;
  830. var prev = this._scope[this._reference];
  831. if (prev && prev !== this)
  832. prev.emit('deactivate');
  833. this._scope[this._reference] = this;
  834. this.emit('activate', prev);
  835. return true;
  836. },
  837. isActive: function() {
  838. return this._scope[this._reference] === this;
  839. },
  840. remove: function() {
  841. if (this._index == null)
  842. return false;
  843. Base.splice(this._scope[this._list], null, this._index, 1);
  844. if (this._scope[this._reference] == this)
  845. this._scope[this._reference] = null;
  846. this._scope = null;
  847. return true;
  848. },
  849. getView: function() {
  850. return this._scope.getView();
  851. }
  852. });
  853. var CollisionDetection = {
  854. findItemBoundsCollisions: function(items1, items2, tolerance) {
  855. function getBounds(items) {
  856. var bounds = new Array(items.length);
  857. for (var i = 0; i < items.length; i++) {
  858. var rect = items[i].getBounds();
  859. bounds[i] = [rect.left, rect.top, rect.right, rect.bottom];
  860. }
  861. return bounds;
  862. }
  863. var bounds1 = getBounds(items1),
  864. bounds2 = !items2 || items2 === items1
  865. ? bounds1
  866. : getBounds(items2);
  867. return this.findBoundsCollisions(bounds1, bounds2, tolerance || 0);
  868. },
  869. findCurveBoundsCollisions: function(curves1, curves2, tolerance, bothAxis) {
  870. function getBounds(curves) {
  871. var min = Math.min,
  872. max = Math.max,
  873. bounds = new Array(curves.length);
  874. for (var i = 0; i < curves.length; i++) {
  875. var v = curves[i];
  876. bounds[i] = [
  877. min(v[0], v[2], v[4], v[6]),
  878. min(v[1], v[3], v[5], v[7]),
  879. max(v[0], v[2], v[4], v[6]),
  880. max(v[1], v[3], v[5], v[7])
  881. ];
  882. }
  883. return bounds;
  884. }
  885. var bounds1 = getBounds(curves1),
  886. bounds2 = !curves2 || curves2 === curves1
  887. ? bounds1
  888. : getBounds(curves2);
  889. if (bothAxis) {
  890. var hor = this.findBoundsCollisions(
  891. bounds1, bounds2, tolerance || 0, false, true),
  892. ver = this.findBoundsCollisions(
  893. bounds1, bounds2, tolerance || 0, true, true),
  894. list = [];
  895. for (var i = 0, l = hor.length; i < l; i++) {
  896. list[i] = { hor: hor[i], ver: ver[i] };
  897. }
  898. return list;
  899. }
  900. return this.findBoundsCollisions(bounds1, bounds2, tolerance || 0);
  901. },
  902. findBoundsCollisions: function(boundsA, boundsB, tolerance,
  903. sweepVertical, onlySweepAxisCollisions) {
  904. var self = !boundsB || boundsA === boundsB,
  905. allBounds = self ? boundsA : boundsA.concat(boundsB),
  906. lengthA = boundsA.length,
  907. lengthAll = allBounds.length;
  908. function binarySearch(indices, coord, value) {
  909. var lo = 0,
  910. hi = indices.length;
  911. while (lo < hi) {
  912. var mid = (hi + lo) >>> 1;
  913. if (allBounds[indices[mid]][coord] < value) {
  914. lo = mid + 1;
  915. } else {
  916. hi = mid;
  917. }
  918. }
  919. return lo - 1;
  920. }
  921. var pri0 = sweepVertical ? 1 : 0,
  922. pri1 = pri0 + 2,
  923. sec0 = sweepVertical ? 0 : 1,
  924. sec1 = sec0 + 2;
  925. var allIndicesByPri0 = new Array(lengthAll);
  926. for (var i = 0; i < lengthAll; i++) {
  927. allIndicesByPri0[i] = i;
  928. }
  929. allIndicesByPri0.sort(function(i1, i2) {
  930. return allBounds[i1][pri0] - allBounds[i2][pri0];
  931. });
  932. var activeIndicesByPri1 = [],
  933. allCollisions = new Array(lengthA);
  934. for (var i = 0; i < lengthAll; i++) {
  935. var curIndex = allIndicesByPri0[i],
  936. curBounds = allBounds[curIndex],
  937. origIndex = self ? curIndex : curIndex - lengthA,
  938. isCurrentA = curIndex < lengthA,
  939. isCurrentB = self || !isCurrentA,
  940. curCollisions = isCurrentA ? [] : null;
  941. if (activeIndicesByPri1.length) {
  942. var pruneCount = binarySearch(activeIndicesByPri1, pri1,
  943. curBounds[pri0] - tolerance) + 1;
  944. activeIndicesByPri1.splice(0, pruneCount);
  945. if (self && onlySweepAxisCollisions) {
  946. curCollisions = curCollisions.concat(activeIndicesByPri1);
  947. for (var j = 0; j < activeIndicesByPri1.length; j++) {
  948. var activeIndex = activeIndicesByPri1[j];
  949. allCollisions[activeIndex].push(origIndex);
  950. }
  951. } else {
  952. var curSec1 = curBounds[sec1],
  953. curSec0 = curBounds[sec0];
  954. for (var j = 0; j < activeIndicesByPri1.length; j++) {
  955. var activeIndex = activeIndicesByPri1[j],
  956. activeBounds = allBounds[activeIndex],
  957. isActiveA = activeIndex < lengthA,
  958. isActiveB = self || activeIndex >= lengthA;
  959. if (
  960. onlySweepAxisCollisions ||
  961. (
  962. isCurrentA && isActiveB ||
  963. isCurrentB && isActiveA
  964. ) && (
  965. curSec1 >= activeBounds[sec0] - tolerance &&
  966. curSec0 <= activeBounds[sec1] + tolerance
  967. )
  968. ) {
  969. if (isCurrentA && isActiveB) {
  970. curCollisions.push(
  971. self ? activeIndex : activeIndex - lengthA);
  972. }
  973. if (isCurrentB && isActiveA) {
  974. allCollisions[activeIndex].push(origIndex);
  975. }
  976. }
  977. }
  978. }
  979. }
  980. if (isCurrentA) {
  981. if (boundsA === boundsB) {
  982. curCollisions.push(curIndex);
  983. }
  984. allCollisions[curIndex] = curCollisions;
  985. }
  986. if (activeIndicesByPri1.length) {
  987. var curPri1 = curBounds[pri1],
  988. index = binarySearch(activeIndicesByPri1, pri1, curPri1);
  989. activeIndicesByPri1.splice(index + 1, 0, curIndex);
  990. } else {
  991. activeIndicesByPri1.push(curIndex);
  992. }
  993. }
  994. for (var i = 0; i < allCollisions.length; i++) {
  995. var collisions = allCollisions[i];
  996. if (collisions) {
  997. collisions.sort(function(i1, i2) { return i1 - i2; });
  998. }
  999. }
  1000. return allCollisions;
  1001. }
  1002. };
  1003. var Formatter = Base.extend({
  1004. initialize: function(precision) {
  1005. this.precision = Base.pick(precision, 5);
  1006. this.multiplier = Math.pow(10, this.precision);
  1007. },
  1008. number: function(val) {
  1009. return this.precision < 16
  1010. ? Math.round(val * this.multiplier) / this.multiplier : val;
  1011. },
  1012. pair: function(val1, val2, separator) {
  1013. return this.number(val1) + (separator || ',') + this.number(val2);
  1014. },
  1015. point: function(val, separator) {
  1016. return this.number(val.x) + (separator || ',') + this.number(val.y);
  1017. },
  1018. size: function(val, separator) {
  1019. return this.number(val.width) + (separator || ',')
  1020. + this.number(val.height);
  1021. },
  1022. rectangle: function(val, separator) {
  1023. return this.point(val, separator) + (separator || ',')
  1024. + this.size(val, separator);
  1025. }
  1026. });
  1027. Formatter.instance = new Formatter();
  1028. var Numerical = new function() {
  1029. var abscissas = [
  1030. [ 0.5773502691896257645091488],
  1031. [0,0.7745966692414833770358531],
  1032. [ 0.3399810435848562648026658,0.8611363115940525752239465],
  1033. [0,0.5384693101056830910363144,0.9061798459386639927976269],
  1034. [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
  1035. [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
  1036. [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
  1037. [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
  1038. [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
  1039. [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
  1040. [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
  1041. [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
  1042. [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
  1043. [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
  1044. [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
  1045. ];
  1046. var weights = [
  1047. [1],
  1048. [0.8888888888888888888888889,0.5555555555555555555555556],
  1049. [0.6521451548625461426269361,0.3478548451374538573730639],
  1050. [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
  1051. [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
  1052. [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
  1053. [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
  1054. [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
  1055. [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
  1056. [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
  1057. [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
  1058. [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
  1059. [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
  1060. [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
  1061. [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
  1062. ];
  1063. var abs = Math.abs,
  1064. sqrt = Math.sqrt,
  1065. pow = Math.pow,
  1066. log2 = Math.log2 || function(x) {
  1067. return Math.log(x) * Math.LOG2E;
  1068. },
  1069. EPSILON = 1e-12,
  1070. MACHINE_EPSILON = 1.12e-16;
  1071. function clamp(value, min, max) {
  1072. return value < min ? min : value > max ? max : value;
  1073. }
  1074. function getDiscriminant(a, b, c) {
  1075. function split(v) {
  1076. var x = v * 134217729,
  1077. y = v - x,
  1078. hi = y + x,
  1079. lo = v - hi;
  1080. return [hi, lo];
  1081. }
  1082. var D = b * b - a * c,
  1083. E = b * b + a * c;
  1084. if (abs(D) * 3 < E) {
  1085. var ad = split(a),
  1086. bd = split(b),
  1087. cd = split(c),
  1088. p = b * b,
  1089. dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1],
  1090. q = a * c,
  1091. dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0])
  1092. + ad[1] * cd[1];
  1093. D = (p - q) + (dp - dq);
  1094. }
  1095. return D;
  1096. }
  1097. function getNormalizationFactor() {
  1098. var norm = Math.max.apply(Math, arguments);
  1099. return norm && (norm < 1e-8 || norm > 1e8)
  1100. ? pow(2, -Math.round(log2(norm)))
  1101. : 0;
  1102. }
  1103. return {
  1104. EPSILON: EPSILON,
  1105. MACHINE_EPSILON: MACHINE_EPSILON,
  1106. CURVETIME_EPSILON: 1e-8,
  1107. GEOMETRIC_EPSILON: 1e-7,
  1108. TRIGONOMETRIC_EPSILON: 1e-8,
  1109. KAPPA: 4 * (sqrt(2) - 1) / 3,
  1110. isZero: function(val) {
  1111. return val >= -EPSILON && val <= EPSILON;
  1112. },
  1113. isMachineZero: function(val) {
  1114. return val >= -MACHINE_EPSILON && val <= MACHINE_EPSILON;
  1115. },
  1116. clamp: clamp,
  1117. integrate: function(f, a, b, n) {
  1118. var x = abscissas[n - 2],
  1119. w = weights[n - 2],
  1120. A = (b - a) * 0.5,
  1121. B = A + a,
  1122. i = 0,
  1123. m = (n + 1) >> 1,
  1124. sum = n & 1 ? w[i++] * f(B) : 0;
  1125. while (i < m) {
  1126. var Ax = A * x[i];
  1127. sum += w[i++] * (f(B + Ax) + f(B - Ax));
  1128. }
  1129. return A * sum;
  1130. },
  1131. findRoot: function(f, df, x, a, b, n, tolerance) {
  1132. for (var i = 0; i < n; i++) {
  1133. var fx = f(x),
  1134. dx = fx / df(x),
  1135. nx = x - dx;
  1136. if (abs(dx) < tolerance) {
  1137. x = nx;
  1138. break;
  1139. }
  1140. if (fx > 0) {
  1141. b = x;
  1142. x = nx <= a ? (a + b) * 0.5 : nx;
  1143. } else {
  1144. a = x;
  1145. x = nx >= b ? (a + b) * 0.5 : nx;
  1146. }
  1147. }
  1148. return clamp(x, a, b);
  1149. },
  1150. solveQuadratic: function(a, b, c, roots, min, max) {
  1151. var x1, x2 = Infinity;
  1152. if (abs(a) < EPSILON) {
  1153. if (abs(b) < EPSILON)
  1154. return abs(c) < EPSILON ? -1 : 0;
  1155. x1 = -c / b;
  1156. } else {
  1157. b *= -0.5;
  1158. var D = getDiscriminant(a, b, c);
  1159. if (D && abs(D) < MACHINE_EPSILON) {
  1160. var f = getNormalizationFactor(abs(a), abs(b), abs(c));
  1161. if (f) {
  1162. a *= f;
  1163. b *= f;
  1164. c *= f;
  1165. D = getDiscriminant(a, b, c);
  1166. }
  1167. }
  1168. if (D >= -MACHINE_EPSILON) {
  1169. var Q = D < 0 ? 0 : sqrt(D),
  1170. R = b + (b < 0 ? -Q : Q);
  1171. if (R === 0) {
  1172. x1 = c / a;
  1173. x2 = -x1;
  1174. } else {
  1175. x1 = R / a;
  1176. x2 = c / R;
  1177. }
  1178. }
  1179. }
  1180. var count = 0,
  1181. boundless = min == null,
  1182. minB = min - EPSILON,
  1183. maxB = max + EPSILON;
  1184. if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB))
  1185. roots[count++] = boundless ? x1 : clamp(x1, min, max);
  1186. if (x2 !== x1
  1187. && isFinite(x2) && (boundless || x2 > minB && x2 < maxB))
  1188. roots[count++] = boundless ? x2 : clamp(x2, min, max);
  1189. return count;
  1190. },
  1191. solveCubic: function(a, b, c, d, roots, min, max) {
  1192. var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)),
  1193. x, b1, c2, qd, q;
  1194. if (f) {
  1195. a *= f;
  1196. b *= f;
  1197. c *= f;
  1198. d *= f;
  1199. }
  1200. function evaluate(x0) {
  1201. x = x0;
  1202. var tmp = a * x;
  1203. b1 = tmp + b;
  1204. c2 = b1 * x + c;
  1205. qd = (tmp + b1) * x + c2;
  1206. q = c2 * x + d;
  1207. }
  1208. if (abs(a) < EPSILON) {
  1209. a = b;
  1210. b1 = c;
  1211. c2 = d;
  1212. x = Infinity;
  1213. } else if (abs(d) < EPSILON) {
  1214. b1 = b;
  1215. c2 = c;
  1216. x = 0;
  1217. } else {
  1218. evaluate(-(b / a) / 3);
  1219. var t = q / a,
  1220. r = pow(abs(t), 1/3),
  1221. s = t < 0 ? -1 : 1,
  1222. td = -qd / a,
  1223. rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r,
  1224. x0 = x - s * rd;
  1225. if (x0 !== x) {
  1226. do {
  1227. evaluate(x0);
  1228. x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON);
  1229. } while (s * x0 > s * x);
  1230. if (abs(a) * x * x > abs(d / x)) {
  1231. c2 = -d / x;
  1232. b1 = (c2 - c) / x;
  1233. }
  1234. }
  1235. }
  1236. var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max),
  1237. boundless = min == null;
  1238. if (isFinite(x) && (count === 0
  1239. || count > 0 && x !== roots[0] && x !== roots[1])
  1240. && (boundless || x > min - EPSILON && x < max + EPSILON))
  1241. roots[count++] = boundless ? x : clamp(x, min, max);
  1242. return count;
  1243. }
  1244. };
  1245. };
  1246. var UID = {
  1247. _id: 1,
  1248. _pools: {},
  1249. get: function(name) {
  1250. if (name) {
  1251. var pool = this._pools[name];
  1252. if (!pool)
  1253. pool = this._pools[name] = { _id: 1 };
  1254. return pool._id++;
  1255. } else {
  1256. return this._id++;
  1257. }
  1258. }
  1259. };
  1260. var Point = Base.extend({
  1261. _class: 'Point',
  1262. _readIndex: true,
  1263. initialize: function Point(arg0, arg1) {
  1264. var type = typeof arg0,
  1265. reading = this.__read,
  1266. read = 0;
  1267. if (type === 'number') {
  1268. var hasY = typeof arg1 === 'number';
  1269. this._set(arg0, hasY ? arg1 : arg0);
  1270. if (reading)
  1271. read = hasY ? 2 : 1;
  1272. } else if (type === 'undefined' || arg0 === null) {
  1273. this._set(0, 0);
  1274. if (reading)
  1275. read = arg0 === null ? 1 : 0;
  1276. } else {
  1277. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1278. read = 1;
  1279. if (Array.isArray(obj)) {
  1280. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1281. } else if ('x' in obj) {
  1282. this._set(obj.x || 0, obj.y || 0);
  1283. } else if ('width' in obj) {
  1284. this._set(obj.width || 0, obj.height || 0);
  1285. } else if ('angle' in obj) {
  1286. this._set(obj.length || 0, 0);
  1287. this.setAngle(obj.angle || 0);
  1288. } else {
  1289. this._set(0, 0);
  1290. read = 0;
  1291. }
  1292. }
  1293. if (reading)
  1294. this.__read = read;
  1295. return this;
  1296. },
  1297. set: '#initialize',
  1298. _set: function(x, y) {
  1299. this.x = x;
  1300. this.y = y;
  1301. return this;
  1302. },
  1303. equals: function(point) {
  1304. return this === point || point
  1305. && (this.x === point.x && this.y === point.y
  1306. || Array.isArray(point)
  1307. && this.x === point[0] && this.y === point[1])
  1308. || false;
  1309. },
  1310. clone: function() {
  1311. return new Point(this.x, this.y);
  1312. },
  1313. toString: function() {
  1314. var f = Formatter.instance;
  1315. return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
  1316. },
  1317. _serialize: function(options) {
  1318. var f = options.formatter;
  1319. return [f.number(this.x), f.number(this.y)];
  1320. },
  1321. getLength: function() {
  1322. return Math.sqrt(this.x * this.x + this.y * this.y);
  1323. },
  1324. setLength: function(length) {
  1325. if (this.isZero()) {
  1326. var angle = this._angle || 0;
  1327. this._set(
  1328. Math.cos(angle) * length,
  1329. Math.sin(angle) * length
  1330. );
  1331. } else {
  1332. var scale = length / this.getLength();
  1333. if (Numerical.isZero(scale))
  1334. this.getAngle();
  1335. this._set(
  1336. this.x * scale,
  1337. this.y * scale
  1338. );
  1339. }
  1340. },
  1341. getAngle: function() {
  1342. return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;
  1343. },
  1344. setAngle: function(angle) {
  1345. this.setAngleInRadians.call(this, angle * Math.PI / 180);
  1346. },
  1347. getAngleInDegrees: '#getAngle',
  1348. setAngleInDegrees: '#setAngle',
  1349. getAngleInRadians: function() {
  1350. if (!arguments.length) {
  1351. return this.isZero()
  1352. ? this._angle || 0
  1353. : this._angle = Math.atan2(this.y, this.x);
  1354. } else {
  1355. var point = Point.read(arguments),
  1356. div = this.getLength() * point.getLength();
  1357. if (Numerical.isZero(div)) {
  1358. return NaN;
  1359. } else {
  1360. var a = this.dot(point) / div;
  1361. return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a);
  1362. }
  1363. }
  1364. },
  1365. setAngleInRadians: function(angle) {
  1366. this._angle = angle;
  1367. if (!this.isZero()) {
  1368. var length = this.getLength();
  1369. this._set(
  1370. Math.cos(angle) * length,
  1371. Math.sin(angle) * length
  1372. );
  1373. }
  1374. },
  1375. getQuadrant: function() {
  1376. return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
  1377. }
  1378. }, {
  1379. beans: false,
  1380. getDirectedAngle: function() {
  1381. var point = Point.read(arguments);
  1382. return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
  1383. },
  1384. getDistance: function() {
  1385. var args = arguments,
  1386. point = Point.read(args),
  1387. x = point.x - this.x,
  1388. y = point.y - this.y,
  1389. d = x * x + y * y,
  1390. squared = Base.read(args);
  1391. return squared ? d : Math.sqrt(d);
  1392. },
  1393. normalize: function(length) {
  1394. if (length === undefined)
  1395. length = 1;
  1396. var current = this.getLength(),
  1397. scale = current !== 0 ? length / current : 0,
  1398. point = new Point(this.x * scale, this.y * scale);
  1399. if (scale >= 0)
  1400. point._angle = this._angle;
  1401. return point;
  1402. },
  1403. rotate: function(angle, center) {
  1404. if (angle === 0)
  1405. return this.clone();
  1406. angle = angle * Math.PI / 180;
  1407. var point = center ? this.subtract(center) : this,
  1408. sin = Math.sin(angle),
  1409. cos = Math.cos(angle);
  1410. point = new Point(
  1411. point.x * cos - point.y * sin,
  1412. point.x * sin + point.y * cos
  1413. );
  1414. return center ? point.add(center) : point;
  1415. },
  1416. transform: function(matrix) {
  1417. return matrix ? matrix._transformPoint(this) : this;
  1418. },
  1419. add: function() {
  1420. var point = Point.read(arguments);
  1421. return new Point(this.x + point.x, this.y + point.y);
  1422. },
  1423. subtract: function() {
  1424. var point = Point.read(arguments);
  1425. return new Point(this.x - point.x, this.y - point.y);
  1426. },
  1427. multiply: function() {
  1428. var point = Point.read(arguments);
  1429. return new Point(this.x * point.x, this.y * point.y);
  1430. },
  1431. divide: function() {
  1432. var point = Point.read(arguments);
  1433. return new Point(this.x / point.x, this.y / point.y);
  1434. },
  1435. modulo: function() {
  1436. var point = Point.read(arguments);
  1437. return new Point(this.x % point.x, this.y % point.y);
  1438. },
  1439. negate: function() {
  1440. return new Point(-this.x, -this.y);
  1441. },
  1442. isInside: function() {
  1443. return Rectangle.read(arguments).contains(this);
  1444. },
  1445. isClose: function() {
  1446. var args = arguments,
  1447. point = Point.read(args),
  1448. tolerance = Base.read(args);
  1449. return this.getDistance(point) <= tolerance;
  1450. },
  1451. isCollinear: function() {
  1452. var point = Point.read(arguments);
  1453. return Point.isCollinear(this.x, this.y, point.x, point.y);
  1454. },
  1455. isColinear: '#isCollinear',
  1456. isOrthogonal: function() {
  1457. var point = Point.read(arguments);
  1458. return Point.isOrthogonal(this.x, this.y, point.x, point.y);
  1459. },
  1460. isZero: function() {
  1461. var isZero = Numerical.isZero;
  1462. return isZero(this.x) && isZero(this.y);
  1463. },
  1464. isNaN: function() {
  1465. return isNaN(this.x) || isNaN(this.y);
  1466. },
  1467. isInQuadrant: function(q) {
  1468. return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0
  1469. && this.y * (q > 2 ? -1 : 1) >= 0;
  1470. },
  1471. dot: function() {
  1472. var point = Point.read(arguments);
  1473. return this.x * point.x + this.y * point.y;
  1474. },
  1475. cross: function() {
  1476. var point = Point.read(arguments);
  1477. return this.x * point.y - this.y * point.x;
  1478. },
  1479. project: function() {
  1480. var point = Point.read(arguments),
  1481. scale = point.isZero() ? 0 : this.dot(point) / point.dot(point);
  1482. return new Point(
  1483. point.x * scale,
  1484. point.y * scale
  1485. );
  1486. },
  1487. statics: {
  1488. min: function() {
  1489. var args = arguments,
  1490. point1 = Point.read(args),
  1491. point2 = Point.read(args);
  1492. return new Point(
  1493. Math.min(point1.x, point2.x),
  1494. Math.min(point1.y, point2.y)
  1495. );
  1496. },
  1497. max: function() {
  1498. var args = arguments,
  1499. point1 = Point.read(args),
  1500. point2 = Point.read(args);
  1501. return new Point(
  1502. Math.max(point1.x, point2.x),
  1503. Math.max(point1.y, point2.y)
  1504. );
  1505. },
  1506. random: function() {
  1507. return new Point(Math.random(), Math.random());
  1508. },
  1509. isCollinear: function(x1, y1, x2, y2) {
  1510. return Math.abs(x1 * y2 - y1 * x2)
  1511. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1512. * 1e-8;
  1513. },
  1514. isOrthogonal: function(x1, y1, x2, y2) {
  1515. return Math.abs(x1 * x2 + y1 * y2)
  1516. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1517. * 1e-8;
  1518. }
  1519. }
  1520. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1521. var op = Math[key];
  1522. this[key] = function() {
  1523. return new Point(op(this.x), op(this.y));
  1524. };
  1525. }, {}));
  1526. var LinkedPoint = Point.extend({
  1527. initialize: function Point(x, y, owner, setter) {
  1528. this._x = x;
  1529. this._y = y;
  1530. this._owner = owner;
  1531. this._setter = setter;
  1532. },
  1533. _set: function(x, y, _dontNotify) {
  1534. this._x = x;
  1535. this._y = y;
  1536. if (!_dontNotify)
  1537. this._owner[this._setter](this);
  1538. return this;
  1539. },
  1540. getX: function() {
  1541. return this._x;
  1542. },
  1543. setX: function(x) {
  1544. this._x = x;
  1545. this._owner[this._setter](this);
  1546. },
  1547. getY: function() {
  1548. return this._y;
  1549. },
  1550. setY: function(y) {
  1551. this._y = y;
  1552. this._owner[this._setter](this);
  1553. },
  1554. isSelected: function() {
  1555. return !!(this._owner._selection & this._getSelection());
  1556. },
  1557. setSelected: function(selected) {
  1558. this._owner._changeSelection(this._getSelection(), selected);
  1559. },
  1560. _getSelection: function() {
  1561. return this._setter === 'setPosition' ? 4 : 0;
  1562. }
  1563. });
  1564. var Size = Base.extend({
  1565. _class: 'Size',
  1566. _readIndex: true,
  1567. initialize: function Size(arg0, arg1) {
  1568. var type = typeof arg0,
  1569. reading = this.__read,
  1570. read = 0;
  1571. if (type === 'number') {
  1572. var hasHeight = typeof arg1 === 'number';
  1573. this._set(arg0, hasHeight ? arg1 : arg0);
  1574. if (reading)
  1575. read = hasHeight ? 2 : 1;
  1576. } else if (type === 'undefined' || arg0 === null) {
  1577. this._set(0, 0);
  1578. if (reading)
  1579. read = arg0 === null ? 1 : 0;
  1580. } else {
  1581. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1582. read = 1;
  1583. if (Array.isArray(obj)) {
  1584. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1585. } else if ('width' in obj) {
  1586. this._set(obj.width || 0, obj.height || 0);
  1587. } else if ('x' in obj) {
  1588. this._set(obj.x || 0, obj.y || 0);
  1589. } else {
  1590. this._set(0, 0);
  1591. read = 0;
  1592. }
  1593. }
  1594. if (reading)
  1595. this.__read = read;
  1596. return this;
  1597. },
  1598. set: '#initialize',
  1599. _set: function(width, height) {
  1600. this.width = width;
  1601. this.height = height;
  1602. return this;
  1603. },
  1604. equals: function(size) {
  1605. return size === this || size && (this.width === size.width
  1606. && this.height === size.height
  1607. || Array.isArray(size) && this.width === size[0]
  1608. && this.height === size[1]) || false;
  1609. },
  1610. clone: function() {
  1611. return new Size(this.width, this.height);
  1612. },
  1613. toString: function() {
  1614. var f = Formatter.instance;
  1615. return '{ width: ' + f.number(this.width)
  1616. + ', height: ' + f.number(this.height) + ' }';
  1617. },
  1618. _serialize: function(options) {
  1619. var f = options.formatter;
  1620. return [f.number(this.width),
  1621. f.number(this.height)];
  1622. },
  1623. add: function() {
  1624. var size = Size.read(arguments);
  1625. return new Size(this.width + size.width, this.height + size.height);
  1626. },
  1627. subtract: function() {
  1628. var size = Size.read(arguments);
  1629. return new Size(this.width - size.width, this.height - size.height);
  1630. },
  1631. multiply: function() {
  1632. var size = Size.read(arguments);
  1633. return new Size(this.width * size.width, this.height * size.height);
  1634. },
  1635. divide: function() {
  1636. var size = Size.read(arguments);
  1637. return new Size(this.width / size.width, this.height / size.height);
  1638. },
  1639. modulo: function() {
  1640. var size = Size.read(arguments);
  1641. return new Size(this.width % size.width, this.height % size.height);
  1642. },
  1643. negate: function() {
  1644. return new Size(-this.width, -this.height);
  1645. },
  1646. isZero: function() {
  1647. var isZero = Numerical.isZero;
  1648. return isZero(this.width) && isZero(this.height);
  1649. },
  1650. isNaN: function() {
  1651. return isNaN(this.width) || isNaN(this.height);
  1652. },
  1653. statics: {
  1654. min: function(size1, size2) {
  1655. return new Size(
  1656. Math.min(size1.width, size2.width),
  1657. Math.min(size1.height, size2.height));
  1658. },
  1659. max: function(size1, size2) {
  1660. return new Size(
  1661. Math.max(size1.width, size2.width),
  1662. Math.max(size1.height, size2.height));
  1663. },
  1664. random: function() {
  1665. return new Size(Math.random(), Math.random());
  1666. }
  1667. }
  1668. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1669. var op = Math[key];
  1670. this[key] = function() {
  1671. return new Size(op(this.width), op(this.height));
  1672. };
  1673. }, {}));
  1674. var LinkedSize = Size.extend({
  1675. initialize: function Size(width, height, owner, setter) {
  1676. this._width = width;
  1677. this._height = height;
  1678. this._owner = owner;
  1679. this._setter = setter;
  1680. },
  1681. _set: function(width, height, _dontNotify) {
  1682. this._width = width;
  1683. this._height = height;
  1684. if (!_dontNotify)
  1685. this._owner[this._setter](this);
  1686. return this;
  1687. },
  1688. getWidth: function() {
  1689. return this._width;
  1690. },
  1691. setWidth: function(width) {
  1692. this._width = width;
  1693. this._owner[this._setter](this);
  1694. },
  1695. getHeight: function() {
  1696. return this._height;
  1697. },
  1698. setHeight: function(height) {
  1699. this._height = height;
  1700. this._owner[this._setter](this);
  1701. }
  1702. });
  1703. var Rectangle = Base.extend({
  1704. _class: 'Rectangle',
  1705. _readIndex: true,
  1706. beans: true,
  1707. initialize: function Rectangle(arg0, arg1, arg2, arg3) {
  1708. var args = arguments,
  1709. type = typeof arg0,
  1710. read;
  1711. if (type === 'number') {
  1712. this._set(arg0, arg1, arg2, arg3);
  1713. read = 4;
  1714. } else if (type === 'undefined' || arg0 === null) {
  1715. this._set(0, 0, 0, 0);
  1716. read = arg0 === null ? 1 : 0;
  1717. } else if (args.length === 1) {
  1718. if (Array.isArray(arg0)) {
  1719. this._set.apply(this, arg0);
  1720. read = 1;
  1721. } else if (arg0.x !== undefined || arg0.width !== undefined) {
  1722. this._set(arg0.x || 0, arg0.y || 0,
  1723. arg0.width || 0, arg0.height || 0);
  1724. read = 1;
  1725. } else if (arg0.from === undefined && arg0.to === undefined) {
  1726. this._set(0, 0, 0, 0);
  1727. if (Base.readSupported(args, this)) {
  1728. read = 1;
  1729. }
  1730. }
  1731. }
  1732. if (read === undefined) {
  1733. var frm = Point.readNamed(args, 'from'),
  1734. next = Base.peek(args),
  1735. x = frm.x,
  1736. y = frm.y,
  1737. width,
  1738. height;
  1739. if (next && next.x !== undefined || Base.hasNamed(args, 'to')) {
  1740. var to = Point.readNamed(args, 'to');
  1741. width = to.x - x;
  1742. height = to.y - y;
  1743. if (width < 0) {
  1744. x = to.x;
  1745. width = -width;
  1746. }
  1747. if (height < 0) {
  1748. y = to.y;
  1749. height = -height;
  1750. }
  1751. } else {
  1752. var size = Size.read(args);
  1753. width = size.width;
  1754. height = size.height;
  1755. }
  1756. this._set(x, y, width, height);
  1757. read = args.__index;
  1758. }
  1759. var filtered = args.__filtered;
  1760. if (filtered)
  1761. this.__filtered = filtered;
  1762. if (this.__read)
  1763. this.__read = read;
  1764. return this;
  1765. },
  1766. set: '#initialize',
  1767. _set: function(x, y, width, height) {
  1768. this.x = x;
  1769. this.y = y;
  1770. this.width = width;
  1771. this.height = height;
  1772. return this;
  1773. },
  1774. clone: function() {
  1775. return new Rectangle(this.x, this.y, this.width, this.height);
  1776. },
  1777. equals: function(rect) {
  1778. var rt = Base.isPlainValue(rect)
  1779. ? Rectangle.read(arguments)
  1780. : rect;
  1781. return rt === this
  1782. || rt && this.x === rt.x && this.y === rt.y
  1783. && this.width === rt.width && this.height === rt.height
  1784. || false;
  1785. },
  1786. toString: function() {
  1787. var f = Formatter.instance;
  1788. return '{ x: ' + f.number(this.x)
  1789. + ', y: ' + f.number(this.y)
  1790. + ', width: ' + f.number(this.width)
  1791. + ', height: ' + f.number(this.height)
  1792. + ' }';
  1793. },
  1794. _serialize: function(options) {
  1795. var f = options.formatter;
  1796. return [f.number(this.x),
  1797. f.number(this.y),
  1798. f.number(this.width),
  1799. f.number(this.height)];
  1800. },
  1801. getPoint: function(_dontLink) {
  1802. var ctor = _dontLink ? Point : LinkedPoint;
  1803. return new ctor(this.x, this.y, this, 'setPoint');
  1804. },
  1805. setPoint: function() {
  1806. var point = Point.read(arguments);
  1807. this.x = point.x;
  1808. this.y = point.y;
  1809. },
  1810. getSize: function(_dontLink) {
  1811. var ctor = _dontLink ? Size : LinkedSize;
  1812. return new ctor(this.width, this.height, this, 'setSize');
  1813. },
  1814. _fw: 1,
  1815. _fh: 1,
  1816. setSize: function() {
  1817. var size = Size.read(arguments),
  1818. sx = this._sx,
  1819. sy = this._sy,
  1820. w = size.width,
  1821. h = size.height;
  1822. if (sx) {
  1823. this.x += (this.width - w) * sx;
  1824. }
  1825. if (sy) {
  1826. this.y += (this.height - h) * sy;
  1827. }
  1828. this.width = w;
  1829. this.height = h;
  1830. this._fw = this._fh = 1;
  1831. },
  1832. getLeft: function() {
  1833. return this.x;
  1834. },
  1835. setLeft: function(left) {
  1836. if (!this._fw) {
  1837. var amount = left - this.x;
  1838. this.width -= this._sx === 0.5 ? amount * 2 : amount;
  1839. }
  1840. this.x = left;
  1841. this._sx = this._fw = 0;
  1842. },
  1843. getTop: function() {
  1844. return this.y;
  1845. },
  1846. setTop: function(top) {
  1847. if (!this._fh) {
  1848. var amount = top - this.y;
  1849. this.height -= this._sy === 0.5 ? amount * 2 : amount;
  1850. }
  1851. this.y = top;
  1852. this._sy = this._fh = 0;
  1853. },
  1854. getRight: function() {
  1855. return this.x + this.width;
  1856. },
  1857. setRight: function(right) {
  1858. if (!this._fw) {
  1859. var amount = right - this.x;
  1860. this.width = this._sx === 0.5 ? amount * 2 : amount;
  1861. }
  1862. this.x = right - this.width;
  1863. this._sx = 1;
  1864. this._fw = 0;
  1865. },
  1866. getBottom: function() {
  1867. return this.y + this.height;
  1868. },
  1869. setBottom: function(bottom) {
  1870. if (!this._fh) {
  1871. var amount = bottom - this.y;
  1872. this.height = this._sy === 0.5 ? amount * 2 : amount;
  1873. }
  1874. this.y = bottom - this.height;
  1875. this._sy = 1;
  1876. this._fh = 0;
  1877. },
  1878. getCenterX: function() {
  1879. return this.x + this.width / 2;
  1880. },
  1881. setCenterX: function(x) {
  1882. if (this._fw || this._sx === 0.5) {
  1883. this.x = x - this.width / 2;
  1884. } else {
  1885. if (this._sx) {
  1886. this.x += (x - this.x) * 2 * this._sx;
  1887. }
  1888. this.width = (x - this.x) * 2;
  1889. }
  1890. this._sx = 0.5;
  1891. this._fw = 0;
  1892. },
  1893. getCenterY: function() {
  1894. return this.y + this.height / 2;
  1895. },
  1896. setCenterY: function(y) {
  1897. if (this._fh || this._sy === 0.5) {
  1898. this.y = y - this.height / 2;
  1899. } else {
  1900. if (this._sy) {
  1901. this.y += (y - this.y) * 2 * this._sy;
  1902. }
  1903. this.height = (y - this.y) * 2;
  1904. }
  1905. this._sy = 0.5;
  1906. this._fh = 0;
  1907. },
  1908. getCenter: function(_dontLink) {
  1909. var ctor = _dontLink ? Point : LinkedPoint;
  1910. return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');
  1911. },
  1912. setCenter: function() {
  1913. var point = Point.read(arguments);
  1914. this.setCenterX(point.x);
  1915. this.setCenterY(point.y);
  1916. return this;
  1917. },
  1918. getArea: function() {
  1919. return this.width * this.height;
  1920. },
  1921. isEmpty: function() {
  1922. return this.width === 0 || this.height === 0;
  1923. },
  1924. contains: function(arg) {
  1925. return arg && arg.width !== undefined
  1926. || (Array.isArray(arg) ? arg : arguments).length === 4
  1927. ? this._containsRectangle(Rectangle.read(arguments))
  1928. : this._containsPoint(Point.read(arguments));
  1929. },
  1930. _containsPoint: function(point) {
  1931. var x = point.x,
  1932. y = point.y;
  1933. return x >= this.x && y >= this.y
  1934. && x <= this.x + this.width
  1935. && y <= this.y + this.height;
  1936. },
  1937. _containsRectangle: function(rect) {
  1938. var x = rect.x,
  1939. y = rect.y;
  1940. return x >= this.x && y >= this.y
  1941. && x + rect.width <= this.x + this.width
  1942. && y + rect.height <= this.y + this.height;
  1943. },
  1944. intersects: function() {
  1945. var rect = Rectangle.read(arguments),
  1946. epsilon = Base.read(arguments) || 0;
  1947. return rect.x + rect.width > this.x - epsilon
  1948. && rect.y + rect.height > this.y - epsilon
  1949. && rect.x < this.x + this.width + epsilon
  1950. && rect.y < this.y + this.height + epsilon;
  1951. },
  1952. intersect: function() {
  1953. var rect = Rectangle.read(arguments),
  1954. x1 = Math.max(this.x, rect.x),
  1955. y1 = Math.max(this.y, rect.y),
  1956. x2 = Math.min(this.x + this.width, rect.x + rect.width),
  1957. y2 = Math.min(this.y + this.height, rect.y + rect.height);
  1958. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1959. },
  1960. unite: function() {
  1961. var rect = Rectangle.read(arguments),
  1962. x1 = Math.min(this.x, rect.x),
  1963. y1 = Math.min(this.y, rect.y),
  1964. x2 = Math.max(this.x + this.width, rect.x + rect.width),
  1965. y2 = Math.max(this.y + this.height, rect.y + rect.height);
  1966. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1967. },
  1968. include: function() {
  1969. var point = Point.read(arguments);
  1970. var x1 = Math.min(this.x, point.x),
  1971. y1 = Math.min(this.y, point.y),
  1972. x2 = Math.max(this.x + this.width, point.x),
  1973. y2 = Math.max(this.y + this.height, point.y);
  1974. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1975. },
  1976. expand: function() {
  1977. var amount = Size.read(arguments),
  1978. hor = amount.width,
  1979. ver = amount.height;
  1980. return new Rectangle(this.x - hor / 2, this.y - ver / 2,
  1981. this.width + hor, this.height + ver);
  1982. },
  1983. scale: function(hor, ver) {
  1984. return this.expand(this.width * hor - this.width,
  1985. this.height * (ver === undefined ? hor : ver) - this.height);
  1986. }
  1987. }, Base.each([
  1988. ['Top', 'Left'], ['Top', 'Right'],
  1989. ['Bottom', 'Left'], ['Bottom', 'Right'],
  1990. ['Left', 'Center'], ['Top', 'Center'],
  1991. ['Right', 'Center'], ['Bottom', 'Center']
  1992. ],
  1993. function(parts, index) {
  1994. var part = parts.join(''),
  1995. xFirst = /^[RL]/.test(part);
  1996. if (index >= 4)
  1997. parts[1] += xFirst ? 'Y' : 'X';
  1998. var x = parts[xFirst ? 0 : 1],
  1999. y = parts[xFirst ? 1 : 0],
  2000. getX = 'get' + x,
  2001. getY = 'get' + y,
  2002. setX = 'set' + x,
  2003. setY = 'set' + y,
  2004. get = 'get' + part,
  2005. set = 'set' + part;
  2006. this[get] = function(_dontLink) {
  2007. var ctor = _dontLink ? Point : LinkedPoint;
  2008. return new ctor(this[getX](), this[getY](), this, set);
  2009. };
  2010. this[set] = function() {
  2011. var point = Point.read(arguments);
  2012. this[setX](point.x);
  2013. this[setY](point.y);
  2014. };
  2015. }, {
  2016. beans: true
  2017. }
  2018. ));
  2019. var LinkedRectangle = Rectangle.extend({
  2020. initialize: function Rectangle(x, y, width, height, owner, setter) {
  2021. this._set(x, y, width, height, true);
  2022. this._owner = owner;
  2023. this._setter = setter;
  2024. },
  2025. _set: function(x, y, width, height, _dontNotify) {
  2026. this._x = x;
  2027. this._y = y;
  2028. this._width = width;
  2029. this._height = height;
  2030. if (!_dontNotify)
  2031. this._owner[this._setter](this);
  2032. return this;
  2033. }
  2034. },
  2035. new function() {
  2036. var proto = Rectangle.prototype;
  2037. return Base.each(['x', 'y', 'width', 'height'], function(key) {
  2038. var part = Base.capitalize(key),
  2039. internal = '_' + key;
  2040. this['get' + part] = function() {
  2041. return this[internal];
  2042. };
  2043. this['set' + part] = function(value) {
  2044. this[internal] = value;
  2045. if (!this._dontNotify)
  2046. this._owner[this._setter](this);
  2047. };
  2048. }, Base.each(['Point', 'Size', 'Center',
  2049. 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
  2050. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  2051. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
  2052. function(key) {
  2053. var name = 'set' + key;
  2054. this[name] = function() {
  2055. this._dontNotify = true;
  2056. proto[name].apply(this, arguments);
  2057. this._dontNotify = false;
  2058. this._owner[this._setter](this);
  2059. };
  2060. }, {
  2061. isSelected: function() {
  2062. return !!(this._owner._selection & 2);
  2063. },
  2064. setSelected: function(selected) {
  2065. var owner = this._owner;
  2066. if (owner._changeSelection) {
  2067. owner._changeSelection(2, selected);
  2068. }
  2069. }
  2070. })
  2071. );
  2072. });
  2073. var Matrix = Base.extend({
  2074. _class: 'Matrix',
  2075. initialize: function Matrix(arg, _dontNotify) {
  2076. var args = arguments,
  2077. count = args.length,
  2078. ok = true;
  2079. if (count >= 6) {
  2080. this._set.apply(this, args);
  2081. } else if (count === 1 || count === 2) {
  2082. if (arg instanceof Matrix) {
  2083. this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty,
  2084. _dontNotify);
  2085. } else if (Array.isArray(arg)) {
  2086. this._set.apply(this,
  2087. _dontNotify ? arg.concat([_dontNotify]) : arg);
  2088. } else {
  2089. ok = false;
  2090. }
  2091. } else if (!count) {
  2092. this.reset();
  2093. } else {
  2094. ok = false;
  2095. }
  2096. if (!ok) {
  2097. throw new Error('Unsupported matrix parameters');
  2098. }
  2099. return this;
  2100. },
  2101. set: '#initialize',
  2102. _set: function(a, b, c, d, tx, ty, _dontNotify) {
  2103. this._a = a;
  2104. this._b = b;
  2105. this._c = c;
  2106. this._d = d;
  2107. this._tx = tx;
  2108. this._ty = ty;
  2109. if (!_dontNotify)
  2110. this._changed();
  2111. return this;
  2112. },
  2113. _serialize: function(options, dictionary) {
  2114. return Base.serialize(this.getValues(), options, true, dictionary);
  2115. },
  2116. _changed: function() {
  2117. var owner = this._owner;
  2118. if (owner) {
  2119. if (owner._applyMatrix) {
  2120. owner.transform(null, true);
  2121. } else {
  2122. owner._changed(25);
  2123. }
  2124. }
  2125. },
  2126. clone: function() {
  2127. return new Matrix(this._a, this._b, this._c, this._d,
  2128. this._tx, this._ty);
  2129. },
  2130. equals: function(mx) {
  2131. return mx === this || mx && this._a === mx._a && this._b === mx._b
  2132. && this._c === mx._c && this._d === mx._d
  2133. && this._tx === mx._tx && this._ty === mx._ty;
  2134. },
  2135. toString: function() {
  2136. var f = Formatter.instance;
  2137. return '[[' + [f.number(this._a), f.number(this._c),
  2138. f.number(this._tx)].join(', ') + '], ['
  2139. + [f.number(this._b), f.number(this._d),
  2140. f.number(this._ty)].join(', ') + ']]';
  2141. },
  2142. reset: function(_dontNotify) {
  2143. this._a = this._d = 1;
  2144. this._b = this._c = this._tx = this._ty = 0;
  2145. if (!_dontNotify)
  2146. this._changed();
  2147. return this;
  2148. },
  2149. apply: function(recursively, _setApplyMatrix) {
  2150. var owner = this._owner;
  2151. if (owner) {
  2152. owner.transform(null, Base.pick(recursively, true), _setApplyMatrix);
  2153. return this.isIdentity();
  2154. }
  2155. return false;
  2156. },
  2157. translate: function() {
  2158. var point = Point.read(arguments),
  2159. x = point.x,
  2160. y = point.y;
  2161. this._tx += x * this._a + y * this._c;
  2162. this._ty += x * this._b + y * this._d;
  2163. this._changed();
  2164. return this;
  2165. },
  2166. scale: function() {
  2167. var args = arguments,
  2168. scale = Point.read(args),
  2169. center = Point.read(args, 0, { readNull: true });
  2170. if (center)
  2171. this.translate(center);
  2172. this._a *= scale.x;
  2173. this._b *= scale.x;
  2174. this._c *= scale.y;
  2175. this._d *= scale.y;
  2176. if (center)
  2177. this.translate(center.negate());
  2178. this._changed();
  2179. return this;
  2180. },
  2181. rotate: function(angle ) {
  2182. angle *= Math.PI / 180;
  2183. var center = Point.read(arguments, 1),
  2184. x = center.x,
  2185. y = center.y,
  2186. cos = Math.cos(angle),
  2187. sin = Math.sin(angle),
  2188. tx = x - x * cos + y * sin,
  2189. ty = y - x * sin - y * cos,
  2190. a = this._a,
  2191. b = this._b,
  2192. c = this._c,
  2193. d = this._d;
  2194. this._a = cos * a + sin * c;
  2195. this._b = cos * b + sin * d;
  2196. this._c = -sin * a + cos * c;
  2197. this._d = -sin * b + cos * d;
  2198. this._tx += tx * a + ty * c;
  2199. this._ty += tx * b + ty * d;
  2200. this._changed();
  2201. return this;
  2202. },
  2203. shear: function() {
  2204. var args = arguments,
  2205. shear = Point.read(args),
  2206. center = Point.read(args, 0, { readNull: true });
  2207. if (center)
  2208. this.translate(center);
  2209. var a = this._a,
  2210. b = this._b;
  2211. this._a += shear.y * this._c;
  2212. this._b += shear.y * this._d;
  2213. this._c += shear.x * a;
  2214. this._d += shear.x * b;
  2215. if (center)
  2216. this.translate(center.negate());
  2217. this._changed();
  2218. return this;
  2219. },
  2220. skew: function() {
  2221. var args = arguments,
  2222. skew = Point.read(args),
  2223. center = Point.read(args, 0, { readNull: true }),
  2224. toRadians = Math.PI / 180,
  2225. shear = new Point(Math.tan(skew.x * toRadians),
  2226. Math.tan(skew.y * toRadians));
  2227. return this.shear(shear, center);
  2228. },
  2229. append: function(mx, _dontNotify) {
  2230. if (mx) {
  2231. var a1 = this._a,
  2232. b1 = this._b,
  2233. c1 = this._c,
  2234. d1 = this._d,
  2235. a2 = mx._a,
  2236. b2 = mx._c,
  2237. c2 = mx._b,
  2238. d2 = mx._d,
  2239. tx2 = mx._tx,
  2240. ty2 = mx._ty;
  2241. this._a = a2 * a1 + c2 * c1;
  2242. this._c = b2 * a1 + d2 * c1;
  2243. this._b = a2 * b1 + c2 * d1;
  2244. this._d = b2 * b1 + d2 * d1;
  2245. this._tx += tx2 * a1 + ty2 * c1;
  2246. this._ty += tx2 * b1 + ty2 * d1;
  2247. if (!_dontNotify)
  2248. this._changed();
  2249. }
  2250. return this;
  2251. },
  2252. prepend: function(mx, _dontNotify) {
  2253. if (mx) {
  2254. var a1 = this._a,
  2255. b1 = this._b,
  2256. c1 = this._c,
  2257. d1 = this._d,
  2258. tx1 = this._tx,
  2259. ty1 = this._ty,
  2260. a2 = mx._a,
  2261. b2 = mx._c,
  2262. c2 = mx._b,
  2263. d2 = mx._d,
  2264. tx2 = mx._tx,
  2265. ty2 = mx._ty;
  2266. this._a = a2 * a1 + b2 * b1;
  2267. this._c = a2 * c1 + b2 * d1;
  2268. this._b = c2 * a1 + d2 * b1;
  2269. this._d = c2 * c1 + d2 * d1;
  2270. this._tx = a2 * tx1 + b2 * ty1 + tx2;
  2271. this._ty = c2 * tx1 + d2 * ty1 + ty2;
  2272. if (!_dontNotify)
  2273. this._changed();
  2274. }
  2275. return this;
  2276. },
  2277. appended: function(mx) {
  2278. return this.clone().append(mx);
  2279. },
  2280. prepended: function(mx) {
  2281. return this.clone().prepend(mx);
  2282. },
  2283. invert: function() {
  2284. var a = this._a,
  2285. b = this._b,
  2286. c = this._c,
  2287. d = this._d,
  2288. tx = this._tx,
  2289. ty = this._ty,
  2290. det = a * d - b * c,
  2291. res = null;
  2292. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2293. this._a = d / det;
  2294. this._b = -b / det;
  2295. this._c = -c / det;
  2296. this._d = a / det;
  2297. this._tx = (c * ty - d * tx) / det;
  2298. this._ty = (b * tx - a * ty) / det;
  2299. res = this;
  2300. }
  2301. return res;
  2302. },
  2303. inverted: function() {
  2304. return this.clone().invert();
  2305. },
  2306. concatenate: '#append',
  2307. preConcatenate: '#prepend',
  2308. chain: '#appended',
  2309. _shiftless: function() {
  2310. return new Matrix(this._a, this._b, this._c, this._d, 0, 0);
  2311. },
  2312. _orNullIfIdentity: function() {
  2313. return this.isIdentity() ? null : this;
  2314. },
  2315. isIdentity: function() {
  2316. return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1
  2317. && this._tx === 0 && this._ty === 0;
  2318. },
  2319. isInvertible: function() {
  2320. var det = this._a * this._d - this._c * this._b;
  2321. return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty);
  2322. },
  2323. isSingular: function() {
  2324. return !this.isInvertible();
  2325. },
  2326. transform: function( src, dst, count) {
  2327. return arguments.length < 3
  2328. ? this._transformPoint(Point.read(arguments))
  2329. : this._transformCoordinates(src, dst, count);
  2330. },
  2331. _transformPoint: function(point, dest, _dontNotify) {
  2332. var x = point.x,
  2333. y = point.y;
  2334. if (!dest)
  2335. dest = new Point();
  2336. return dest._set(
  2337. x * this._a + y * this._c + this._tx,
  2338. x * this._b + y * this._d + this._ty,
  2339. _dontNotify);
  2340. },
  2341. _transformCoordinates: function(src, dst, count) {
  2342. for (var i = 0, max = 2 * count; i < max; i += 2) {
  2343. var x = src[i],
  2344. y = src[i + 1];
  2345. dst[i] = x * this._a + y * this._c + this._tx;
  2346. dst[i + 1] = x * this._b + y * this._d + this._ty;
  2347. }
  2348. return dst;
  2349. },
  2350. _transformCorners: function(rect) {
  2351. var x1 = rect.x,
  2352. y1 = rect.y,
  2353. x2 = x1 + rect.width,
  2354. y2 = y1 + rect.height,
  2355. coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
  2356. return this._transformCoordinates(coords, coords, 4);
  2357. },
  2358. _transformBounds: function(bounds, dest, _dontNotify) {
  2359. var coords = this._transformCorners(bounds),
  2360. min = coords.slice(0, 2),
  2361. max = min.slice();
  2362. for (var i = 2; i < 8; i++) {
  2363. var val = coords[i],
  2364. j = i & 1;
  2365. if (val < min[j]) {
  2366. min[j] = val;
  2367. } else if (val > max[j]) {
  2368. max[j] = val;
  2369. }
  2370. }
  2371. if (!dest)
  2372. dest = new Rectangle();
  2373. return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1],
  2374. _dontNotify);
  2375. },
  2376. inverseTransform: function() {
  2377. return this._inverseTransform(Point.read(arguments));
  2378. },
  2379. _inverseTransform: function(point, dest, _dontNotify) {
  2380. var a = this._a,
  2381. b = this._b,
  2382. c = this._c,
  2383. d = this._d,
  2384. tx = this._tx,
  2385. ty = this._ty,
  2386. det = a * d - b * c,
  2387. res = null;
  2388. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2389. var x = point.x - this._tx,
  2390. y = point.y - this._ty;
  2391. if (!dest)
  2392. dest = new Point();
  2393. res = dest._set(
  2394. (x * d - y * c) / det,
  2395. (y * a - x * b) / det,
  2396. _dontNotify);
  2397. }
  2398. return res;
  2399. },
  2400. decompose: function() {
  2401. var a = this._a,
  2402. b = this._b,
  2403. c = this._c,
  2404. d = this._d,
  2405. det = a * d - b * c,
  2406. sqrt = Math.sqrt,
  2407. atan2 = Math.atan2,
  2408. degrees = 180 / Math.PI,
  2409. rotate,
  2410. scale,
  2411. skew;
  2412. if (a !== 0 || b !== 0) {
  2413. var r = sqrt(a * a + b * b);
  2414. rotate = Math.acos(a / r) * (b > 0 ? 1 : -1);
  2415. scale = [r, det / r];
  2416. skew = [atan2(a * c + b * d, r * r), 0];
  2417. } else if (c !== 0 || d !== 0) {
  2418. var s = sqrt(c * c + d * d);
  2419. rotate = Math.asin(c / s) * (d > 0 ? 1 : -1);
  2420. scale = [det / s, s];
  2421. skew = [0, atan2(a * c + b * d, s * s)];
  2422. } else {
  2423. rotate = 0;
  2424. skew = scale = [0, 0];
  2425. }
  2426. return {
  2427. translation: this.getTranslation(),
  2428. rotation: rotate * degrees,
  2429. scaling: new Point(scale),
  2430. skewing: new Point(skew[0] * degrees, skew[1] * degrees)
  2431. };
  2432. },
  2433. getValues: function() {
  2434. return [ this._a, this._b, this._c, this._d, this._tx, this._ty ];
  2435. },
  2436. getTranslation: function() {
  2437. return new Point(this._tx, this._ty);
  2438. },
  2439. getScaling: function() {
  2440. return this.decompose().scaling;
  2441. },
  2442. getRotation: function() {
  2443. return this.decompose().rotation;
  2444. },
  2445. applyToContext: function(ctx) {
  2446. if (!this.isIdentity()) {
  2447. ctx.transform(this._a, this._b, this._c, this._d,
  2448. this._tx, this._ty);
  2449. }
  2450. }
  2451. }, Base.each(['a', 'b', 'c', 'd', 'tx', 'ty'], function(key) {
  2452. var part = Base.capitalize(key),
  2453. prop = '_' + key;
  2454. this['get' + part] = function() {
  2455. return this[prop];
  2456. };
  2457. this['set' + part] = function(value) {
  2458. this[prop] = value;
  2459. this._changed();
  2460. };
  2461. }, {}));
  2462. var Line = Base.extend({
  2463. _class: 'Line',
  2464. initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
  2465. var asVector = false;
  2466. if (arguments.length >= 4) {
  2467. this._px = arg0;
  2468. this._py = arg1;
  2469. this._vx = arg2;
  2470. this._vy = arg3;
  2471. asVector = arg4;
  2472. } else {
  2473. this._px = arg0.x;
  2474. this._py = arg0.y;
  2475. this._vx = arg1.x;
  2476. this._vy = arg1.y;
  2477. asVector = arg2;
  2478. }
  2479. if (!asVector) {
  2480. this._vx -= this._px;
  2481. this._vy -= this._py;
  2482. }
  2483. },
  2484. getPoint: function() {
  2485. return new Point(this._px, this._py);
  2486. },
  2487. getVector: function() {
  2488. return new Point(this._vx, this._vy);
  2489. },
  2490. getLength: function() {
  2491. return this.getVector().getLength();
  2492. },
  2493. intersect: function(line, isInfinite) {
  2494. return Line.intersect(
  2495. this._px, this._py, this._vx, this._vy,
  2496. line._px, line._py, line._vx, line._vy,
  2497. true, isInfinite);
  2498. },
  2499. getSide: function(point, isInfinite) {
  2500. return Line.getSide(
  2501. this._px, this._py, this._vx, this._vy,
  2502. point.x, point.y, true, isInfinite);
  2503. },
  2504. getDistance: function(point) {
  2505. return Math.abs(this.getSignedDistance(point));
  2506. },
  2507. getSignedDistance: function(point) {
  2508. return Line.getSignedDistance(this._px, this._py, this._vx, this._vy,
  2509. point.x, point.y, true);
  2510. },
  2511. isCollinear: function(line) {
  2512. return Point.isCollinear(this._vx, this._vy, line._vx, line._vy);
  2513. },
  2514. isOrthogonal: function(line) {
  2515. return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy);
  2516. },
  2517. statics: {
  2518. intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector,
  2519. isInfinite) {
  2520. if (!asVector) {
  2521. v1x -= p1x;
  2522. v1y -= p1y;
  2523. v2x -= p2x;
  2524. v2y -= p2y;
  2525. }
  2526. var cross = v1x * v2y - v1y * v2x;
  2527. if (!Numerical.isMachineZero(cross)) {
  2528. var dx = p1x - p2x,
  2529. dy = p1y - p2y,
  2530. u1 = (v2x * dy - v2y * dx) / cross,
  2531. u2 = (v1x * dy - v1y * dx) / cross,
  2532. epsilon = 1e-12,
  2533. uMin = -epsilon,
  2534. uMax = 1 + epsilon;
  2535. if (isInfinite
  2536. || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) {
  2537. if (!isInfinite) {
  2538. u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1;
  2539. }
  2540. return new Point(
  2541. p1x + u1 * v1x,
  2542. p1y + u1 * v1y);
  2543. }
  2544. }
  2545. },
  2546. getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) {
  2547. if (!asVector) {
  2548. vx -= px;
  2549. vy -= py;
  2550. }
  2551. var v2x = x - px,
  2552. v2y = y - py,
  2553. ccw = v2x * vy - v2y * vx;
  2554. if (!isInfinite && Numerical.isMachineZero(ccw)) {
  2555. ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy);
  2556. if (ccw >= 0 && ccw <= 1)
  2557. ccw = 0;
  2558. }
  2559. return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
  2560. },
  2561. getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
  2562. if (!asVector) {
  2563. vx -= px;
  2564. vy -= py;
  2565. }
  2566. return vx === 0 ? (vy > 0 ? x - px : px - x)
  2567. : vy === 0 ? (vx < 0 ? y - py : py - y)
  2568. : ((x - px) * vy - (y - py) * vx) / (
  2569. vy > vx
  2570. ? vy * Math.sqrt(1 + (vx * vx) / (vy * vy))
  2571. : vx * Math.sqrt(1 + (vy * vy) / (vx * vx))
  2572. );
  2573. },
  2574. getDistance: function(px, py, vx, vy, x, y, asVector) {
  2575. return Math.abs(
  2576. Line.getSignedDistance(px, py, vx, vy, x, y, asVector));
  2577. }
  2578. }
  2579. });
  2580. var Project = PaperScopeItem.extend({
  2581. _class: 'Project',
  2582. _list: 'projects',
  2583. _reference: 'project',
  2584. _compactSerialize: true,
  2585. initialize: function Project(element) {
  2586. PaperScopeItem.call(this, true);
  2587. this._children = [];
  2588. this._namedChildren = {};
  2589. this._activeLayer = null;
  2590. this._currentStyle = new Style(null, null, this);
  2591. this._view = View.create(this,
  2592. element || CanvasProvider.getCanvas(1, 1));
  2593. this._selectionItems = {};
  2594. this._selectionCount = 0;
  2595. this._updateVersion = 0;
  2596. },
  2597. _serialize: function(options, dictionary) {
  2598. return Base.serialize(this._children, options, true, dictionary);
  2599. },
  2600. _changed: function(flags, item) {
  2601. if (flags & 1) {
  2602. var view = this._view;
  2603. if (view) {
  2604. view._needsUpdate = true;
  2605. if (!view._requested && view._autoUpdate)
  2606. view.requestUpdate();
  2607. }
  2608. }
  2609. var changes = this._changes;
  2610. if (changes && item) {
  2611. var changesById = this._changesById,
  2612. id = item._id,
  2613. entry = changesById[id];
  2614. if (entry) {
  2615. entry.flags |= flags;
  2616. } else {
  2617. changes.push(changesById[id] = { item: item, flags: flags });
  2618. }
  2619. }
  2620. },
  2621. clear: function() {
  2622. var children = this._children;
  2623. for (var i = children.length - 1; i >= 0; i--)
  2624. children[i].remove();
  2625. },
  2626. isEmpty: function() {
  2627. return !this._children.length;
  2628. },
  2629. remove: function remove() {
  2630. if (!remove.base.call(this))
  2631. return false;
  2632. if (this._view)
  2633. this._view.remove();
  2634. return true;
  2635. },
  2636. getView: function() {
  2637. return this._view;
  2638. },
  2639. getCurrentStyle: function() {
  2640. return this._currentStyle;
  2641. },
  2642. setCurrentStyle: function(style) {
  2643. this._currentStyle.set(style);
  2644. },
  2645. getIndex: function() {
  2646. return this._index;
  2647. },
  2648. getOptions: function() {
  2649. return this._scope.settings;
  2650. },
  2651. getLayers: function() {
  2652. return this._children;
  2653. },
  2654. getActiveLayer: function() {
  2655. return this._activeLayer || new Layer({ project: this, insert: true });
  2656. },
  2657. getSymbolDefinitions: function() {
  2658. var definitions = [],
  2659. ids = {};
  2660. this.getItems({
  2661. class: SymbolItem,
  2662. match: function(item) {
  2663. var definition = item._definition,
  2664. id = definition._id;
  2665. if (!ids[id]) {
  2666. ids[id] = true;
  2667. definitions.push(definition);
  2668. }
  2669. return false;
  2670. }
  2671. });
  2672. return definitions;
  2673. },
  2674. getSymbols: 'getSymbolDefinitions',
  2675. getSelectedItems: function() {
  2676. var selectionItems = this._selectionItems,
  2677. items = [];
  2678. for (var id in selectionItems) {
  2679. var item = selectionItems[id],
  2680. selection = item._selection;
  2681. if ((selection & 1) && item.isInserted()) {
  2682. items.push(item);
  2683. } else if (!selection) {
  2684. this._updateSelection(item);
  2685. }
  2686. }
  2687. return items;
  2688. },
  2689. _updateSelection: function(item) {
  2690. var id = item._id,
  2691. selectionItems = this._selectionItems;
  2692. if (item._selection) {
  2693. if (selectionItems[id] !== item) {
  2694. this._selectionCount++;
  2695. selectionItems[id] = item;
  2696. }
  2697. } else if (selectionItems[id] === item) {
  2698. this._selectionCount--;
  2699. delete selectionItems[id];
  2700. }
  2701. },
  2702. selectAll: function() {
  2703. var children = this._children;
  2704. for (var i = 0, l = children.length; i < l; i++)
  2705. children[i].setFullySelected(true);
  2706. },
  2707. deselectAll: function() {
  2708. var selectionItems = this._selectionItems;
  2709. for (var i in selectionItems)
  2710. selectionItems[i].setFullySelected(false);
  2711. },
  2712. addLayer: function(layer) {
  2713. return this.insertLayer(undefined, layer);
  2714. },
  2715. insertLayer: function(index, layer) {
  2716. if (layer instanceof Layer) {
  2717. layer._remove(false, true);
  2718. Base.splice(this._children, [layer], index, 0);
  2719. layer._setProject(this, true);
  2720. var name = layer._name;
  2721. if (name)
  2722. layer.setName(name);
  2723. if (this._changes)
  2724. layer._changed(5);
  2725. if (!this._activeLayer)
  2726. this._activeLayer = layer;
  2727. } else {
  2728. layer = null;
  2729. }
  2730. return layer;
  2731. },
  2732. _insertItem: function(index, item, _created) {
  2733. item = this.insertLayer(index, item)
  2734. || (this._activeLayer || this._insertItem(undefined,
  2735. new Layer(Item.NO_INSERT), true))
  2736. .insertChild(index, item);
  2737. if (_created && item.activate)
  2738. item.activate();
  2739. return item;
  2740. },
  2741. getItems: function(options) {
  2742. return Item._getItems(this, options);
  2743. },
  2744. getItem: function(options) {
  2745. return Item._getItems(this, options, null, null, true)[0] || null;
  2746. },
  2747. importJSON: function(json) {
  2748. this.activate();
  2749. var layer = this._activeLayer;
  2750. return Base.importJSON(json, layer && layer.isEmpty() && layer);
  2751. },
  2752. removeOn: function(type) {
  2753. var sets = this._removeSets;
  2754. if (sets) {
  2755. if (type === 'mouseup')
  2756. sets.mousedrag = null;
  2757. var set = sets[type];
  2758. if (set) {
  2759. for (var id in set) {
  2760. var item = set[id];
  2761. for (var key in sets) {
  2762. var other = sets[key];
  2763. if (other && other != set)
  2764. delete other[item._id];
  2765. }
  2766. item.remove();
  2767. }
  2768. sets[type] = null;
  2769. }
  2770. }
  2771. },
  2772. draw: function(ctx, matrix, pixelRatio) {
  2773. this._updateVersion++;
  2774. ctx.save();
  2775. matrix.applyToContext(ctx);
  2776. var children = this._children,
  2777. param = new Base({
  2778. offset: new Point(0, 0),
  2779. pixelRatio: pixelRatio,
  2780. viewMatrix: matrix.isIdentity() ? null : matrix,
  2781. matrices: [new Matrix()],
  2782. updateMatrix: true
  2783. });
  2784. for (var i = 0, l = children.length; i < l; i++) {
  2785. children[i].draw(ctx, param);
  2786. }
  2787. ctx.restore();
  2788. if (this._selectionCount > 0) {
  2789. ctx.save();
  2790. ctx.strokeWidth = 1;
  2791. var items = this._selectionItems,
  2792. size = this._scope.settings.handleSize,
  2793. version = this._updateVersion;
  2794. for (var id in items) {
  2795. items[id]._drawSelection(ctx, matrix, size, items, version);
  2796. }
  2797. ctx.restore();
  2798. }
  2799. }
  2800. });
  2801. var Item = Base.extend(Emitter, {
  2802. statics: {
  2803. extend: function extend(src) {
  2804. if (src._serializeFields)
  2805. src._serializeFields = Base.set({},
  2806. this.prototype._serializeFields, src._serializeFields);
  2807. return extend.base.apply(this, arguments);
  2808. },
  2809. NO_INSERT: { insert: false }
  2810. },
  2811. _class: 'Item',
  2812. _name: null,
  2813. _applyMatrix: true,
  2814. _canApplyMatrix: true,
  2815. _canScaleStroke: false,
  2816. _pivot: null,
  2817. _visible: true,
  2818. _blendMode: 'normal',
  2819. _opacity: 1,
  2820. _locked: false,
  2821. _guide: false,
  2822. _clipMask: false,
  2823. _selection: 0,
  2824. _selectBounds: true,
  2825. _selectChildren: false,
  2826. _serializeFields: {
  2827. name: null,
  2828. applyMatrix: null,
  2829. matrix: new Matrix(),
  2830. pivot: null,
  2831. visible: true,
  2832. blendMode: 'normal',
  2833. opacity: 1,
  2834. locked: false,
  2835. guide: false,
  2836. clipMask: false,
  2837. selected: false,
  2838. data: {}
  2839. },
  2840. _prioritize: ['applyMatrix']
  2841. },
  2842. new function() {
  2843. var handlers = ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
  2844. 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'];
  2845. return Base.each(handlers,
  2846. function(name) {
  2847. this._events[name] = {
  2848. install: function(type) {
  2849. this.getView()._countItemEvent(type, 1);
  2850. },
  2851. uninstall: function(type) {
  2852. this.getView()._countItemEvent(type, -1);
  2853. }
  2854. };
  2855. }, {
  2856. _events: {
  2857. onFrame: {
  2858. install: function() {
  2859. this.getView()._animateItem(this, true);
  2860. },
  2861. uninstall: function() {
  2862. this.getView()._animateItem(this, false);
  2863. }
  2864. },
  2865. onLoad: {},
  2866. onError: {}
  2867. },
  2868. statics: {
  2869. _itemHandlers: handlers
  2870. }
  2871. }
  2872. );
  2873. }, {
  2874. initialize: function Item() {
  2875. },
  2876. _initialize: function(props, point) {
  2877. var hasProps = props && Base.isPlainObject(props),
  2878. internal = hasProps && props.internal === true,
  2879. matrix = this._matrix = new Matrix(),
  2880. project = hasProps && props.project || paper.project,
  2881. settings = paper.settings;
  2882. this._id = internal ? null : UID.get();
  2883. this._parent = this._index = null;
  2884. this._applyMatrix = this._canApplyMatrix && settings.applyMatrix;
  2885. if (point)
  2886. matrix.translate(point);
  2887. matrix._owner = this;
  2888. this._style = new Style(project._currentStyle, this, project);
  2889. if (internal || hasProps && props.insert == false
  2890. || !settings.insertItems && !(hasProps && props.insert === true)) {
  2891. this._setProject(project);
  2892. } else {
  2893. (hasProps && props.parent || project)
  2894. ._insertItem(undefined, this, true);
  2895. }
  2896. if (hasProps && props !== Item.NO_INSERT) {
  2897. this.set(props, {
  2898. internal: true, insert: true, project: true, parent: true
  2899. });
  2900. }
  2901. return hasProps;
  2902. },
  2903. _serialize: function(options, dictionary) {
  2904. var props = {},
  2905. that = this;
  2906. function serialize(fields) {
  2907. for (var key in fields) {
  2908. var value = that[key];
  2909. if (!Base.equals(value, key === 'leading'
  2910. ? fields.fontSize * 1.2 : fields[key])) {
  2911. props[key] = Base.serialize(value, options,
  2912. key !== 'data', dictionary);
  2913. }
  2914. }
  2915. }
  2916. serialize(this._serializeFields);
  2917. if (!(this instanceof Group))
  2918. serialize(this._style._defaults);
  2919. return [ this._class, props ];
  2920. },
  2921. _changed: function(flags) {
  2922. var symbol = this._symbol,
  2923. cacheParent = this._parent || symbol,
  2924. project = this._project;
  2925. if (flags & 8) {
  2926. this._bounds = this._position = this._decomposed = undefined;
  2927. }
  2928. if (flags & 16) {
  2929. this._globalMatrix = undefined;
  2930. }
  2931. if (cacheParent
  2932. && (flags & 72)) {
  2933. Item._clearBoundsCache(cacheParent);
  2934. }
  2935. if (flags & 2) {
  2936. Item._clearBoundsCache(this);
  2937. }
  2938. if (project)
  2939. project._changed(flags, this);
  2940. if (symbol)
  2941. symbol._changed(flags);
  2942. },
  2943. getId: function() {
  2944. return this._id;
  2945. },
  2946. getName: function() {
  2947. return this._name;
  2948. },
  2949. setName: function(name) {
  2950. if (this._name)
  2951. this._removeNamed();
  2952. if (name === (+name) + '')
  2953. throw new Error(
  2954. 'Names consisting only of numbers are not supported.');
  2955. var owner = this._getOwner();
  2956. if (name && owner) {
  2957. var children = owner._children,
  2958. namedChildren = owner._namedChildren;
  2959. (namedChildren[name] = namedChildren[name] || []).push(this);
  2960. if (!(name in children))
  2961. children[name] = this;
  2962. }
  2963. this._name = name || undefined;
  2964. this._changed(256);
  2965. },
  2966. getStyle: function() {
  2967. return this._style;
  2968. },
  2969. setStyle: function(style) {
  2970. this.getStyle().set(style);
  2971. }
  2972. }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
  2973. function(name) {
  2974. var part = Base.capitalize(name),
  2975. key = '_' + name,
  2976. flags = {
  2977. locked: 256,
  2978. visible: 265
  2979. };
  2980. this['get' + part] = function() {
  2981. return this[key];
  2982. };
  2983. this['set' + part] = function(value) {
  2984. if (value != this[key]) {
  2985. this[key] = value;
  2986. this._changed(flags[name] || 257);
  2987. }
  2988. };
  2989. },
  2990. {}), {
  2991. beans: true,
  2992. getSelection: function() {
  2993. return this._selection;
  2994. },
  2995. setSelection: function(selection) {
  2996. if (selection !== this._selection) {
  2997. this._selection = selection;
  2998. var project = this._project;
  2999. if (project) {
  3000. project._updateSelection(this);
  3001. this._changed(257);
  3002. }
  3003. }
  3004. },
  3005. _changeSelection: function(flag, selected) {
  3006. var selection = this._selection;
  3007. this.setSelection(selected ? selection | flag : selection & ~flag);
  3008. },
  3009. isSelected: function() {
  3010. if (this._selectChildren) {
  3011. var children = this._children;
  3012. for (var i = 0, l = children.length; i < l; i++)
  3013. if (children[i].isSelected())
  3014. return true;
  3015. }
  3016. return !!(this._selection & 1);
  3017. },
  3018. setSelected: function(selected) {
  3019. if (this._selectChildren) {
  3020. var children = this._children;
  3021. for (var i = 0, l = children.length; i < l; i++)
  3022. children[i].setSelected(selected);
  3023. }
  3024. this._changeSelection(1, selected);
  3025. },
  3026. isFullySelected: function() {
  3027. var children = this._children,
  3028. selected = !!(this._selection & 1);
  3029. if (children && selected) {
  3030. for (var i = 0, l = children.length; i < l; i++)
  3031. if (!children[i].isFullySelected())
  3032. return false;
  3033. return true;
  3034. }
  3035. return selected;
  3036. },
  3037. setFullySelected: function(selected) {
  3038. var children = this._children;
  3039. if (children) {
  3040. for (var i = 0, l = children.length; i < l; i++)
  3041. children[i].setFullySelected(selected);
  3042. }
  3043. this._changeSelection(1, selected);
  3044. },
  3045. isClipMask: function() {
  3046. return this._clipMask;
  3047. },
  3048. setClipMask: function(clipMask) {
  3049. if (this._clipMask != (clipMask = !!clipMask)) {
  3050. this._clipMask = clipMask;
  3051. if (clipMask) {
  3052. this.setFillColor(null);
  3053. this.setStrokeColor(null);
  3054. }
  3055. this._changed(257);
  3056. if (this._parent)
  3057. this._parent._changed(2048);
  3058. }
  3059. },
  3060. getData: function() {
  3061. if (!this._data)
  3062. this._data = {};
  3063. return this._data;
  3064. },
  3065. setData: function(data) {
  3066. this._data = data;
  3067. },
  3068. getPosition: function(_dontLink) {
  3069. var ctor = _dontLink ? Point : LinkedPoint;
  3070. var position = this._position ||
  3071. (this._position = this._getPositionFromBounds());
  3072. return new ctor(position.x, position.y, this, 'setPosition');
  3073. },
  3074. setPosition: function() {
  3075. this.translate(Point.read(arguments).subtract(this.getPosition(true)));
  3076. },
  3077. _getPositionFromBounds: function(bounds) {
  3078. return this._pivot
  3079. ? this._matrix._transformPoint(this._pivot)
  3080. : (bounds || this.getBounds()).getCenter(true);
  3081. },
  3082. getPivot: function() {
  3083. var pivot = this._pivot;
  3084. return pivot
  3085. ? new LinkedPoint(pivot.x, pivot.y, this, 'setPivot')
  3086. : null;
  3087. },
  3088. setPivot: function() {
  3089. this._pivot = Point.read(arguments, 0, { clone: true, readNull: true });
  3090. this._position = undefined;
  3091. }
  3092. }, Base.each({
  3093. getStrokeBounds: { stroke: true },
  3094. getHandleBounds: { handle: true },
  3095. getInternalBounds: { internal: true }
  3096. },
  3097. function(options, key) {
  3098. this[key] = function(matrix) {
  3099. return this.getBounds(matrix, options);
  3100. };
  3101. },
  3102. {
  3103. beans: true,
  3104. getBounds: function(matrix, options) {
  3105. var hasMatrix = options || matrix instanceof Matrix,
  3106. opts = Base.set({}, hasMatrix ? options : matrix,
  3107. this._boundsOptions);
  3108. if (!opts.stroke || this.getStrokeScaling())
  3109. opts.cacheItem = this;
  3110. var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect;
  3111. return !arguments.length
  3112. ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height,
  3113. this, 'setBounds')
  3114. : rect;
  3115. },
  3116. setBounds: function() {
  3117. var rect = Rectangle.read(arguments),
  3118. bounds = this.getBounds(),
  3119. _matrix = this._matrix,
  3120. matrix = new Matrix(),
  3121. center = rect.getCenter();
  3122. matrix.translate(center);
  3123. if (rect.width != bounds.width || rect.height != bounds.height) {
  3124. if (!_matrix.isInvertible()) {
  3125. _matrix.set(_matrix._backup
  3126. || new Matrix().translate(_matrix.getTranslation()));
  3127. bounds = this.getBounds();
  3128. }
  3129. matrix.scale(
  3130. bounds.width !== 0 ? rect.width / bounds.width : 0,
  3131. bounds.height !== 0 ? rect.height / bounds.height : 0);
  3132. }
  3133. center = bounds.getCenter();
  3134. matrix.translate(-center.x, -center.y);
  3135. this.transform(matrix);
  3136. },
  3137. _getBounds: function(matrix, options) {
  3138. var children = this._children;
  3139. if (!children || !children.length)
  3140. return new Rectangle();
  3141. Item._updateBoundsCache(this, options.cacheItem);
  3142. return Item._getBounds(children, matrix, options);
  3143. },
  3144. _getBoundsCacheKey: function(options, internal) {
  3145. return [
  3146. options.stroke ? 1 : 0,
  3147. options.handle ? 1 : 0,
  3148. internal ? 1 : 0
  3149. ].join('');
  3150. },
  3151. _getCachedBounds: function(matrix, options, noInternal) {
  3152. matrix = matrix && matrix._orNullIfIdentity();
  3153. var internal = options.internal && !noInternal,
  3154. cacheItem = options.cacheItem,
  3155. _matrix = internal ? null : this._matrix._orNullIfIdentity(),
  3156. cacheKey = cacheItem && (!matrix || matrix.equals(_matrix))
  3157. && this._getBoundsCacheKey(options, internal),
  3158. bounds = this._bounds;
  3159. Item._updateBoundsCache(this._parent || this._symbol, cacheItem);
  3160. if (cacheKey && bounds && cacheKey in bounds) {
  3161. var cached = bounds[cacheKey];
  3162. return {
  3163. rect: cached.rect.clone(),
  3164. nonscaling: cached.nonscaling
  3165. };
  3166. }
  3167. var res = this._getBounds(matrix || _matrix, options),
  3168. rect = res.rect || res,
  3169. style = this._style,
  3170. nonscaling = res.nonscaling || style.hasStroke()
  3171. && !style.getStrokeScaling();
  3172. if (cacheKey) {
  3173. if (!bounds) {
  3174. this._bounds = bounds = {};
  3175. }
  3176. var cached = bounds[cacheKey] = {
  3177. rect: rect.clone(),
  3178. nonscaling: nonscaling,
  3179. internal: internal
  3180. };
  3181. }
  3182. return {
  3183. rect: rect,
  3184. nonscaling: nonscaling
  3185. };
  3186. },
  3187. _getStrokeMatrix: function(matrix, options) {
  3188. var parent = this.getStrokeScaling() ? null
  3189. : options && options.internal ? this
  3190. : this._parent || this._symbol && this._symbol._item,
  3191. mx = parent ? parent.getViewMatrix().invert() : matrix;
  3192. return mx && mx._shiftless();
  3193. },
  3194. statics: {
  3195. _updateBoundsCache: function(parent, item) {
  3196. if (parent && item) {
  3197. var id = item._id,
  3198. ref = parent._boundsCache = parent._boundsCache || {
  3199. ids: {},
  3200. list: []
  3201. };
  3202. if (!ref.ids[id]) {
  3203. ref.list.push(item);
  3204. ref.ids[id] = item;
  3205. }
  3206. }
  3207. },
  3208. _clearBoundsCache: function(item) {
  3209. var cache = item._boundsCache;
  3210. if (cache) {
  3211. item._bounds = item._position = item._boundsCache = undefined;
  3212. for (var i = 0, list = cache.list, l = list.length; i < l; i++){
  3213. var other = list[i];
  3214. if (other !== item) {
  3215. other._bounds = other._position = undefined;
  3216. if (other._boundsCache)
  3217. Item._clearBoundsCache(other);
  3218. }
  3219. }
  3220. }
  3221. },
  3222. _getBounds: function(items, matrix, options) {
  3223. var x1 = Infinity,
  3224. x2 = -x1,
  3225. y1 = x1,
  3226. y2 = x2,
  3227. nonscaling = false;
  3228. options = options || {};
  3229. for (var i = 0, l = items.length; i < l; i++) {
  3230. var item = items[i];
  3231. if (item._visible && !item.isEmpty(true)) {
  3232. var bounds = item._getCachedBounds(
  3233. matrix && matrix.appended(item._matrix), options, true),
  3234. rect = bounds.rect;
  3235. x1 = Math.min(rect.x, x1);
  3236. y1 = Math.min(rect.y, y1);
  3237. x2 = Math.max(rect.x + rect.width, x2);
  3238. y2 = Math.max(rect.y + rect.height, y2);
  3239. if (bounds.nonscaling)
  3240. nonscaling = true;
  3241. }
  3242. }
  3243. return {
  3244. rect: isFinite(x1)
  3245. ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
  3246. : new Rectangle(),
  3247. nonscaling: nonscaling
  3248. };
  3249. }
  3250. }
  3251. }), {
  3252. beans: true,
  3253. _decompose: function() {
  3254. return this._applyMatrix
  3255. ? null
  3256. : this._decomposed || (this._decomposed = this._matrix.decompose());
  3257. },
  3258. getRotation: function() {
  3259. var decomposed = this._decompose();
  3260. return decomposed ? decomposed.rotation : 0;
  3261. },
  3262. setRotation: function(rotation) {
  3263. var current = this.getRotation();
  3264. if (current != null && rotation != null) {
  3265. var decomposed = this._decomposed;
  3266. this.rotate(rotation - current);
  3267. if (decomposed) {
  3268. decomposed.rotation = rotation;
  3269. this._decomposed = decomposed;
  3270. }
  3271. }
  3272. },
  3273. getScaling: function() {
  3274. var decomposed = this._decompose(),
  3275. s = decomposed && decomposed.scaling;
  3276. return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, 'setScaling');
  3277. },
  3278. setScaling: function() {
  3279. var current = this.getScaling(),
  3280. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  3281. if (current && scaling && !current.equals(scaling)) {
  3282. var rotation = this.getRotation(),
  3283. decomposed = this._decomposed,
  3284. matrix = new Matrix(),
  3285. isZero = Numerical.isZero;
  3286. if (isZero(current.x) || isZero(current.y)) {
  3287. matrix.translate(decomposed.translation);
  3288. if (rotation) {
  3289. matrix.rotate(rotation);
  3290. }
  3291. matrix.scale(scaling.x, scaling.y);
  3292. this._matrix.set(matrix);
  3293. } else {
  3294. var center = this.getPosition(true);
  3295. matrix.translate(center);
  3296. if (rotation)
  3297. matrix.rotate(rotation);
  3298. matrix.scale(scaling.x / current.x, scaling.y / current.y);
  3299. if (rotation)
  3300. matrix.rotate(-rotation);
  3301. matrix.translate(center.negate());
  3302. this.transform(matrix);
  3303. }
  3304. if (decomposed) {
  3305. decomposed.scaling = scaling;
  3306. this._decomposed = decomposed;
  3307. }
  3308. }
  3309. },
  3310. getMatrix: function() {
  3311. return this._matrix;
  3312. },
  3313. setMatrix: function() {
  3314. var matrix = this._matrix;
  3315. matrix.set.apply(matrix, arguments);
  3316. },
  3317. getGlobalMatrix: function(_dontClone) {
  3318. var matrix = this._globalMatrix;
  3319. if (matrix) {
  3320. var parent = this._parent;
  3321. var parents = [];
  3322. while (parent) {
  3323. if (!parent._globalMatrix) {
  3324. matrix = null;
  3325. for (var i = 0, l = parents.length; i < l; i++) {
  3326. parents[i]._globalMatrix = null;
  3327. }
  3328. break;
  3329. }
  3330. parents.push(parent);
  3331. parent = parent._parent;
  3332. }
  3333. }
  3334. if (!matrix) {
  3335. matrix = this._globalMatrix = this._matrix.clone();
  3336. var parent = this._parent;
  3337. if (parent)
  3338. matrix.prepend(parent.getGlobalMatrix(true));
  3339. }
  3340. return _dontClone ? matrix : matrix.clone();
  3341. },
  3342. getViewMatrix: function() {
  3343. return this.getGlobalMatrix().prepend(this.getView()._matrix);
  3344. },
  3345. getApplyMatrix: function() {
  3346. return this._applyMatrix;
  3347. },
  3348. setApplyMatrix: function(apply) {
  3349. if (this._applyMatrix = this._canApplyMatrix && !!apply)
  3350. this.transform(null, true);
  3351. },
  3352. getTransformContent: '#getApplyMatrix',
  3353. setTransformContent: '#setApplyMatrix',
  3354. }, {
  3355. getProject: function() {
  3356. return this._project;
  3357. },
  3358. _setProject: function(project, installEvents) {
  3359. if (this._project !== project) {
  3360. if (this._project)
  3361. this._installEvents(false);
  3362. this._project = project;
  3363. var children = this._children;
  3364. for (var i = 0, l = children && children.length; i < l; i++)
  3365. children[i]._setProject(project);
  3366. installEvents = true;
  3367. }
  3368. if (installEvents)
  3369. this._installEvents(true);
  3370. },
  3371. getView: function() {
  3372. return this._project._view;
  3373. },
  3374. _installEvents: function _installEvents(install) {
  3375. _installEvents.base.call(this, install);
  3376. var children = this._children;
  3377. for (var i = 0, l = children && children.length; i < l; i++)
  3378. children[i]._installEvents(install);
  3379. },
  3380. getLayer: function() {
  3381. var parent = this;
  3382. while (parent = parent._parent) {
  3383. if (parent instanceof Layer)
  3384. return parent;
  3385. }
  3386. return null;
  3387. },
  3388. getParent: function() {
  3389. return this._parent;
  3390. },
  3391. setParent: function(item) {
  3392. return item.addChild(this);
  3393. },
  3394. _getOwner: '#getParent',
  3395. getChildren: function() {
  3396. return this._children;
  3397. },
  3398. setChildren: function(items) {
  3399. this.removeChildren();
  3400. this.addChildren(items);
  3401. },
  3402. getFirstChild: function() {
  3403. return this._children && this._children[0] || null;
  3404. },
  3405. getLastChild: function() {
  3406. return this._children && this._children[this._children.length - 1]
  3407. || null;
  3408. },
  3409. getNextSibling: function() {
  3410. var owner = this._getOwner();
  3411. return owner && owner._children[this._index + 1] || null;
  3412. },
  3413. getPreviousSibling: function() {
  3414. var owner = this._getOwner();
  3415. return owner && owner._children[this._index - 1] || null;
  3416. },
  3417. getIndex: function() {
  3418. return this._index;
  3419. },
  3420. equals: function(item) {
  3421. return item === this || item && this._class === item._class
  3422. && this._style.equals(item._style)
  3423. && this._matrix.equals(item._matrix)
  3424. && this._locked === item._locked
  3425. && this._visible === item._visible
  3426. && this._blendMode === item._blendMode
  3427. && this._opacity === item._opacity
  3428. && this._clipMask === item._clipMask
  3429. && this._guide === item._guide
  3430. && this._equals(item)
  3431. || false;
  3432. },
  3433. _equals: function(item) {
  3434. return Base.equals(this._children, item._children);
  3435. },
  3436. clone: function(options) {
  3437. var copy = new this.constructor(Item.NO_INSERT),
  3438. children = this._children,
  3439. insert = Base.pick(options ? options.insert : undefined,
  3440. options === undefined || options === true),
  3441. deep = Base.pick(options ? options.deep : undefined, true);
  3442. if (children)
  3443. copy.copyAttributes(this);
  3444. if (!children || deep)
  3445. copy.copyContent(this);
  3446. if (!children)
  3447. copy.copyAttributes(this);
  3448. if (insert)
  3449. copy.insertAbove(this);
  3450. var name = this._name,
  3451. parent = this._parent;
  3452. if (name && parent) {
  3453. var children = parent._children,
  3454. orig = name,
  3455. i = 1;
  3456. while (children[name])
  3457. name = orig + ' ' + (i++);
  3458. if (name !== orig)
  3459. copy.setName(name);
  3460. }
  3461. return copy;
  3462. },
  3463. copyContent: function(source) {
  3464. var children = source._children;
  3465. for (var i = 0, l = children && children.length; i < l; i++) {
  3466. this.addChild(children[i].clone(false), true);
  3467. }
  3468. },
  3469. copyAttributes: function(source, excludeMatrix) {
  3470. this.setStyle(source._style);
  3471. var keys = ['_locked', '_visible', '_blendMode', '_opacity',
  3472. '_clipMask', '_guide'];
  3473. for (var i = 0, l = keys.length; i < l; i++) {
  3474. var key = keys[i];
  3475. if (source.hasOwnProperty(key))
  3476. this[key] = source[key];
  3477. }
  3478. if (!excludeMatrix)
  3479. this._matrix.set(source._matrix, true);
  3480. this.setApplyMatrix(source._applyMatrix);
  3481. this.setPivot(source._pivot);
  3482. this.setSelection(source._selection);
  3483. var data = source._data,
  3484. name = source._name;
  3485. this._data = data ? Base.clone(data) : null;
  3486. if (name)
  3487. this.setName(name);
  3488. },
  3489. rasterize: function(arg0, arg1) {
  3490. var resolution,
  3491. insert,
  3492. raster;
  3493. if (Base.isPlainObject(arg0)) {
  3494. resolution = arg0.resolution;
  3495. insert = arg0.insert;
  3496. raster = arg0.raster;
  3497. } else {
  3498. resolution = arg0;
  3499. insert = arg1;
  3500. }
  3501. if (raster) {
  3502. raster.matrix.reset(true);
  3503. } else {
  3504. raster = new Raster(Item.NO_INSERT);
  3505. }
  3506. var bounds = this.getStrokeBounds(),
  3507. scale = (resolution || this.getView().getResolution()) / 72,
  3508. topLeft = bounds.getTopLeft().floor(),
  3509. bottomRight = bounds.getBottomRight().ceil(),
  3510. boundsSize = new Size(bottomRight.subtract(topLeft)),
  3511. rasterSize = boundsSize.multiply(scale);
  3512. raster.setSize(rasterSize, true);
  3513. if (!rasterSize.isZero()) {
  3514. var ctx = raster.getContext(true),
  3515. matrix = new Matrix().scale(scale).translate(topLeft.negate());
  3516. ctx.save();
  3517. matrix.applyToContext(ctx);
  3518. this.draw(ctx, new Base({ matrices: [matrix] }));
  3519. ctx.restore();
  3520. }
  3521. raster.transform(
  3522. new Matrix()
  3523. .translate(topLeft.add(boundsSize.divide(2)))
  3524. .scale(1 / scale)
  3525. );
  3526. if (insert === undefined || insert) {
  3527. raster.insertAbove(this);
  3528. }
  3529. return raster;
  3530. },
  3531. contains: function() {
  3532. var matrix = this._matrix;
  3533. return (
  3534. matrix.isInvertible() &&
  3535. !!this._contains(matrix._inverseTransform(Point.read(arguments)))
  3536. );
  3537. },
  3538. _contains: function(point) {
  3539. var children = this._children;
  3540. if (children) {
  3541. for (var i = children.length - 1; i >= 0; i--) {
  3542. if (children[i].contains(point))
  3543. return true;
  3544. }
  3545. return false;
  3546. }
  3547. return point.isInside(this.getInternalBounds());
  3548. },
  3549. isInside: function() {
  3550. return Rectangle.read(arguments).contains(this.getBounds());
  3551. },
  3552. _asPathItem: function() {
  3553. return new Path.Rectangle({
  3554. rectangle: this.getInternalBounds(),
  3555. matrix: this._matrix,
  3556. insert: false,
  3557. });
  3558. },
  3559. intersects: function(item, _matrix) {
  3560. if (!(item instanceof Item))
  3561. return false;
  3562. return this._asPathItem().getIntersections(item._asPathItem(), null,
  3563. _matrix, true).length > 0;
  3564. }
  3565. },
  3566. new function() {
  3567. function hitTest() {
  3568. var args = arguments;
  3569. return this._hitTest(
  3570. Point.read(args),
  3571. HitResult.getOptions(args));
  3572. }
  3573. function hitTestAll() {
  3574. var args = arguments,
  3575. point = Point.read(args),
  3576. options = HitResult.getOptions(args),
  3577. all = [];
  3578. this._hitTest(point, new Base({ all: all }, options));
  3579. return all;
  3580. }
  3581. function hitTestChildren(point, options, viewMatrix, _exclude) {
  3582. var children = this._children;
  3583. if (children) {
  3584. for (var i = children.length - 1; i >= 0; i--) {
  3585. var child = children[i];
  3586. var res = child !== _exclude && child._hitTest(point, options,
  3587. viewMatrix);
  3588. if (res && !options.all)
  3589. return res;
  3590. }
  3591. }
  3592. return null;
  3593. }
  3594. Project.inject({
  3595. hitTest: hitTest,
  3596. hitTestAll: hitTestAll,
  3597. _hitTest: hitTestChildren
  3598. });
  3599. return {
  3600. hitTest: hitTest,
  3601. hitTestAll: hitTestAll,
  3602. _hitTestChildren: hitTestChildren,
  3603. };
  3604. }, {
  3605. _hitTest: function(point, options, parentViewMatrix) {
  3606. if (this._locked || !this._visible || this._guide && !options.guides
  3607. || this.isEmpty()) {
  3608. return null;
  3609. }
  3610. var matrix = this._matrix,
  3611. viewMatrix = parentViewMatrix
  3612. ? parentViewMatrix.appended(matrix)
  3613. : this.getGlobalMatrix().prepend(this.getView()._matrix),
  3614. tolerance = Math.max(options.tolerance, 1e-12),
  3615. tolerancePadding = options._tolerancePadding = new Size(
  3616. Path._getStrokePadding(tolerance,
  3617. matrix._shiftless().invert()));
  3618. point = matrix._inverseTransform(point);
  3619. if (!point || !this._children &&
  3620. !this.getBounds({ internal: true, stroke: true, handle: true })
  3621. .expand(tolerancePadding.multiply(2))._containsPoint(point)) {
  3622. return null;
  3623. }
  3624. var checkSelf = !(options.guides && !this._guide
  3625. || options.selected && !this.isSelected()
  3626. || options.type && options.type !== Base.hyphenate(this._class)
  3627. || options.class && !(this instanceof options.class)),
  3628. match = options.match,
  3629. that = this,
  3630. bounds,
  3631. res;
  3632. function filter(hit) {
  3633. if (hit && match && !match(hit))
  3634. hit = null;
  3635. if (hit && options.all)
  3636. options.all.push(hit);
  3637. return hit;
  3638. }
  3639. function checkPoint(type, part) {
  3640. var pt = part ? bounds['get' + part]() : that.getPosition();
  3641. if (point.subtract(pt).divide(tolerancePadding).length <= 1) {
  3642. return new HitResult(type, that, {
  3643. name: part ? Base.hyphenate(part) : type,
  3644. point: pt
  3645. });
  3646. }
  3647. }
  3648. var checkPosition = options.position,
  3649. checkCenter = options.center,
  3650. checkBounds = options.bounds;
  3651. if (checkSelf && this._parent
  3652. && (checkPosition || checkCenter || checkBounds)) {
  3653. if (checkCenter || checkBounds) {
  3654. bounds = this.getInternalBounds();
  3655. }
  3656. res = checkPosition && checkPoint('position') ||
  3657. checkCenter && checkPoint('center', 'Center');
  3658. if (!res && checkBounds) {
  3659. var points = [
  3660. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  3661. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
  3662. ];
  3663. for (var i = 0; i < 8 && !res; i++) {
  3664. res = checkPoint('bounds', points[i]);
  3665. }
  3666. }
  3667. res = filter(res);
  3668. }
  3669. if (!res) {
  3670. res = this._hitTestChildren(point, options, viewMatrix)
  3671. || checkSelf
  3672. && filter(this._hitTestSelf(point, options, viewMatrix,
  3673. this.getStrokeScaling() ? null
  3674. : viewMatrix._shiftless().invert()))
  3675. || null;
  3676. }
  3677. if (res && res.point) {
  3678. res.point = matrix.transform(res.point);
  3679. }
  3680. return res;
  3681. },
  3682. _hitTestSelf: function(point, options) {
  3683. if (options.fill && this.hasFill() && this._contains(point))
  3684. return new HitResult('fill', this);
  3685. },
  3686. matches: function(name, compare) {
  3687. function matchObject(obj1, obj2) {
  3688. for (var i in obj1) {
  3689. if (obj1.hasOwnProperty(i)) {
  3690. var val1 = obj1[i],
  3691. val2 = obj2[i];
  3692. if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
  3693. if (!matchObject(val1, val2))
  3694. return false;
  3695. } else if (!Base.equals(val1, val2)) {
  3696. return false;
  3697. }
  3698. }
  3699. }
  3700. return true;
  3701. }
  3702. var type = typeof name;
  3703. if (type === 'object') {
  3704. for (var key in name) {
  3705. if (name.hasOwnProperty(key) && !this.matches(key, name[key]))
  3706. return false;
  3707. }
  3708. return true;
  3709. } else if (type === 'function') {
  3710. return name(this);
  3711. } else if (name === 'match') {
  3712. return compare(this);
  3713. } else {
  3714. var value = /^(empty|editable)$/.test(name)
  3715. ? this['is' + Base.capitalize(name)]()
  3716. : name === 'type'
  3717. ? Base.hyphenate(this._class)
  3718. : this[name];
  3719. if (name === 'class') {
  3720. if (typeof compare === 'function')
  3721. return this instanceof compare;
  3722. value = this._class;
  3723. }
  3724. if (typeof compare === 'function') {
  3725. return !!compare(value);
  3726. } else if (compare) {
  3727. if (compare.test) {
  3728. return compare.test(value);
  3729. } else if (Base.isPlainObject(compare)) {
  3730. return matchObject(compare, value);
  3731. }
  3732. }
  3733. return Base.equals(value, compare);
  3734. }
  3735. },
  3736. getItems: function(options) {
  3737. return Item._getItems(this, options, this._matrix);
  3738. },
  3739. getItem: function(options) {
  3740. return Item._getItems(this, options, this._matrix, null, true)[0]
  3741. || null;
  3742. },
  3743. statics: {
  3744. _getItems: function _getItems(item, options, matrix, param, firstOnly) {
  3745. if (!param) {
  3746. var obj = typeof options === 'object' && options,
  3747. overlapping = obj && obj.overlapping,
  3748. inside = obj && obj.inside,
  3749. bounds = overlapping || inside,
  3750. rect = bounds && Rectangle.read([bounds]);
  3751. param = {
  3752. items: [],
  3753. recursive: obj && obj.recursive !== false,
  3754. inside: !!inside,
  3755. overlapping: !!overlapping,
  3756. rect: rect,
  3757. path: overlapping && new Path.Rectangle({
  3758. rectangle: rect,
  3759. insert: false
  3760. })
  3761. };
  3762. if (obj) {
  3763. options = Base.filter({}, options, {
  3764. recursive: true, inside: true, overlapping: true
  3765. });
  3766. }
  3767. }
  3768. var children = item._children,
  3769. items = param.items,
  3770. rect = param.rect;
  3771. matrix = rect && (matrix || new Matrix());
  3772. for (var i = 0, l = children && children.length; i < l; i++) {
  3773. var child = children[i],
  3774. childMatrix = matrix && matrix.appended(child._matrix),
  3775. add = true;
  3776. if (rect) {
  3777. var bounds = child.getBounds(childMatrix);
  3778. if (!rect.intersects(bounds))
  3779. continue;
  3780. if (!(rect.contains(bounds)
  3781. || param.overlapping && (bounds.contains(rect)
  3782. || param.path.intersects(child, childMatrix))))
  3783. add = false;
  3784. }
  3785. if (add && child.matches(options)) {
  3786. items.push(child);
  3787. if (firstOnly)
  3788. break;
  3789. }
  3790. if (param.recursive !== false) {
  3791. _getItems(child, options, childMatrix, param, firstOnly);
  3792. }
  3793. if (firstOnly && items.length > 0)
  3794. break;
  3795. }
  3796. return items;
  3797. }
  3798. }
  3799. }, {
  3800. importJSON: function(json) {
  3801. var res = Base.importJSON(json, this);
  3802. return res !== this ? this.addChild(res) : res;
  3803. },
  3804. addChild: function(item) {
  3805. return this.insertChild(undefined, item);
  3806. },
  3807. insertChild: function(index, item) {
  3808. var res = item ? this.insertChildren(index, [item]) : null;
  3809. return res && res[0];
  3810. },
  3811. addChildren: function(items) {
  3812. return this.insertChildren(this._children.length, items);
  3813. },
  3814. insertChildren: function(index, items) {
  3815. var children = this._children;
  3816. if (children && items && items.length > 0) {
  3817. items = Base.slice(items);
  3818. var inserted = {};
  3819. for (var i = items.length - 1; i >= 0; i--) {
  3820. var item = items[i],
  3821. id = item && item._id;
  3822. if (!item || inserted[id]) {
  3823. items.splice(i, 1);
  3824. } else {
  3825. item._remove(false, true);
  3826. inserted[id] = true;
  3827. }
  3828. }
  3829. Base.splice(children, items, index, 0);
  3830. var project = this._project,
  3831. notifySelf = project._changes;
  3832. for (var i = 0, l = items.length; i < l; i++) {
  3833. var item = items[i],
  3834. name = item._name;
  3835. item._parent = this;
  3836. item._setProject(project, true);
  3837. if (name)
  3838. item.setName(name);
  3839. if (notifySelf)
  3840. item._changed(5);
  3841. }
  3842. this._changed(11);
  3843. } else {
  3844. items = null;
  3845. }
  3846. return items;
  3847. },
  3848. _insertItem: '#insertChild',
  3849. _insertAt: function(item, offset) {
  3850. var owner = item && item._getOwner(),
  3851. res = item !== this && owner ? this : null;
  3852. if (res) {
  3853. res._remove(false, true);
  3854. owner._insertItem(item._index + offset, res);
  3855. }
  3856. return res;
  3857. },
  3858. insertAbove: function(item) {
  3859. return this._insertAt(item, 1);
  3860. },
  3861. insertBelow: function(item) {
  3862. return this._insertAt(item, 0);
  3863. },
  3864. sendToBack: function() {
  3865. var owner = this._getOwner();
  3866. return owner ? owner._insertItem(0, this) : null;
  3867. },
  3868. bringToFront: function() {
  3869. var owner = this._getOwner();
  3870. return owner ? owner._insertItem(undefined, this) : null;
  3871. },
  3872. appendTop: '#addChild',
  3873. appendBottom: function(item) {
  3874. return this.insertChild(0, item);
  3875. },
  3876. moveAbove: '#insertAbove',
  3877. moveBelow: '#insertBelow',
  3878. addTo: function(owner) {
  3879. return owner._insertItem(undefined, this);
  3880. },
  3881. copyTo: function(owner) {
  3882. return this.clone(false).addTo(owner);
  3883. },
  3884. reduce: function(options) {
  3885. var children = this._children;
  3886. if (children && children.length === 1) {
  3887. var child = children[0].reduce(options);
  3888. if (this._parent) {
  3889. child.insertAbove(this);
  3890. this.remove();
  3891. } else {
  3892. child.remove();
  3893. }
  3894. return child;
  3895. }
  3896. return this;
  3897. },
  3898. _removeNamed: function() {
  3899. var owner = this._getOwner();
  3900. if (owner) {
  3901. var children = owner._children,
  3902. namedChildren = owner._namedChildren,
  3903. name = this._name,
  3904. namedArray = namedChildren[name],
  3905. index = namedArray ? namedArray.indexOf(this) : -1;
  3906. if (index !== -1) {
  3907. if (children[name] == this)
  3908. delete children[name];
  3909. namedArray.splice(index, 1);
  3910. if (namedArray.length) {
  3911. children[name] = namedArray[0];
  3912. } else {
  3913. delete namedChildren[name];
  3914. }
  3915. }
  3916. }
  3917. },
  3918. _remove: function(notifySelf, notifyParent) {
  3919. var owner = this._getOwner(),
  3920. project = this._project,
  3921. index = this._index;
  3922. if (this._style)
  3923. this._style._dispose();
  3924. if (owner) {
  3925. if (this._name)
  3926. this._removeNamed();
  3927. if (index != null) {
  3928. if (project._activeLayer === this)
  3929. project._activeLayer = this.getNextSibling()
  3930. || this.getPreviousSibling();
  3931. Base.splice(owner._children, null, index, 1);
  3932. }
  3933. this._installEvents(false);
  3934. if (notifySelf && project._changes)
  3935. this._changed(5);
  3936. if (notifyParent)
  3937. owner._changed(11, this);
  3938. this._parent = null;
  3939. return true;
  3940. }
  3941. return false;
  3942. },
  3943. remove: function() {
  3944. return this._remove(true, true);
  3945. },
  3946. replaceWith: function(item) {
  3947. var ok = item && item.insertBelow(this);
  3948. if (ok)
  3949. this.remove();
  3950. return ok;
  3951. },
  3952. removeChildren: function(start, end) {
  3953. if (!this._children)
  3954. return null;
  3955. start = start || 0;
  3956. end = Base.pick(end, this._children.length);
  3957. var removed = Base.splice(this._children, null, start, end - start);
  3958. for (var i = removed.length - 1; i >= 0; i--) {
  3959. removed[i]._remove(true, false);
  3960. }
  3961. if (removed.length > 0)
  3962. this._changed(11);
  3963. return removed;
  3964. },
  3965. clear: '#removeChildren',
  3966. reverseChildren: function() {
  3967. if (this._children) {
  3968. this._children.reverse();
  3969. for (var i = 0, l = this._children.length; i < l; i++)
  3970. this._children[i]._index = i;
  3971. this._changed(11);
  3972. }
  3973. },
  3974. isEmpty: function(recursively) {
  3975. var children = this._children;
  3976. var numChildren = children ? children.length : 0;
  3977. if (recursively) {
  3978. for (var i = 0; i < numChildren; i++) {
  3979. if (!children[i].isEmpty(recursively)) {
  3980. return false;
  3981. }
  3982. }
  3983. return true;
  3984. }
  3985. return !numChildren;
  3986. },
  3987. isEditable: function() {
  3988. var item = this;
  3989. while (item) {
  3990. if (!item._visible || item._locked)
  3991. return false;
  3992. item = item._parent;
  3993. }
  3994. return true;
  3995. },
  3996. hasFill: function() {
  3997. return this.getStyle().hasFill();
  3998. },
  3999. hasStroke: function() {
  4000. return this.getStyle().hasStroke();
  4001. },
  4002. hasShadow: function() {
  4003. return this.getStyle().hasShadow();
  4004. },
  4005. _getOrder: function(item) {
  4006. function getList(item) {
  4007. var list = [];
  4008. do {
  4009. list.unshift(item);
  4010. } while (item = item._parent);
  4011. return list;
  4012. }
  4013. var list1 = getList(this),
  4014. list2 = getList(item);
  4015. for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
  4016. if (list1[i] != list2[i]) {
  4017. return list1[i]._index < list2[i]._index ? 1 : -1;
  4018. }
  4019. }
  4020. return 0;
  4021. },
  4022. hasChildren: function() {
  4023. return this._children && this._children.length > 0;
  4024. },
  4025. isInserted: function() {
  4026. return this._parent ? this._parent.isInserted() : false;
  4027. },
  4028. isAbove: function(item) {
  4029. return this._getOrder(item) === -1;
  4030. },
  4031. isBelow: function(item) {
  4032. return this._getOrder(item) === 1;
  4033. },
  4034. isParent: function(item) {
  4035. return this._parent === item;
  4036. },
  4037. isChild: function(item) {
  4038. return item && item._parent === this;
  4039. },
  4040. isDescendant: function(item) {
  4041. var parent = this;
  4042. while (parent = parent._parent) {
  4043. if (parent === item)
  4044. return true;
  4045. }
  4046. return false;
  4047. },
  4048. isAncestor: function(item) {
  4049. return item ? item.isDescendant(this) : false;
  4050. },
  4051. isSibling: function(item) {
  4052. return this._parent === item._parent;
  4053. },
  4054. isGroupedWith: function(item) {
  4055. var parent = this._parent;
  4056. while (parent) {
  4057. if (parent._parent
  4058. && /^(Group|Layer|CompoundPath)$/.test(parent._class)
  4059. && item.isDescendant(parent))
  4060. return true;
  4061. parent = parent._parent;
  4062. }
  4063. return false;
  4064. },
  4065. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  4066. var rotate = key === 'rotate';
  4067. this[key] = function() {
  4068. var args = arguments,
  4069. value = (rotate ? Base : Point).read(args),
  4070. center = Point.read(args, 0, { readNull: true });
  4071. return this.transform(new Matrix()[key](value,
  4072. center || this.getPosition(true)));
  4073. };
  4074. }, {
  4075. translate: function() {
  4076. var mx = new Matrix();
  4077. return this.transform(mx.translate.apply(mx, arguments));
  4078. },
  4079. transform: function(matrix, _applyRecursively, _setApplyMatrix) {
  4080. var _matrix = this._matrix,
  4081. transformMatrix = matrix && !matrix.isIdentity(),
  4082. applyMatrix = (
  4083. _setApplyMatrix && this._canApplyMatrix ||
  4084. this._applyMatrix && (
  4085. transformMatrix || !_matrix.isIdentity() ||
  4086. _applyRecursively && this._children
  4087. )
  4088. );
  4089. if (!transformMatrix && !applyMatrix)
  4090. return this;
  4091. if (transformMatrix) {
  4092. if (!matrix.isInvertible() && _matrix.isInvertible())
  4093. _matrix._backup = _matrix.getValues();
  4094. _matrix.prepend(matrix, true);
  4095. var style = this._style,
  4096. fillColor = style.getFillColor(true),
  4097. strokeColor = style.getStrokeColor(true);
  4098. if (fillColor)
  4099. fillColor.transform(matrix);
  4100. if (strokeColor)
  4101. strokeColor.transform(matrix);
  4102. }
  4103. if (applyMatrix && (applyMatrix = this._transformContent(
  4104. _matrix, _applyRecursively, _setApplyMatrix))) {
  4105. var pivot = this._pivot;
  4106. if (pivot)
  4107. _matrix._transformPoint(pivot, pivot, true);
  4108. _matrix.reset(true);
  4109. if (_setApplyMatrix && this._canApplyMatrix)
  4110. this._applyMatrix = true;
  4111. }
  4112. var bounds = this._bounds,
  4113. position = this._position;
  4114. if (transformMatrix || applyMatrix) {
  4115. this._changed(25);
  4116. }
  4117. var decomp = transformMatrix && bounds && matrix.decompose();
  4118. if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) {
  4119. for (var key in bounds) {
  4120. var cache = bounds[key];
  4121. if (cache.nonscaling) {
  4122. delete bounds[key];
  4123. } else if (applyMatrix || !cache.internal) {
  4124. var rect = cache.rect;
  4125. matrix._transformBounds(rect, rect);
  4126. }
  4127. }
  4128. this._bounds = bounds;
  4129. var cached = bounds[this._getBoundsCacheKey(
  4130. this._boundsOptions || {})];
  4131. if (cached) {
  4132. this._position = this._getPositionFromBounds(cached.rect);
  4133. }
  4134. } else if (transformMatrix && position && this._pivot) {
  4135. this._position = matrix._transformPoint(position, position);
  4136. }
  4137. return this;
  4138. },
  4139. _transformContent: function(matrix, applyRecursively, setApplyMatrix) {
  4140. var children = this._children;
  4141. if (children) {
  4142. for (var i = 0, l = children.length; i < l; i++) {
  4143. children[i].transform(matrix, applyRecursively, setApplyMatrix);
  4144. }
  4145. return true;
  4146. }
  4147. },
  4148. globalToLocal: function() {
  4149. return this.getGlobalMatrix(true)._inverseTransform(
  4150. Point.read(arguments));
  4151. },
  4152. localToGlobal: function() {
  4153. return this.getGlobalMatrix(true)._transformPoint(
  4154. Point.read(arguments));
  4155. },
  4156. parentToLocal: function() {
  4157. return this._matrix._inverseTransform(Point.read(arguments));
  4158. },
  4159. localToParent: function() {
  4160. return this._matrix._transformPoint(Point.read(arguments));
  4161. },
  4162. fitBounds: function(rectangle, fill) {
  4163. rectangle = Rectangle.read(arguments);
  4164. var bounds = this.getBounds(),
  4165. itemRatio = bounds.height / bounds.width,
  4166. rectRatio = rectangle.height / rectangle.width,
  4167. scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
  4168. ? rectangle.width / bounds.width
  4169. : rectangle.height / bounds.height,
  4170. newBounds = new Rectangle(new Point(),
  4171. new Size(bounds.width * scale, bounds.height * scale));
  4172. newBounds.setCenter(rectangle.getCenter());
  4173. this.setBounds(newBounds);
  4174. }
  4175. }), {
  4176. _setStyles: function(ctx, param, viewMatrix) {
  4177. var style = this._style,
  4178. matrix = this._matrix;
  4179. if (style.hasFill()) {
  4180. ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix);
  4181. }
  4182. if (style.hasStroke()) {
  4183. ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix);
  4184. ctx.lineWidth = style.getStrokeWidth();
  4185. var strokeJoin = style.getStrokeJoin(),
  4186. strokeCap = style.getStrokeCap(),
  4187. miterLimit = style.getMiterLimit();
  4188. if (strokeJoin)
  4189. ctx.lineJoin = strokeJoin;
  4190. if (strokeCap)
  4191. ctx.lineCap = strokeCap;
  4192. if (miterLimit)
  4193. ctx.miterLimit = miterLimit;
  4194. if (paper.support.nativeDash) {
  4195. var dashArray = style.getDashArray(),
  4196. dashOffset = style.getDashOffset();
  4197. if (dashArray && dashArray.length) {
  4198. if ('setLineDash' in ctx) {
  4199. ctx.setLineDash(dashArray);
  4200. ctx.lineDashOffset = dashOffset;
  4201. } else {
  4202. ctx.mozDash = dashArray;
  4203. ctx.mozDashOffset = dashOffset;
  4204. }
  4205. }
  4206. }
  4207. }
  4208. if (style.hasShadow()) {
  4209. var pixelRatio = param.pixelRatio || 1,
  4210. mx = viewMatrix._shiftless().prepend(
  4211. new Matrix().scale(pixelRatio, pixelRatio)),
  4212. blur = mx.transform(new Point(style.getShadowBlur(), 0)),
  4213. offset = mx.transform(this.getShadowOffset());
  4214. ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx);
  4215. ctx.shadowBlur = blur.getLength();
  4216. ctx.shadowOffsetX = offset.x;
  4217. ctx.shadowOffsetY = offset.y;
  4218. }
  4219. },
  4220. draw: function(ctx, param, parentStrokeMatrix) {
  4221. var updateVersion = this._updateVersion = this._project._updateVersion;
  4222. if (!this._visible || this._opacity === 0)
  4223. return;
  4224. var matrices = param.matrices,
  4225. viewMatrix = param.viewMatrix,
  4226. matrix = this._matrix,
  4227. globalMatrix = matrices[matrices.length - 1].appended(matrix);
  4228. if (!globalMatrix.isInvertible())
  4229. return;
  4230. viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix)
  4231. : globalMatrix;
  4232. matrices.push(globalMatrix);
  4233. if (param.updateMatrix) {
  4234. this._globalMatrix = globalMatrix;
  4235. }
  4236. var blendMode = this._blendMode,
  4237. opacity = Numerical.clamp(this._opacity, 0, 1),
  4238. normalBlend = blendMode === 'normal',
  4239. nativeBlend = BlendMode.nativeModes[blendMode],
  4240. direct = normalBlend && opacity === 1
  4241. || param.dontStart
  4242. || param.clip
  4243. || (nativeBlend || normalBlend && opacity < 1)
  4244. && this._canComposite(),
  4245. pixelRatio = param.pixelRatio || 1,
  4246. mainCtx, itemOffset, prevOffset;
  4247. if (!direct) {
  4248. var bounds = this.getStrokeBounds(viewMatrix);
  4249. if (!bounds.width || !bounds.height) {
  4250. matrices.pop();
  4251. return;
  4252. }
  4253. prevOffset = param.offset;
  4254. itemOffset = param.offset = bounds.getTopLeft().floor();
  4255. mainCtx = ctx;
  4256. ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1)
  4257. .multiply(pixelRatio));
  4258. if (pixelRatio !== 1)
  4259. ctx.scale(pixelRatio, pixelRatio);
  4260. }
  4261. ctx.save();
  4262. var strokeMatrix = parentStrokeMatrix
  4263. ? parentStrokeMatrix.appended(matrix)
  4264. : this._canScaleStroke && !this.getStrokeScaling(true)
  4265. && viewMatrix,
  4266. clip = !direct && param.clipItem,
  4267. transform = !strokeMatrix || clip;
  4268. if (direct) {
  4269. ctx.globalAlpha = opacity;
  4270. if (nativeBlend)
  4271. ctx.globalCompositeOperation = blendMode;
  4272. } else if (transform) {
  4273. ctx.translate(-itemOffset.x, -itemOffset.y);
  4274. }
  4275. if (transform) {
  4276. (direct ? matrix : viewMatrix).applyToContext(ctx);
  4277. }
  4278. if (clip) {
  4279. param.clipItem.draw(ctx, param.extend({ clip: true }));
  4280. }
  4281. if (strokeMatrix) {
  4282. ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  4283. var offset = param.offset;
  4284. if (offset)
  4285. ctx.translate(-offset.x, -offset.y);
  4286. }
  4287. this._draw(ctx, param, viewMatrix, strokeMatrix);
  4288. ctx.restore();
  4289. matrices.pop();
  4290. if (param.clip && !param.dontFinish) {
  4291. ctx.clip(this.getFillRule());
  4292. }
  4293. if (!direct) {
  4294. BlendMode.process(blendMode, ctx, mainCtx, opacity,
  4295. itemOffset.subtract(prevOffset).multiply(pixelRatio));
  4296. CanvasProvider.release(ctx);
  4297. param.offset = prevOffset;
  4298. }
  4299. },
  4300. _isUpdated: function(updateVersion) {
  4301. var parent = this._parent;
  4302. if (parent instanceof CompoundPath)
  4303. return parent._isUpdated(updateVersion);
  4304. var updated = this._updateVersion === updateVersion;
  4305. if (!updated && parent && parent._visible
  4306. && parent._isUpdated(updateVersion)) {
  4307. this._updateVersion = updateVersion;
  4308. updated = true;
  4309. }
  4310. return updated;
  4311. },
  4312. _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) {
  4313. var selection = this._selection,
  4314. itemSelected = selection & 1,
  4315. boundsSelected = selection & 2
  4316. || itemSelected && this._selectBounds,
  4317. positionSelected = selection & 4;
  4318. if (!this._drawSelected)
  4319. itemSelected = false;
  4320. if ((itemSelected || boundsSelected || positionSelected)
  4321. && this._isUpdated(updateVersion)) {
  4322. var layer,
  4323. color = this.getSelectedColor(true) || (layer = this.getLayer())
  4324. && layer.getSelectedColor(true),
  4325. mx = matrix.appended(this.getGlobalMatrix(true)),
  4326. half = size / 2;
  4327. ctx.strokeStyle = ctx.fillStyle = color
  4328. ? color.toCanvasStyle(ctx) : '#009dec';
  4329. if (itemSelected)
  4330. this._drawSelected(ctx, mx, selectionItems);
  4331. if (positionSelected) {
  4332. var pos = this.getPosition(true),
  4333. parent = this._parent,
  4334. point = parent ? parent.localToGlobal(pos) : pos,
  4335. x = point.x,
  4336. y = point.y;
  4337. ctx.beginPath();
  4338. ctx.arc(x, y, half, 0, Math.PI * 2, true);
  4339. ctx.stroke();
  4340. var deltas = [[0, -1], [1, 0], [0, 1], [-1, 0]],
  4341. start = half,
  4342. end = size + 1;
  4343. for (var i = 0; i < 4; i++) {
  4344. var delta = deltas[i],
  4345. dx = delta[0],
  4346. dy = delta[1];
  4347. ctx.moveTo(x + dx * start, y + dy * start);
  4348. ctx.lineTo(x + dx * end, y + dy * end);
  4349. ctx.stroke();
  4350. }
  4351. }
  4352. if (boundsSelected) {
  4353. var coords = mx._transformCorners(this.getInternalBounds());
  4354. ctx.beginPath();
  4355. for (var i = 0; i < 8; i++) {
  4356. ctx[!i ? 'moveTo' : 'lineTo'](coords[i], coords[++i]);
  4357. }
  4358. ctx.closePath();
  4359. ctx.stroke();
  4360. for (var i = 0; i < 8; i++) {
  4361. ctx.fillRect(coords[i] - half, coords[++i] - half,
  4362. size, size);
  4363. }
  4364. }
  4365. }
  4366. },
  4367. _canComposite: function() {
  4368. return false;
  4369. }
  4370. }, Base.each(['down', 'drag', 'up', 'move'], function(key) {
  4371. this['removeOn' + Base.capitalize(key)] = function() {
  4372. var hash = {};
  4373. hash[key] = true;
  4374. return this.removeOn(hash);
  4375. };
  4376. }, {
  4377. removeOn: function(obj) {
  4378. for (var name in obj) {
  4379. if (obj[name]) {
  4380. var key = 'mouse' + name,
  4381. project = this._project,
  4382. sets = project._removeSets = project._removeSets || {};
  4383. sets[key] = sets[key] || {};
  4384. sets[key][this._id] = this;
  4385. }
  4386. }
  4387. return this;
  4388. }
  4389. }), {
  4390. tween: function(from, to, options) {
  4391. if (!options) {
  4392. options = to;
  4393. to = from;
  4394. from = null;
  4395. if (!options) {
  4396. options = to;
  4397. to = null;
  4398. }
  4399. }
  4400. var easing = options && options.easing,
  4401. start = options && options.start,
  4402. duration = options != null && (
  4403. typeof options === 'number' ? options : options.duration
  4404. ),
  4405. tween = new Tween(this, from, to, duration, easing, start);
  4406. function onFrame(event) {
  4407. tween._handleFrame(event.time * 1000);
  4408. if (!tween.running) {
  4409. this.off('frame', onFrame);
  4410. }
  4411. }
  4412. if (duration) {
  4413. this.on('frame', onFrame);
  4414. }
  4415. return tween;
  4416. },
  4417. tweenTo: function(to, options) {
  4418. return this.tween(null, to, options);
  4419. },
  4420. tweenFrom: function(from, options) {
  4421. return this.tween(from, null, options);
  4422. }
  4423. });
  4424. var Group = Item.extend({
  4425. _class: 'Group',
  4426. _selectBounds: false,
  4427. _selectChildren: true,
  4428. _serializeFields: {
  4429. children: []
  4430. },
  4431. initialize: function Group(arg) {
  4432. this._children = [];
  4433. this._namedChildren = {};
  4434. if (!this._initialize(arg))
  4435. this.addChildren(Array.isArray(arg) ? arg : arguments);
  4436. },
  4437. _changed: function _changed(flags) {
  4438. _changed.base.call(this, flags);
  4439. if (flags & 2050) {
  4440. this._clipItem = undefined;
  4441. }
  4442. },
  4443. _getClipItem: function() {
  4444. var clipItem = this._clipItem;
  4445. if (clipItem === undefined) {
  4446. clipItem = null;
  4447. var children = this._children;
  4448. for (var i = 0, l = children.length; i < l; i++) {
  4449. if (children[i]._clipMask) {
  4450. clipItem = children[i];
  4451. break;
  4452. }
  4453. }
  4454. this._clipItem = clipItem;
  4455. }
  4456. return clipItem;
  4457. },
  4458. isClipped: function() {
  4459. return !!this._getClipItem();
  4460. },
  4461. setClipped: function(clipped) {
  4462. var child = this.getFirstChild();
  4463. if (child)
  4464. child.setClipMask(clipped);
  4465. },
  4466. _getBounds: function _getBounds(matrix, options) {
  4467. var clipItem = this._getClipItem();
  4468. return clipItem
  4469. ? clipItem._getCachedBounds(clipItem._matrix.prepended(matrix),
  4470. Base.set({}, options, { stroke: false }))
  4471. : _getBounds.base.call(this, matrix, options);
  4472. },
  4473. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  4474. var clipItem = this._getClipItem();
  4475. return (!clipItem || clipItem.contains(point))
  4476. && _hitTestChildren.base.call(this, point, options, viewMatrix,
  4477. clipItem);
  4478. },
  4479. _draw: function(ctx, param) {
  4480. var clip = param.clip,
  4481. clipItem = !clip && this._getClipItem();
  4482. param = param.extend({ clipItem: clipItem, clip: false });
  4483. if (clip) {
  4484. ctx.beginPath();
  4485. param.dontStart = param.dontFinish = true;
  4486. } else if (clipItem) {
  4487. clipItem.draw(ctx, param.extend({ clip: true }));
  4488. }
  4489. var children = this._children;
  4490. for (var i = 0, l = children.length; i < l; i++) {
  4491. var item = children[i];
  4492. if (item !== clipItem)
  4493. item.draw(ctx, param);
  4494. }
  4495. }
  4496. });
  4497. var Layer = Group.extend({
  4498. _class: 'Layer',
  4499. initialize: function Layer() {
  4500. Group.apply(this, arguments);
  4501. },
  4502. _getOwner: function() {
  4503. return this._parent || this._index != null && this._project;
  4504. },
  4505. isInserted: function isInserted() {
  4506. return this._parent ? isInserted.base.call(this) : this._index != null;
  4507. },
  4508. activate: function() {
  4509. this._project._activeLayer = this;
  4510. },
  4511. _hitTestSelf: function() {
  4512. }
  4513. });
  4514. var Shape = Item.extend({
  4515. _class: 'Shape',
  4516. _applyMatrix: false,
  4517. _canApplyMatrix: false,
  4518. _canScaleStroke: true,
  4519. _serializeFields: {
  4520. type: null,
  4521. size: null,
  4522. radius: null
  4523. },
  4524. initialize: function Shape(props, point) {
  4525. this._initialize(props, point);
  4526. },
  4527. _equals: function(item) {
  4528. return this._type === item._type
  4529. && this._size.equals(item._size)
  4530. && Base.equals(this._radius, item._radius);
  4531. },
  4532. copyContent: function(source) {
  4533. this.setType(source._type);
  4534. this.setSize(source._size);
  4535. this.setRadius(source._radius);
  4536. },
  4537. getType: function() {
  4538. return this._type;
  4539. },
  4540. setType: function(type) {
  4541. this._type = type;
  4542. },
  4543. getShape: '#getType',
  4544. setShape: '#setType',
  4545. getSize: function() {
  4546. var size = this._size;
  4547. return new LinkedSize(size.width, size.height, this, 'setSize');
  4548. },
  4549. setSize: function() {
  4550. var size = Size.read(arguments);
  4551. if (!this._size) {
  4552. this._size = size.clone();
  4553. } else if (!this._size.equals(size)) {
  4554. var type = this._type,
  4555. width = size.width,
  4556. height = size.height;
  4557. if (type === 'rectangle') {
  4558. this._radius.set(Size.min(this._radius, size.divide(2).abs()));
  4559. } else if (type === 'circle') {
  4560. width = height = (width + height) / 2;
  4561. this._radius = width / 2;
  4562. } else if (type === 'ellipse') {
  4563. this._radius._set(width / 2, height / 2);
  4564. }
  4565. this._size._set(width, height);
  4566. this._changed(9);
  4567. }
  4568. },
  4569. getRadius: function() {
  4570. var rad = this._radius;
  4571. return this._type === 'circle'
  4572. ? rad
  4573. : new LinkedSize(rad.width, rad.height, this, 'setRadius');
  4574. },
  4575. setRadius: function(radius) {
  4576. var type = this._type;
  4577. if (type === 'circle') {
  4578. if (radius === this._radius)
  4579. return;
  4580. var size = radius * 2;
  4581. this._radius = radius;
  4582. this._size._set(size, size);
  4583. } else {
  4584. radius = Size.read(arguments);
  4585. if (!this._radius) {
  4586. this._radius = radius.clone();
  4587. } else {
  4588. if (this._radius.equals(radius))
  4589. return;
  4590. this._radius.set(radius);
  4591. if (type === 'rectangle') {
  4592. var size = Size.max(this._size, radius.multiply(2));
  4593. this._size.set(size);
  4594. } else if (type === 'ellipse') {
  4595. this._size._set(radius.width * 2, radius.height * 2);
  4596. }
  4597. }
  4598. }
  4599. this._changed(9);
  4600. },
  4601. isEmpty: function() {
  4602. return false;
  4603. },
  4604. toPath: function(insert) {
  4605. var path = new Path[Base.capitalize(this._type)]({
  4606. center: new Point(),
  4607. size: this._size,
  4608. radius: this._radius,
  4609. insert: false
  4610. });
  4611. path.copyAttributes(this);
  4612. if (paper.settings.applyMatrix)
  4613. path.setApplyMatrix(true);
  4614. if (insert === undefined || insert)
  4615. path.insertAbove(this);
  4616. return path;
  4617. },
  4618. toShape: '#clone',
  4619. _asPathItem: function() {
  4620. return this.toPath(false);
  4621. },
  4622. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  4623. var style = this._style,
  4624. hasFill = style.hasFill(),
  4625. hasStroke = style.hasStroke(),
  4626. dontPaint = param.dontFinish || param.clip,
  4627. untransformed = !strokeMatrix;
  4628. if (hasFill || hasStroke || dontPaint) {
  4629. var type = this._type,
  4630. radius = this._radius,
  4631. isCircle = type === 'circle';
  4632. if (!param.dontStart)
  4633. ctx.beginPath();
  4634. if (untransformed && isCircle) {
  4635. ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
  4636. } else {
  4637. var rx = isCircle ? radius : radius.width,
  4638. ry = isCircle ? radius : radius.height,
  4639. size = this._size,
  4640. width = size.width,
  4641. height = size.height;
  4642. if (untransformed && type === 'rectangle' && rx === 0 && ry === 0) {
  4643. ctx.rect(-width / 2, -height / 2, width, height);
  4644. } else {
  4645. var x = width / 2,
  4646. y = height / 2,
  4647. kappa = 1 - 0.5522847498307936,
  4648. cx = rx * kappa,
  4649. cy = ry * kappa,
  4650. c = [
  4651. -x, -y + ry,
  4652. -x, -y + cy,
  4653. -x + cx, -y,
  4654. -x + rx, -y,
  4655. x - rx, -y,
  4656. x - cx, -y,
  4657. x, -y + cy,
  4658. x, -y + ry,
  4659. x, y - ry,
  4660. x, y - cy,
  4661. x - cx, y,
  4662. x - rx, y,
  4663. -x + rx, y,
  4664. -x + cx, y,
  4665. -x, y - cy,
  4666. -x, y - ry
  4667. ];
  4668. if (strokeMatrix)
  4669. strokeMatrix.transform(c, c, 32);
  4670. ctx.moveTo(c[0], c[1]);
  4671. ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]);
  4672. if (x !== rx)
  4673. ctx.lineTo(c[8], c[9]);
  4674. ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]);
  4675. if (y !== ry)
  4676. ctx.lineTo(c[16], c[17]);
  4677. ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]);
  4678. if (x !== rx)
  4679. ctx.lineTo(c[24], c[25]);
  4680. ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]);
  4681. }
  4682. }
  4683. ctx.closePath();
  4684. }
  4685. if (!dontPaint && (hasFill || hasStroke)) {
  4686. this._setStyles(ctx, param, viewMatrix);
  4687. if (hasFill) {
  4688. ctx.fill(style.getFillRule());
  4689. ctx.shadowColor = 'rgba(0,0,0,0)';
  4690. }
  4691. if (hasStroke)
  4692. ctx.stroke();
  4693. }
  4694. },
  4695. _canComposite: function() {
  4696. return !(this.hasFill() && this.hasStroke());
  4697. },
  4698. _getBounds: function(matrix, options) {
  4699. var rect = new Rectangle(this._size).setCenter(0, 0),
  4700. style = this._style,
  4701. strokeWidth = options.stroke && style.hasStroke()
  4702. && style.getStrokeWidth();
  4703. if (matrix)
  4704. rect = matrix._transformBounds(rect);
  4705. return strokeWidth
  4706. ? rect.expand(Path._getStrokePadding(strokeWidth,
  4707. this._getStrokeMatrix(matrix, options)))
  4708. : rect;
  4709. }
  4710. },
  4711. new function() {
  4712. function getCornerCenter(that, point, expand) {
  4713. var radius = that._radius;
  4714. if (!radius.isZero()) {
  4715. var halfSize = that._size.divide(2);
  4716. for (var q = 1; q <= 4; q++) {
  4717. var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1),
  4718. corner = dir.multiply(halfSize),
  4719. center = corner.subtract(dir.multiply(radius)),
  4720. rect = new Rectangle(
  4721. expand ? corner.add(dir.multiply(expand)) : corner,
  4722. center);
  4723. if (rect.contains(point))
  4724. return { point: center, quadrant: q };
  4725. }
  4726. }
  4727. }
  4728. function isOnEllipseStroke(point, radius, padding, quadrant) {
  4729. var vector = point.divide(radius);
  4730. return (!quadrant || vector.isInQuadrant(quadrant)) &&
  4731. vector.subtract(vector.normalize()).multiply(radius)
  4732. .divide(padding).length <= 1;
  4733. }
  4734. return {
  4735. _contains: function _contains(point) {
  4736. if (this._type === 'rectangle') {
  4737. var center = getCornerCenter(this, point);
  4738. return center
  4739. ? point.subtract(center.point).divide(this._radius)
  4740. .getLength() <= 1
  4741. : _contains.base.call(this, point);
  4742. } else {
  4743. return point.divide(this.size).getLength() <= 0.5;
  4744. }
  4745. },
  4746. _hitTestSelf: function _hitTestSelf(point, options, viewMatrix,
  4747. strokeMatrix) {
  4748. var hit = false,
  4749. style = this._style,
  4750. hitStroke = options.stroke && style.hasStroke(),
  4751. hitFill = options.fill && style.hasFill();
  4752. if (hitStroke || hitFill) {
  4753. var type = this._type,
  4754. radius = this._radius,
  4755. strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0,
  4756. strokePadding = options._tolerancePadding.add(
  4757. Path._getStrokePadding(strokeRadius,
  4758. !style.getStrokeScaling() && strokeMatrix));
  4759. if (type === 'rectangle') {
  4760. var padding = strokePadding.multiply(2),
  4761. center = getCornerCenter(this, point, padding);
  4762. if (center) {
  4763. hit = isOnEllipseStroke(point.subtract(center.point),
  4764. radius, strokePadding, center.quadrant);
  4765. } else {
  4766. var rect = new Rectangle(this._size).setCenter(0, 0),
  4767. outer = rect.expand(padding),
  4768. inner = rect.expand(padding.negate());
  4769. hit = outer._containsPoint(point)
  4770. && !inner._containsPoint(point);
  4771. }
  4772. } else {
  4773. hit = isOnEllipseStroke(point, radius, strokePadding);
  4774. }
  4775. }
  4776. return hit ? new HitResult(hitStroke ? 'stroke' : 'fill', this)
  4777. : _hitTestSelf.base.apply(this, arguments);
  4778. }
  4779. };
  4780. }, {
  4781. statics: new function() {
  4782. function createShape(type, point, size, radius, args) {
  4783. var item = Base.create(Shape.prototype);
  4784. item._type = type;
  4785. item._size = size;
  4786. item._radius = radius;
  4787. item._initialize(Base.getNamed(args), point);
  4788. return item;
  4789. }
  4790. return {
  4791. Circle: function() {
  4792. var args = arguments,
  4793. center = Point.readNamed(args, 'center'),
  4794. radius = Base.readNamed(args, 'radius');
  4795. return createShape('circle', center, new Size(radius * 2), radius,
  4796. args);
  4797. },
  4798. Rectangle: function() {
  4799. var args = arguments,
  4800. rect = Rectangle.readNamed(args, 'rectangle'),
  4801. radius = Size.min(Size.readNamed(args, 'radius'),
  4802. rect.getSize(true).divide(2));
  4803. return createShape('rectangle', rect.getCenter(true),
  4804. rect.getSize(true), radius, args);
  4805. },
  4806. Ellipse: function() {
  4807. var args = arguments,
  4808. ellipse = Shape._readEllipse(args),
  4809. radius = ellipse.radius;
  4810. return createShape('ellipse', ellipse.center, radius.multiply(2),
  4811. radius, args);
  4812. },
  4813. _readEllipse: function(args) {
  4814. var center,
  4815. radius;
  4816. if (Base.hasNamed(args, 'radius')) {
  4817. center = Point.readNamed(args, 'center');
  4818. radius = Size.readNamed(args, 'radius');
  4819. } else {
  4820. var rect = Rectangle.readNamed(args, 'rectangle');
  4821. center = rect.getCenter(true);
  4822. radius = rect.getSize(true).divide(2);
  4823. }
  4824. return { center: center, radius: radius };
  4825. }
  4826. };
  4827. }});
  4828. var Raster = Item.extend({
  4829. _class: 'Raster',
  4830. _applyMatrix: false,
  4831. _canApplyMatrix: false,
  4832. _boundsOptions: { stroke: false, handle: false },
  4833. _serializeFields: {
  4834. crossOrigin: null,
  4835. source: null
  4836. },
  4837. _prioritize: ['crossOrigin'],
  4838. _smoothing: 'low',
  4839. beans: true,
  4840. initialize: function Raster(source, position) {
  4841. if (!this._initialize(source,
  4842. position !== undefined && Point.read(arguments))) {
  4843. var image,
  4844. type = typeof source,
  4845. object = type === 'string'
  4846. ? document.getElementById(source)
  4847. : type === 'object'
  4848. ? source
  4849. : null;
  4850. if (object && object !== Item.NO_INSERT) {
  4851. if (object.getContext || object.naturalHeight != null) {
  4852. image = object;
  4853. } else if (object) {
  4854. var size = Size.read(arguments);
  4855. if (!size.isZero()) {
  4856. image = CanvasProvider.getCanvas(size);
  4857. }
  4858. }
  4859. }
  4860. if (image) {
  4861. this.setImage(image);
  4862. } else {
  4863. this.setSource(source);
  4864. }
  4865. }
  4866. if (!this._size) {
  4867. this._size = new Size();
  4868. this._loaded = false;
  4869. }
  4870. },
  4871. _equals: function(item) {
  4872. return this.getSource() === item.getSource();
  4873. },
  4874. copyContent: function(source) {
  4875. var image = source._image,
  4876. canvas = source._canvas;
  4877. if (image) {
  4878. this._setImage(image);
  4879. } else if (canvas) {
  4880. var copyCanvas = CanvasProvider.getCanvas(source._size);
  4881. copyCanvas.getContext('2d').drawImage(canvas, 0, 0);
  4882. this._setImage(copyCanvas);
  4883. }
  4884. this._crossOrigin = source._crossOrigin;
  4885. },
  4886. getSize: function() {
  4887. var size = this._size;
  4888. return new LinkedSize(size ? size.width : 0, size ? size.height : 0,
  4889. this, 'setSize');
  4890. },
  4891. setSize: function(_size, _clear) {
  4892. var size = Size.read(arguments);
  4893. if (!size.equals(this._size)) {
  4894. if (size.width > 0 && size.height > 0) {
  4895. var element = !_clear && this.getElement();
  4896. this._setImage(CanvasProvider.getCanvas(size));
  4897. if (element) {
  4898. this.getContext(true).drawImage(element, 0, 0,
  4899. size.width, size.height);
  4900. }
  4901. } else {
  4902. if (this._canvas)
  4903. CanvasProvider.release(this._canvas);
  4904. this._size = size.clone();
  4905. }
  4906. } else if (_clear) {
  4907. this.clear();
  4908. }
  4909. },
  4910. getWidth: function() {
  4911. return this._size ? this._size.width : 0;
  4912. },
  4913. setWidth: function(width) {
  4914. this.setSize(width, this.getHeight());
  4915. },
  4916. getHeight: function() {
  4917. return this._size ? this._size.height : 0;
  4918. },
  4919. setHeight: function(height) {
  4920. this.setSize(this.getWidth(), height);
  4921. },
  4922. getLoaded: function() {
  4923. return this._loaded;
  4924. },
  4925. isEmpty: function() {
  4926. var size = this._size;
  4927. return !size || size.width === 0 && size.height === 0;
  4928. },
  4929. getResolution: function() {
  4930. var matrix = this._matrix,
  4931. orig = new Point(0, 0).transform(matrix),
  4932. u = new Point(1, 0).transform(matrix).subtract(orig),
  4933. v = new Point(0, 1).transform(matrix).subtract(orig);
  4934. return new Size(
  4935. 72 / u.getLength(),
  4936. 72 / v.getLength()
  4937. );
  4938. },
  4939. getPpi: '#getResolution',
  4940. getImage: function() {
  4941. return this._image;
  4942. },
  4943. setImage: function(image) {
  4944. var that = this;
  4945. function emit(event) {
  4946. var view = that.getView(),
  4947. type = event && event.type || 'load';
  4948. if (view && that.responds(type)) {
  4949. paper = view._scope;
  4950. that.emit(type, new Event(event));
  4951. }
  4952. }
  4953. this._setImage(image);
  4954. if (this._loaded) {
  4955. setTimeout(emit, 0);
  4956. } else if (image) {
  4957. DomEvent.add(image, {
  4958. load: function(event) {
  4959. that._setImage(image);
  4960. emit(event);
  4961. },
  4962. error: emit
  4963. });
  4964. }
  4965. },
  4966. _setImage: function(image) {
  4967. if (this._canvas)
  4968. CanvasProvider.release(this._canvas);
  4969. if (image && image.getContext) {
  4970. this._image = null;
  4971. this._canvas = image;
  4972. this._loaded = true;
  4973. } else {
  4974. this._image = image;
  4975. this._canvas = null;
  4976. this._loaded = !!(image && image.src && image.complete);
  4977. }
  4978. this._size = new Size(
  4979. image ? image.naturalWidth || image.width : 0,
  4980. image ? image.naturalHeight || image.height : 0);
  4981. this._context = null;
  4982. this._changed(1033);
  4983. },
  4984. getCanvas: function() {
  4985. if (!this._canvas) {
  4986. var ctx = CanvasProvider.getContext(this._size);
  4987. try {
  4988. if (this._image)
  4989. ctx.drawImage(this._image, 0, 0);
  4990. this._canvas = ctx.canvas;
  4991. } catch (e) {
  4992. CanvasProvider.release(ctx);
  4993. }
  4994. }
  4995. return this._canvas;
  4996. },
  4997. setCanvas: '#setImage',
  4998. getContext: function(_change) {
  4999. if (!this._context)
  5000. this._context = this.getCanvas().getContext('2d');
  5001. if (_change) {
  5002. this._image = null;
  5003. this._changed(1025);
  5004. }
  5005. return this._context;
  5006. },
  5007. setContext: function(context) {
  5008. this._context = context;
  5009. },
  5010. getSource: function() {
  5011. var image = this._image;
  5012. return image && image.src || this.toDataURL();
  5013. },
  5014. setSource: function(src) {
  5015. var image = new self.Image(),
  5016. crossOrigin = this._crossOrigin;
  5017. if (crossOrigin)
  5018. image.crossOrigin = crossOrigin;
  5019. if (src)
  5020. image.src = src;
  5021. this.setImage(image);
  5022. },
  5023. getCrossOrigin: function() {
  5024. var image = this._image;
  5025. return image && image.crossOrigin || this._crossOrigin || '';
  5026. },
  5027. setCrossOrigin: function(crossOrigin) {
  5028. this._crossOrigin = crossOrigin;
  5029. var image = this._image;
  5030. if (image)
  5031. image.crossOrigin = crossOrigin;
  5032. },
  5033. getSmoothing: function() {
  5034. return this._smoothing;
  5035. },
  5036. setSmoothing: function(smoothing) {
  5037. this._smoothing = typeof smoothing === 'string'
  5038. ? smoothing
  5039. : smoothing ? 'low' : 'off';
  5040. this._changed(257);
  5041. },
  5042. getElement: function() {
  5043. return this._canvas || this._loaded && this._image;
  5044. }
  5045. }, {
  5046. beans: false,
  5047. getSubCanvas: function() {
  5048. var rect = Rectangle.read(arguments),
  5049. ctx = CanvasProvider.getContext(rect.getSize());
  5050. ctx.drawImage(this.getCanvas(), rect.x, rect.y,
  5051. rect.width, rect.height, 0, 0, rect.width, rect.height);
  5052. return ctx.canvas;
  5053. },
  5054. getSubRaster: function() {
  5055. var rect = Rectangle.read(arguments),
  5056. raster = new Raster(Item.NO_INSERT);
  5057. raster._setImage(this.getSubCanvas(rect));
  5058. raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
  5059. raster._matrix.prepend(this._matrix);
  5060. raster.insertAbove(this);
  5061. return raster;
  5062. },
  5063. toDataURL: function() {
  5064. var image = this._image,
  5065. src = image && image.src;
  5066. if (/^data:/.test(src))
  5067. return src;
  5068. var canvas = this.getCanvas();
  5069. return canvas ? canvas.toDataURL.apply(canvas, arguments) : null;
  5070. },
  5071. drawImage: function(image ) {
  5072. var point = Point.read(arguments, 1);
  5073. this.getContext(true).drawImage(image, point.x, point.y);
  5074. },
  5075. getAverageColor: function(object) {
  5076. var bounds, path;
  5077. if (!object) {
  5078. bounds = this.getBounds();
  5079. } else if (object instanceof PathItem) {
  5080. path = object;
  5081. bounds = object.getBounds();
  5082. } else if (typeof object === 'object') {
  5083. if ('width' in object) {
  5084. bounds = new Rectangle(object);
  5085. } else if ('x' in object) {
  5086. bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
  5087. }
  5088. }
  5089. if (!bounds)
  5090. return null;
  5091. var sampleSize = 32,
  5092. width = Math.min(bounds.width, sampleSize),
  5093. height = Math.min(bounds.height, sampleSize);
  5094. var ctx = Raster._sampleContext;
  5095. if (!ctx) {
  5096. ctx = Raster._sampleContext = CanvasProvider.getContext(
  5097. new Size(sampleSize));
  5098. } else {
  5099. ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
  5100. }
  5101. ctx.save();
  5102. var matrix = new Matrix()
  5103. .scale(width / bounds.width, height / bounds.height)
  5104. .translate(-bounds.x, -bounds.y);
  5105. matrix.applyToContext(ctx);
  5106. if (path)
  5107. path.draw(ctx, new Base({ clip: true, matrices: [matrix] }));
  5108. this._matrix.applyToContext(ctx);
  5109. var element = this.getElement(),
  5110. size = this._size;
  5111. if (element)
  5112. ctx.drawImage(element, -size.width / 2, -size.height / 2);
  5113. ctx.restore();
  5114. var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
  5115. Math.ceil(height)).data,
  5116. channels = [0, 0, 0],
  5117. total = 0;
  5118. for (var i = 0, l = pixels.length; i < l; i += 4) {
  5119. var alpha = pixels[i + 3];
  5120. total += alpha;
  5121. alpha /= 255;
  5122. channels[0] += pixels[i] * alpha;
  5123. channels[1] += pixels[i + 1] * alpha;
  5124. channels[2] += pixels[i + 2] * alpha;
  5125. }
  5126. for (var i = 0; i < 3; i++)
  5127. channels[i] /= total;
  5128. return total ? Color.read(channels) : null;
  5129. },
  5130. getPixel: function() {
  5131. var point = Point.read(arguments);
  5132. var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
  5133. return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
  5134. data[3] / 255);
  5135. },
  5136. setPixel: function() {
  5137. var args = arguments,
  5138. point = Point.read(args),
  5139. color = Color.read(args),
  5140. components = color._convert('rgb'),
  5141. alpha = color._alpha,
  5142. ctx = this.getContext(true),
  5143. imageData = ctx.createImageData(1, 1),
  5144. data = imageData.data;
  5145. data[0] = components[0] * 255;
  5146. data[1] = components[1] * 255;
  5147. data[2] = components[2] * 255;
  5148. data[3] = alpha != null ? alpha * 255 : 255;
  5149. ctx.putImageData(imageData, point.x, point.y);
  5150. },
  5151. clear: function() {
  5152. var size = this._size;
  5153. this.getContext(true).clearRect(0, 0, size.width + 1, size.height + 1);
  5154. },
  5155. createImageData: function() {
  5156. var size = Size.read(arguments);
  5157. return this.getContext().createImageData(size.width, size.height);
  5158. },
  5159. getImageData: function() {
  5160. var rect = Rectangle.read(arguments);
  5161. if (rect.isEmpty())
  5162. rect = new Rectangle(this._size);
  5163. return this.getContext().getImageData(rect.x, rect.y,
  5164. rect.width, rect.height);
  5165. },
  5166. setImageData: function(data ) {
  5167. var point = Point.read(arguments, 1);
  5168. this.getContext(true).putImageData(data, point.x, point.y);
  5169. },
  5170. _getBounds: function(matrix, options) {
  5171. var rect = new Rectangle(this._size).setCenter(0, 0);
  5172. return matrix ? matrix._transformBounds(rect) : rect;
  5173. },
  5174. _hitTestSelf: function(point) {
  5175. if (this._contains(point)) {
  5176. var that = this;
  5177. return new HitResult('pixel', that, {
  5178. offset: point.add(that._size.divide(2)).round(),
  5179. color: {
  5180. get: function() {
  5181. return that.getPixel(this.offset);
  5182. }
  5183. }
  5184. });
  5185. }
  5186. },
  5187. _draw: function(ctx, param, viewMatrix) {
  5188. var element = this.getElement();
  5189. if (element && element.width > 0 && element.height > 0) {
  5190. ctx.globalAlpha = Numerical.clamp(this._opacity, 0, 1);
  5191. this._setStyles(ctx, param, viewMatrix);
  5192. var smoothing = this._smoothing,
  5193. disabled = smoothing === 'off';
  5194. DomElement.setPrefixed(
  5195. ctx,
  5196. disabled ? 'imageSmoothingEnabled' : 'imageSmoothingQuality',
  5197. disabled ? false : smoothing
  5198. );
  5199. ctx.drawImage(element,
  5200. -this._size.width / 2, -this._size.height / 2);
  5201. }
  5202. },
  5203. _canComposite: function() {
  5204. return true;
  5205. }
  5206. });
  5207. var SymbolItem = Item.extend({
  5208. _class: 'SymbolItem',
  5209. _applyMatrix: false,
  5210. _canApplyMatrix: false,
  5211. _boundsOptions: { stroke: true },
  5212. _serializeFields: {
  5213. symbol: null
  5214. },
  5215. initialize: function SymbolItem(arg0, arg1) {
  5216. if (!this._initialize(arg0,
  5217. arg1 !== undefined && Point.read(arguments, 1)))
  5218. this.setDefinition(arg0 instanceof SymbolDefinition ?
  5219. arg0 : new SymbolDefinition(arg0));
  5220. },
  5221. _equals: function(item) {
  5222. return this._definition === item._definition;
  5223. },
  5224. copyContent: function(source) {
  5225. this.setDefinition(source._definition);
  5226. },
  5227. getDefinition: function() {
  5228. return this._definition;
  5229. },
  5230. setDefinition: function(definition) {
  5231. this._definition = definition;
  5232. this._changed(9);
  5233. },
  5234. getSymbol: '#getDefinition',
  5235. setSymbol: '#setDefinition',
  5236. isEmpty: function() {
  5237. return this._definition._item.isEmpty();
  5238. },
  5239. _getBounds: function(matrix, options) {
  5240. var item = this._definition._item;
  5241. return item._getCachedBounds(item._matrix.prepended(matrix), options);
  5242. },
  5243. _hitTestSelf: function(point, options, viewMatrix) {
  5244. var opts = options.extend({ all: false });
  5245. var res = this._definition._item._hitTest(point, opts, viewMatrix);
  5246. if (res)
  5247. res.item = this;
  5248. return res;
  5249. },
  5250. _draw: function(ctx, param) {
  5251. this._definition._item.draw(ctx, param);
  5252. }
  5253. });
  5254. var SymbolDefinition = Base.extend({
  5255. _class: 'SymbolDefinition',
  5256. initialize: function SymbolDefinition(item, dontCenter) {
  5257. this._id = UID.get();
  5258. this.project = paper.project;
  5259. if (item)
  5260. this.setItem(item, dontCenter);
  5261. },
  5262. _serialize: function(options, dictionary) {
  5263. return dictionary.add(this, function() {
  5264. return Base.serialize([this._class, this._item],
  5265. options, false, dictionary);
  5266. });
  5267. },
  5268. _changed: function(flags) {
  5269. if (flags & 8)
  5270. Item._clearBoundsCache(this);
  5271. if (flags & 1)
  5272. this.project._changed(flags);
  5273. },
  5274. getItem: function() {
  5275. return this._item;
  5276. },
  5277. setItem: function(item, _dontCenter) {
  5278. if (item._symbol)
  5279. item = item.clone();
  5280. if (this._item)
  5281. this._item._symbol = null;
  5282. this._item = item;
  5283. item.remove();
  5284. item.setSelected(false);
  5285. if (!_dontCenter)
  5286. item.setPosition(new Point());
  5287. item._symbol = this;
  5288. this._changed(9);
  5289. },
  5290. getDefinition: '#getItem',
  5291. setDefinition: '#setItem',
  5292. place: function(position) {
  5293. return new SymbolItem(this, position);
  5294. },
  5295. clone: function() {
  5296. return new SymbolDefinition(this._item.clone(false));
  5297. },
  5298. equals: function(symbol) {
  5299. return symbol === this
  5300. || symbol && this._item.equals(symbol._item)
  5301. || false;
  5302. }
  5303. });
  5304. var HitResult = Base.extend({
  5305. _class: 'HitResult',
  5306. initialize: function HitResult(type, item, values) {
  5307. this.type = type;
  5308. this.item = item;
  5309. if (values)
  5310. this.inject(values);
  5311. },
  5312. statics: {
  5313. getOptions: function(args) {
  5314. var options = args && Base.read(args);
  5315. return new Base({
  5316. type: null,
  5317. tolerance: paper.settings.hitTolerance,
  5318. fill: !options,
  5319. stroke: !options,
  5320. segments: !options,
  5321. handles: false,
  5322. ends: false,
  5323. position: false,
  5324. center: false,
  5325. bounds: false,
  5326. guides: false,
  5327. selected: false
  5328. }, options);
  5329. }
  5330. }
  5331. });
  5332. var Segment = Base.extend({
  5333. _class: 'Segment',
  5334. beans: true,
  5335. _selection: 0,
  5336. initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
  5337. var count = arguments.length,
  5338. point, handleIn, handleOut, selection;
  5339. if (count > 0) {
  5340. if (arg0 == null || typeof arg0 === 'object') {
  5341. if (count === 1 && arg0 && 'point' in arg0) {
  5342. point = arg0.point;
  5343. handleIn = arg0.handleIn;
  5344. handleOut = arg0.handleOut;
  5345. selection = arg0.selection;
  5346. } else {
  5347. point = arg0;
  5348. handleIn = arg1;
  5349. handleOut = arg2;
  5350. selection = arg3;
  5351. }
  5352. } else {
  5353. point = [ arg0, arg1 ];
  5354. handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
  5355. handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
  5356. }
  5357. }
  5358. new SegmentPoint(point, this, '_point');
  5359. new SegmentPoint(handleIn, this, '_handleIn');
  5360. new SegmentPoint(handleOut, this, '_handleOut');
  5361. if (selection)
  5362. this.setSelection(selection);
  5363. },
  5364. _serialize: function(options, dictionary) {
  5365. var point = this._point,
  5366. selection = this._selection,
  5367. obj = selection || this.hasHandles()
  5368. ? [point, this._handleIn, this._handleOut]
  5369. : point;
  5370. if (selection)
  5371. obj.push(selection);
  5372. return Base.serialize(obj, options, true, dictionary);
  5373. },
  5374. _changed: function(point) {
  5375. var path = this._path;
  5376. if (!path)
  5377. return;
  5378. var curves = path._curves,
  5379. index = this._index,
  5380. curve;
  5381. if (curves) {
  5382. if ((!point || point === this._point || point === this._handleIn)
  5383. && (curve = index > 0 ? curves[index - 1] : path._closed
  5384. ? curves[curves.length - 1] : null))
  5385. curve._changed();
  5386. if ((!point || point === this._point || point === this._handleOut)
  5387. && (curve = curves[index]))
  5388. curve._changed();
  5389. }
  5390. path._changed(41);
  5391. },
  5392. getPoint: function() {
  5393. return this._point;
  5394. },
  5395. setPoint: function() {
  5396. this._point.set(Point.read(arguments));
  5397. },
  5398. getHandleIn: function() {
  5399. return this._handleIn;
  5400. },
  5401. setHandleIn: function() {
  5402. this._handleIn.set(Point.read(arguments));
  5403. },
  5404. getHandleOut: function() {
  5405. return this._handleOut;
  5406. },
  5407. setHandleOut: function() {
  5408. this._handleOut.set(Point.read(arguments));
  5409. },
  5410. hasHandles: function() {
  5411. return !this._handleIn.isZero() || !this._handleOut.isZero();
  5412. },
  5413. isSmooth: function() {
  5414. var handleIn = this._handleIn,
  5415. handleOut = this._handleOut;
  5416. return !handleIn.isZero() && !handleOut.isZero()
  5417. && handleIn.isCollinear(handleOut);
  5418. },
  5419. clearHandles: function() {
  5420. this._handleIn._set(0, 0);
  5421. this._handleOut._set(0, 0);
  5422. },
  5423. getSelection: function() {
  5424. return this._selection;
  5425. },
  5426. setSelection: function(selection) {
  5427. var oldSelection = this._selection,
  5428. path = this._path;
  5429. this._selection = selection = selection || 0;
  5430. if (path && selection !== oldSelection) {
  5431. path._updateSelection(this, oldSelection, selection);
  5432. path._changed(257);
  5433. }
  5434. },
  5435. _changeSelection: function(flag, selected) {
  5436. var selection = this._selection;
  5437. this.setSelection(selected ? selection | flag : selection & ~flag);
  5438. },
  5439. isSelected: function() {
  5440. return !!(this._selection & 7);
  5441. },
  5442. setSelected: function(selected) {
  5443. this._changeSelection(7, selected);
  5444. },
  5445. getIndex: function() {
  5446. return this._index !== undefined ? this._index : null;
  5447. },
  5448. getPath: function() {
  5449. return this._path || null;
  5450. },
  5451. getCurve: function() {
  5452. var path = this._path,
  5453. index = this._index;
  5454. if (path) {
  5455. if (index > 0 && !path._closed
  5456. && index === path._segments.length - 1)
  5457. index--;
  5458. return path.getCurves()[index] || null;
  5459. }
  5460. return null;
  5461. },
  5462. getLocation: function() {
  5463. var curve = this.getCurve();
  5464. return curve
  5465. ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)
  5466. : null;
  5467. },
  5468. getNext: function() {
  5469. var segments = this._path && this._path._segments;
  5470. return segments && (segments[this._index + 1]
  5471. || this._path._closed && segments[0]) || null;
  5472. },
  5473. smooth: function(options, _first, _last) {
  5474. var opts = options || {},
  5475. type = opts.type,
  5476. factor = opts.factor,
  5477. prev = this.getPrevious(),
  5478. next = this.getNext(),
  5479. p0 = (prev || this)._point,
  5480. p1 = this._point,
  5481. p2 = (next || this)._point,
  5482. d1 = p0.getDistance(p1),
  5483. d2 = p1.getDistance(p2);
  5484. if (!type || type === 'catmull-rom') {
  5485. var a = factor === undefined ? 0.5 : factor,
  5486. d1_a = Math.pow(d1, a),
  5487. d1_2a = d1_a * d1_a,
  5488. d2_a = Math.pow(d2, a),
  5489. d2_2a = d2_a * d2_a;
  5490. if (!_first && prev) {
  5491. var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a,
  5492. N = 3 * d2_a * (d2_a + d1_a);
  5493. this.setHandleIn(N !== 0
  5494. ? new Point(
  5495. (d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x,
  5496. (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y)
  5497. : new Point());
  5498. }
  5499. if (!_last && next) {
  5500. var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a,
  5501. N = 3 * d1_a * (d1_a + d2_a);
  5502. this.setHandleOut(N !== 0
  5503. ? new Point(
  5504. (d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x,
  5505. (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y)
  5506. : new Point());
  5507. }
  5508. } else if (type === 'geometric') {
  5509. if (prev && next) {
  5510. var vector = p0.subtract(p2),
  5511. t = factor === undefined ? 0.4 : factor,
  5512. k = t * d1 / (d1 + d2);
  5513. if (!_first)
  5514. this.setHandleIn(vector.multiply(k));
  5515. if (!_last)
  5516. this.setHandleOut(vector.multiply(k - t));
  5517. }
  5518. } else {
  5519. throw new Error('Smoothing method \'' + type + '\' not supported.');
  5520. }
  5521. },
  5522. getPrevious: function() {
  5523. var segments = this._path && this._path._segments;
  5524. return segments && (segments[this._index - 1]
  5525. || this._path._closed && segments[segments.length - 1]) || null;
  5526. },
  5527. isFirst: function() {
  5528. return !this._index;
  5529. },
  5530. isLast: function() {
  5531. var path = this._path;
  5532. return path && this._index === path._segments.length - 1 || false;
  5533. },
  5534. reverse: function() {
  5535. var handleIn = this._handleIn,
  5536. handleOut = this._handleOut,
  5537. tmp = handleIn.clone();
  5538. handleIn.set(handleOut);
  5539. handleOut.set(tmp);
  5540. },
  5541. reversed: function() {
  5542. return new Segment(this._point, this._handleOut, this._handleIn);
  5543. },
  5544. remove: function() {
  5545. return this._path ? !!this._path.removeSegment(this._index) : false;
  5546. },
  5547. clone: function() {
  5548. return new Segment(this._point, this._handleIn, this._handleOut);
  5549. },
  5550. equals: function(segment) {
  5551. return segment === this || segment && this._class === segment._class
  5552. && this._point.equals(segment._point)
  5553. && this._handleIn.equals(segment._handleIn)
  5554. && this._handleOut.equals(segment._handleOut)
  5555. || false;
  5556. },
  5557. toString: function() {
  5558. var parts = [ 'point: ' + this._point ];
  5559. if (!this._handleIn.isZero())
  5560. parts.push('handleIn: ' + this._handleIn);
  5561. if (!this._handleOut.isZero())
  5562. parts.push('handleOut: ' + this._handleOut);
  5563. return '{ ' + parts.join(', ') + ' }';
  5564. },
  5565. transform: function(matrix) {
  5566. this._transformCoordinates(matrix, new Array(6), true);
  5567. this._changed();
  5568. },
  5569. interpolate: function(from, to, factor) {
  5570. var u = 1 - factor,
  5571. v = factor,
  5572. point1 = from._point,
  5573. point2 = to._point,
  5574. handleIn1 = from._handleIn,
  5575. handleIn2 = to._handleIn,
  5576. handleOut2 = to._handleOut,
  5577. handleOut1 = from._handleOut;
  5578. this._point._set(
  5579. u * point1._x + v * point2._x,
  5580. u * point1._y + v * point2._y, true);
  5581. this._handleIn._set(
  5582. u * handleIn1._x + v * handleIn2._x,
  5583. u * handleIn1._y + v * handleIn2._y, true);
  5584. this._handleOut._set(
  5585. u * handleOut1._x + v * handleOut2._x,
  5586. u * handleOut1._y + v * handleOut2._y, true);
  5587. this._changed();
  5588. },
  5589. _transformCoordinates: function(matrix, coords, change) {
  5590. var point = this._point,
  5591. handleIn = !change || !this._handleIn.isZero()
  5592. ? this._handleIn : null,
  5593. handleOut = !change || !this._handleOut.isZero()
  5594. ? this._handleOut : null,
  5595. x = point._x,
  5596. y = point._y,
  5597. i = 2;
  5598. coords[0] = x;
  5599. coords[1] = y;
  5600. if (handleIn) {
  5601. coords[i++] = handleIn._x + x;
  5602. coords[i++] = handleIn._y + y;
  5603. }
  5604. if (handleOut) {
  5605. coords[i++] = handleOut._x + x;
  5606. coords[i++] = handleOut._y + y;
  5607. }
  5608. if (matrix) {
  5609. matrix._transformCoordinates(coords, coords, i / 2);
  5610. x = coords[0];
  5611. y = coords[1];
  5612. if (change) {
  5613. point._x = x;
  5614. point._y = y;
  5615. i = 2;
  5616. if (handleIn) {
  5617. handleIn._x = coords[i++] - x;
  5618. handleIn._y = coords[i++] - y;
  5619. }
  5620. if (handleOut) {
  5621. handleOut._x = coords[i++] - x;
  5622. handleOut._y = coords[i++] - y;
  5623. }
  5624. } else {
  5625. if (!handleIn) {
  5626. coords[i++] = x;
  5627. coords[i++] = y;
  5628. }
  5629. if (!handleOut) {
  5630. coords[i++] = x;
  5631. coords[i++] = y;
  5632. }
  5633. }
  5634. }
  5635. return coords;
  5636. }
  5637. });
  5638. var SegmentPoint = Point.extend({
  5639. initialize: function SegmentPoint(point, owner, key) {
  5640. var x, y,
  5641. selected;
  5642. if (!point) {
  5643. x = y = 0;
  5644. } else if ((x = point[0]) !== undefined) {
  5645. y = point[1];
  5646. } else {
  5647. var pt = point;
  5648. if ((x = pt.x) === undefined) {
  5649. pt = Point.read(arguments);
  5650. x = pt.x;
  5651. }
  5652. y = pt.y;
  5653. selected = pt.selected;
  5654. }
  5655. this._x = x;
  5656. this._y = y;
  5657. this._owner = owner;
  5658. owner[key] = this;
  5659. if (selected)
  5660. this.setSelected(true);
  5661. },
  5662. _set: function(x, y) {
  5663. this._x = x;
  5664. this._y = y;
  5665. this._owner._changed(this);
  5666. return this;
  5667. },
  5668. getX: function() {
  5669. return this._x;
  5670. },
  5671. setX: function(x) {
  5672. this._x = x;
  5673. this._owner._changed(this);
  5674. },
  5675. getY: function() {
  5676. return this._y;
  5677. },
  5678. setY: function(y) {
  5679. this._y = y;
  5680. this._owner._changed(this);
  5681. },
  5682. isZero: function() {
  5683. var isZero = Numerical.isZero;
  5684. return isZero(this._x) && isZero(this._y);
  5685. },
  5686. isSelected: function() {
  5687. return !!(this._owner._selection & this._getSelection());
  5688. },
  5689. setSelected: function(selected) {
  5690. this._owner._changeSelection(this._getSelection(), selected);
  5691. },
  5692. _getSelection: function() {
  5693. var owner = this._owner;
  5694. return this === owner._point ? 1
  5695. : this === owner._handleIn ? 2
  5696. : this === owner._handleOut ? 4
  5697. : 0;
  5698. }
  5699. });
  5700. var Curve = Base.extend({
  5701. _class: 'Curve',
  5702. beans: true,
  5703. initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
  5704. var count = arguments.length,
  5705. seg1, seg2,
  5706. point1, point2,
  5707. handle1, handle2;
  5708. if (count === 3) {
  5709. this._path = arg0;
  5710. seg1 = arg1;
  5711. seg2 = arg2;
  5712. } else if (!count) {
  5713. seg1 = new Segment();
  5714. seg2 = new Segment();
  5715. } else if (count === 1) {
  5716. if ('segment1' in arg0) {
  5717. seg1 = new Segment(arg0.segment1);
  5718. seg2 = new Segment(arg0.segment2);
  5719. } else if ('point1' in arg0) {
  5720. point1 = arg0.point1;
  5721. handle1 = arg0.handle1;
  5722. handle2 = arg0.handle2;
  5723. point2 = arg0.point2;
  5724. } else if (Array.isArray(arg0)) {
  5725. point1 = [arg0[0], arg0[1]];
  5726. point2 = [arg0[6], arg0[7]];
  5727. handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]];
  5728. handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]];
  5729. }
  5730. } else if (count === 2) {
  5731. seg1 = new Segment(arg0);
  5732. seg2 = new Segment(arg1);
  5733. } else if (count === 4) {
  5734. point1 = arg0;
  5735. handle1 = arg1;
  5736. handle2 = arg2;
  5737. point2 = arg3;
  5738. } else if (count === 8) {
  5739. point1 = [arg0, arg1];
  5740. point2 = [arg6, arg7];
  5741. handle1 = [arg2 - arg0, arg3 - arg1];
  5742. handle2 = [arg4 - arg6, arg5 - arg7];
  5743. }
  5744. this._segment1 = seg1 || new Segment(point1, null, handle1);
  5745. this._segment2 = seg2 || new Segment(point2, handle2, null);
  5746. },
  5747. _serialize: function(options, dictionary) {
  5748. return Base.serialize(this.hasHandles()
  5749. ? [this.getPoint1(), this.getHandle1(), this.getHandle2(),
  5750. this.getPoint2()]
  5751. : [this.getPoint1(), this.getPoint2()],
  5752. options, true, dictionary);
  5753. },
  5754. _changed: function() {
  5755. this._length = this._bounds = undefined;
  5756. },
  5757. clone: function() {
  5758. return new Curve(this._segment1, this._segment2);
  5759. },
  5760. toString: function() {
  5761. var parts = [ 'point1: ' + this._segment1._point ];
  5762. if (!this._segment1._handleOut.isZero())
  5763. parts.push('handle1: ' + this._segment1._handleOut);
  5764. if (!this._segment2._handleIn.isZero())
  5765. parts.push('handle2: ' + this._segment2._handleIn);
  5766. parts.push('point2: ' + this._segment2._point);
  5767. return '{ ' + parts.join(', ') + ' }';
  5768. },
  5769. classify: function() {
  5770. return Curve.classify(this.getValues());
  5771. },
  5772. remove: function() {
  5773. var removed = false;
  5774. if (this._path) {
  5775. var segment2 = this._segment2,
  5776. handleOut = segment2._handleOut;
  5777. removed = segment2.remove();
  5778. if (removed)
  5779. this._segment1._handleOut.set(handleOut);
  5780. }
  5781. return removed;
  5782. },
  5783. getPoint1: function() {
  5784. return this._segment1._point;
  5785. },
  5786. setPoint1: function() {
  5787. this._segment1._point.set(Point.read(arguments));
  5788. },
  5789. getPoint2: function() {
  5790. return this._segment2._point;
  5791. },
  5792. setPoint2: function() {
  5793. this._segment2._point.set(Point.read(arguments));
  5794. },
  5795. getHandle1: function() {
  5796. return this._segment1._handleOut;
  5797. },
  5798. setHandle1: function() {
  5799. this._segment1._handleOut.set(Point.read(arguments));
  5800. },
  5801. getHandle2: function() {
  5802. return this._segment2._handleIn;
  5803. },
  5804. setHandle2: function() {
  5805. this._segment2._handleIn.set(Point.read(arguments));
  5806. },
  5807. getSegment1: function() {
  5808. return this._segment1;
  5809. },
  5810. getSegment2: function() {
  5811. return this._segment2;
  5812. },
  5813. getPath: function() {
  5814. return this._path;
  5815. },
  5816. getIndex: function() {
  5817. return this._segment1._index;
  5818. },
  5819. getNext: function() {
  5820. var curves = this._path && this._path._curves;
  5821. return curves && (curves[this._segment1._index + 1]
  5822. || this._path._closed && curves[0]) || null;
  5823. },
  5824. getPrevious: function() {
  5825. var curves = this._path && this._path._curves;
  5826. return curves && (curves[this._segment1._index - 1]
  5827. || this._path._closed && curves[curves.length - 1]) || null;
  5828. },
  5829. isFirst: function() {
  5830. return !this._segment1._index;
  5831. },
  5832. isLast: function() {
  5833. var path = this._path;
  5834. return path && this._segment1._index === path._curves.length - 1
  5835. || false;
  5836. },
  5837. isSelected: function() {
  5838. return this.getPoint1().isSelected()
  5839. && this.getHandle1().isSelected()
  5840. && this.getHandle2().isSelected()
  5841. && this.getPoint2().isSelected();
  5842. },
  5843. setSelected: function(selected) {
  5844. this.getPoint1().setSelected(selected);
  5845. this.getHandle1().setSelected(selected);
  5846. this.getHandle2().setSelected(selected);
  5847. this.getPoint2().setSelected(selected);
  5848. },
  5849. getValues: function(matrix) {
  5850. return Curve.getValues(this._segment1, this._segment2, matrix);
  5851. },
  5852. getPoints: function() {
  5853. var coords = this.getValues(),
  5854. points = [];
  5855. for (var i = 0; i < 8; i += 2)
  5856. points.push(new Point(coords[i], coords[i + 1]));
  5857. return points;
  5858. }
  5859. }, {
  5860. getLength: function() {
  5861. if (this._length == null)
  5862. this._length = Curve.getLength(this.getValues(), 0, 1);
  5863. return this._length;
  5864. },
  5865. getArea: function() {
  5866. return Curve.getArea(this.getValues());
  5867. },
  5868. getLine: function() {
  5869. return new Line(this._segment1._point, this._segment2._point);
  5870. },
  5871. getPart: function(from, to) {
  5872. return new Curve(Curve.getPart(this.getValues(), from, to));
  5873. },
  5874. getPartLength: function(from, to) {
  5875. return Curve.getLength(this.getValues(), from, to);
  5876. },
  5877. divideAt: function(location) {
  5878. return this.divideAtTime(location && location.curve === this
  5879. ? location.time : this.getTimeAt(location));
  5880. },
  5881. divideAtTime: function(time, _setHandles) {
  5882. var tMin = 1e-8,
  5883. tMax = 1 - tMin,
  5884. res = null;
  5885. if (time >= tMin && time <= tMax) {
  5886. var parts = Curve.subdivide(this.getValues(), time),
  5887. left = parts[0],
  5888. right = parts[1],
  5889. setHandles = _setHandles || this.hasHandles(),
  5890. seg1 = this._segment1,
  5891. seg2 = this._segment2,
  5892. path = this._path;
  5893. if (setHandles) {
  5894. seg1._handleOut._set(left[2] - left[0], left[3] - left[1]);
  5895. seg2._handleIn._set(right[4] - right[6],right[5] - right[7]);
  5896. }
  5897. var x = left[6], y = left[7],
  5898. segment = new Segment(new Point(x, y),
  5899. setHandles && new Point(left[4] - x, left[5] - y),
  5900. setHandles && new Point(right[2] - x, right[3] - y));
  5901. if (path) {
  5902. path.insert(seg1._index + 1, segment);
  5903. res = this.getNext();
  5904. } else {
  5905. this._segment2 = segment;
  5906. this._changed();
  5907. res = new Curve(segment, seg2);
  5908. }
  5909. }
  5910. return res;
  5911. },
  5912. splitAt: function(location) {
  5913. var path = this._path;
  5914. return path ? path.splitAt(location) : null;
  5915. },
  5916. splitAtTime: function(time) {
  5917. return this.splitAt(this.getLocationAtTime(time));
  5918. },
  5919. divide: function(offset, isTime) {
  5920. return this.divideAtTime(offset === undefined ? 0.5 : isTime ? offset
  5921. : this.getTimeAt(offset));
  5922. },
  5923. split: function(offset, isTime) {
  5924. return this.splitAtTime(offset === undefined ? 0.5 : isTime ? offset
  5925. : this.getTimeAt(offset));
  5926. },
  5927. reversed: function() {
  5928. return new Curve(this._segment2.reversed(), this._segment1.reversed());
  5929. },
  5930. clearHandles: function() {
  5931. this._segment1._handleOut._set(0, 0);
  5932. this._segment2._handleIn._set(0, 0);
  5933. },
  5934. statics: {
  5935. getValues: function(segment1, segment2, matrix, straight) {
  5936. var p1 = segment1._point,
  5937. h1 = segment1._handleOut,
  5938. h2 = segment2._handleIn,
  5939. p2 = segment2._point,
  5940. x1 = p1.x, y1 = p1.y,
  5941. x2 = p2.x, y2 = p2.y,
  5942. values = straight
  5943. ? [ x1, y1, x1, y1, x2, y2, x2, y2 ]
  5944. : [
  5945. x1, y1,
  5946. x1 + h1._x, y1 + h1._y,
  5947. x2 + h2._x, y2 + h2._y,
  5948. x2, y2
  5949. ];
  5950. if (matrix)
  5951. matrix._transformCoordinates(values, values, 4);
  5952. return values;
  5953. },
  5954. subdivide: function(v, t) {
  5955. var x0 = v[0], y0 = v[1],
  5956. x1 = v[2], y1 = v[3],
  5957. x2 = v[4], y2 = v[5],
  5958. x3 = v[6], y3 = v[7];
  5959. if (t === undefined)
  5960. t = 0.5;
  5961. var u = 1 - t,
  5962. x4 = u * x0 + t * x1, y4 = u * y0 + t * y1,
  5963. x5 = u * x1 + t * x2, y5 = u * y1 + t * y2,
  5964. x6 = u * x2 + t * x3, y6 = u * y2 + t * y3,
  5965. x7 = u * x4 + t * x5, y7 = u * y4 + t * y5,
  5966. x8 = u * x5 + t * x6, y8 = u * y5 + t * y6,
  5967. x9 = u * x7 + t * x8, y9 = u * y7 + t * y8;
  5968. return [
  5969. [x0, y0, x4, y4, x7, y7, x9, y9],
  5970. [x9, y9, x8, y8, x6, y6, x3, y3]
  5971. ];
  5972. },
  5973. getMonoCurves: function(v, dir) {
  5974. var curves = [],
  5975. io = dir ? 0 : 1,
  5976. o0 = v[io + 0],
  5977. o1 = v[io + 2],
  5978. o2 = v[io + 4],
  5979. o3 = v[io + 6];
  5980. if ((o0 >= o1) === (o1 >= o2) && (o1 >= o2) === (o2 >= o3)
  5981. || Curve.isStraight(v)) {
  5982. curves.push(v);
  5983. } else {
  5984. var a = 3 * (o1 - o2) - o0 + o3,
  5985. b = 2 * (o0 + o2) - 4 * o1,
  5986. c = o1 - o0,
  5987. tMin = 1e-8,
  5988. tMax = 1 - tMin,
  5989. roots = [],
  5990. n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax);
  5991. if (!n) {
  5992. curves.push(v);
  5993. } else {
  5994. roots.sort();
  5995. var t = roots[0],
  5996. parts = Curve.subdivide(v, t);
  5997. curves.push(parts[0]);
  5998. if (n > 1) {
  5999. t = (roots[1] - t) / (1 - t);
  6000. parts = Curve.subdivide(parts[1], t);
  6001. curves.push(parts[0]);
  6002. }
  6003. curves.push(parts[1]);
  6004. }
  6005. }
  6006. return curves;
  6007. },
  6008. solveCubic: function (v, coord, val, roots, min, max) {
  6009. var v0 = v[coord],
  6010. v1 = v[coord + 2],
  6011. v2 = v[coord + 4],
  6012. v3 = v[coord + 6],
  6013. res = 0;
  6014. if ( !(v0 < val && v3 < val && v1 < val && v2 < val ||
  6015. v0 > val && v3 > val && v1 > val && v2 > val)) {
  6016. var c = 3 * (v1 - v0),
  6017. b = 3 * (v2 - v1) - c,
  6018. a = v3 - v0 - c - b;
  6019. res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max);
  6020. }
  6021. return res;
  6022. },
  6023. getTimeOf: function(v, point) {
  6024. var p0 = new Point(v[0], v[1]),
  6025. p3 = new Point(v[6], v[7]),
  6026. epsilon = 1e-12,
  6027. geomEpsilon = 1e-7,
  6028. t = point.isClose(p0, epsilon) ? 0
  6029. : point.isClose(p3, epsilon) ? 1
  6030. : null;
  6031. if (t === null) {
  6032. var coords = [point.x, point.y],
  6033. roots = [];
  6034. for (var c = 0; c < 2; c++) {
  6035. var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1);
  6036. for (var i = 0; i < count; i++) {
  6037. var u = roots[i];
  6038. if (point.isClose(Curve.getPoint(v, u), geomEpsilon))
  6039. return u;
  6040. }
  6041. }
  6042. }
  6043. return point.isClose(p0, geomEpsilon) ? 0
  6044. : point.isClose(p3, geomEpsilon) ? 1
  6045. : null;
  6046. },
  6047. getNearestTime: function(v, point) {
  6048. if (Curve.isStraight(v)) {
  6049. var x0 = v[0], y0 = v[1],
  6050. x3 = v[6], y3 = v[7],
  6051. vx = x3 - x0, vy = y3 - y0,
  6052. det = vx * vx + vy * vy;
  6053. if (det === 0)
  6054. return 0;
  6055. var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det;
  6056. return u < 1e-12 ? 0
  6057. : u > 0.999999999999 ? 1
  6058. : Curve.getTimeOf(v,
  6059. new Point(x0 + u * vx, y0 + u * vy));
  6060. }
  6061. var count = 100,
  6062. minDist = Infinity,
  6063. minT = 0;
  6064. function refine(t) {
  6065. if (t >= 0 && t <= 1) {
  6066. var dist = point.getDistance(Curve.getPoint(v, t), true);
  6067. if (dist < minDist) {
  6068. minDist = dist;
  6069. minT = t;
  6070. return true;
  6071. }
  6072. }
  6073. }
  6074. for (var i = 0; i <= count; i++)
  6075. refine(i / count);
  6076. var step = 1 / (count * 2);
  6077. while (step > 1e-8) {
  6078. if (!refine(minT - step) && !refine(minT + step))
  6079. step /= 2;
  6080. }
  6081. return minT;
  6082. },
  6083. getPart: function(v, from, to) {
  6084. var flip = from > to;
  6085. if (flip) {
  6086. var tmp = from;
  6087. from = to;
  6088. to = tmp;
  6089. }
  6090. if (from > 0)
  6091. v = Curve.subdivide(v, from)[1];
  6092. if (to < 1)
  6093. v = Curve.subdivide(v, (to - from) / (1 - from))[0];
  6094. return flip
  6095. ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]]
  6096. : v;
  6097. },
  6098. isFlatEnough: function(v, flatness) {
  6099. var x0 = v[0], y0 = v[1],
  6100. x1 = v[2], y1 = v[3],
  6101. x2 = v[4], y2 = v[5],
  6102. x3 = v[6], y3 = v[7],
  6103. ux = 3 * x1 - 2 * x0 - x3,
  6104. uy = 3 * y1 - 2 * y0 - y3,
  6105. vx = 3 * x2 - 2 * x3 - x0,
  6106. vy = 3 * y2 - 2 * y3 - y0;
  6107. return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
  6108. <= 16 * flatness * flatness;
  6109. },
  6110. getArea: function(v) {
  6111. var x0 = v[0], y0 = v[1],
  6112. x1 = v[2], y1 = v[3],
  6113. x2 = v[4], y2 = v[5],
  6114. x3 = v[6], y3 = v[7];
  6115. return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2)
  6116. + y1 * (x0 - x2) - x1 * (y0 - y2)
  6117. + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20;
  6118. },
  6119. getBounds: function(v) {
  6120. var min = v.slice(0, 2),
  6121. max = min.slice(),
  6122. roots = [0, 0];
  6123. for (var i = 0; i < 2; i++)
  6124. Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
  6125. i, 0, min, max, roots);
  6126. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  6127. },
  6128. _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
  6129. function add(value, padding) {
  6130. var left = value - padding,
  6131. right = value + padding;
  6132. if (left < min[coord])
  6133. min[coord] = left;
  6134. if (right > max[coord])
  6135. max[coord] = right;
  6136. }
  6137. padding /= 2;
  6138. var minPad = min[coord] + padding,
  6139. maxPad = max[coord] - padding;
  6140. if ( v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad ||
  6141. v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) {
  6142. if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) {
  6143. add(v0, 0);
  6144. add(v3, 0);
  6145. } else {
  6146. var a = 3 * (v1 - v2) - v0 + v3,
  6147. b = 2 * (v0 + v2) - 4 * v1,
  6148. c = v1 - v0,
  6149. count = Numerical.solveQuadratic(a, b, c, roots),
  6150. tMin = 1e-8,
  6151. tMax = 1 - tMin;
  6152. add(v3, 0);
  6153. for (var i = 0; i < count; i++) {
  6154. var t = roots[i],
  6155. u = 1 - t;
  6156. if (tMin <= t && t <= tMax)
  6157. add(u * u * u * v0
  6158. + 3 * u * u * t * v1
  6159. + 3 * u * t * t * v2
  6160. + t * t * t * v3,
  6161. padding);
  6162. }
  6163. }
  6164. }
  6165. }
  6166. }}, Base.each(
  6167. ['getBounds', 'getStrokeBounds', 'getHandleBounds'],
  6168. function(name) {
  6169. this[name] = function() {
  6170. if (!this._bounds)
  6171. this._bounds = {};
  6172. var bounds = this._bounds[name];
  6173. if (!bounds) {
  6174. bounds = this._bounds[name] = Path[name](
  6175. [this._segment1, this._segment2], false, this._path);
  6176. }
  6177. return bounds.clone();
  6178. };
  6179. },
  6180. {
  6181. }), Base.each({
  6182. isStraight: function(p1, h1, h2, p2) {
  6183. if (h1.isZero() && h2.isZero()) {
  6184. return true;
  6185. } else {
  6186. var v = p2.subtract(p1);
  6187. if (v.isZero()) {
  6188. return false;
  6189. } else if (v.isCollinear(h1) && v.isCollinear(h2)) {
  6190. var l = new Line(p1, p2),
  6191. epsilon = 1e-7;
  6192. if (l.getDistance(p1.add(h1)) < epsilon &&
  6193. l.getDistance(p2.add(h2)) < epsilon) {
  6194. var div = v.dot(v),
  6195. s1 = v.dot(h1) / div,
  6196. s2 = v.dot(h2) / div;
  6197. return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1;
  6198. }
  6199. }
  6200. }
  6201. return false;
  6202. },
  6203. isLinear: function(p1, h1, h2, p2) {
  6204. var third = p2.subtract(p1).divide(3);
  6205. return h1.equals(third) && h2.negate().equals(third);
  6206. }
  6207. }, function(test, name) {
  6208. this[name] = function(epsilon) {
  6209. var seg1 = this._segment1,
  6210. seg2 = this._segment2;
  6211. return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point,
  6212. epsilon);
  6213. };
  6214. this.statics[name] = function(v, epsilon) {
  6215. var x0 = v[0], y0 = v[1],
  6216. x3 = v[6], y3 = v[7];
  6217. return test(
  6218. new Point(x0, y0),
  6219. new Point(v[2] - x0, v[3] - y0),
  6220. new Point(v[4] - x3, v[5] - y3),
  6221. new Point(x3, y3), epsilon);
  6222. };
  6223. }, {
  6224. statics: {},
  6225. hasHandles: function() {
  6226. return !this._segment1._handleOut.isZero()
  6227. || !this._segment2._handleIn.isZero();
  6228. },
  6229. hasLength: function(epsilon) {
  6230. return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles())
  6231. && this.getLength() > (epsilon || 0);
  6232. },
  6233. isCollinear: function(curve) {
  6234. return curve && this.isStraight() && curve.isStraight()
  6235. && this.getLine().isCollinear(curve.getLine());
  6236. },
  6237. isHorizontal: function() {
  6238. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).y)
  6239. < 1e-8;
  6240. },
  6241. isVertical: function() {
  6242. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).x)
  6243. < 1e-8;
  6244. }
  6245. }), {
  6246. beans: false,
  6247. getLocationAt: function(offset, _isTime) {
  6248. return this.getLocationAtTime(
  6249. _isTime ? offset : this.getTimeAt(offset));
  6250. },
  6251. getLocationAtTime: function(t) {
  6252. return t != null && t >= 0 && t <= 1
  6253. ? new CurveLocation(this, t)
  6254. : null;
  6255. },
  6256. getTimeAt: function(offset, start) {
  6257. return Curve.getTimeAt(this.getValues(), offset, start);
  6258. },
  6259. getParameterAt: '#getTimeAt',
  6260. getTimesWithTangent: function () {
  6261. var tangent = Point.read(arguments);
  6262. return tangent.isZero()
  6263. ? []
  6264. : Curve.getTimesWithTangent(this.getValues(), tangent);
  6265. },
  6266. getOffsetAtTime: function(t) {
  6267. return this.getPartLength(0, t);
  6268. },
  6269. getLocationOf: function() {
  6270. return this.getLocationAtTime(this.getTimeOf(Point.read(arguments)));
  6271. },
  6272. getOffsetOf: function() {
  6273. var loc = this.getLocationOf.apply(this, arguments);
  6274. return loc ? loc.getOffset() : null;
  6275. },
  6276. getTimeOf: function() {
  6277. return Curve.getTimeOf(this.getValues(), Point.read(arguments));
  6278. },
  6279. getParameterOf: '#getTimeOf',
  6280. getNearestLocation: function() {
  6281. var point = Point.read(arguments),
  6282. values = this.getValues(),
  6283. t = Curve.getNearestTime(values, point),
  6284. pt = Curve.getPoint(values, t);
  6285. return new CurveLocation(this, t, pt, null, point.getDistance(pt));
  6286. },
  6287. getNearestPoint: function() {
  6288. var loc = this.getNearestLocation.apply(this, arguments);
  6289. return loc ? loc.getPoint() : loc;
  6290. }
  6291. },
  6292. new function() {
  6293. var methods = ['getPoint', 'getTangent', 'getNormal', 'getWeightedTangent',
  6294. 'getWeightedNormal', 'getCurvature'];
  6295. return Base.each(methods,
  6296. function(name) {
  6297. this[name + 'At'] = function(location, _isTime) {
  6298. var values = this.getValues();
  6299. return Curve[name](values, _isTime ? location
  6300. : Curve.getTimeAt(values, location));
  6301. };
  6302. this[name + 'AtTime'] = function(time) {
  6303. return Curve[name](this.getValues(), time);
  6304. };
  6305. }, {
  6306. statics: {
  6307. _evaluateMethods: methods
  6308. }
  6309. }
  6310. );
  6311. },
  6312. new function() {
  6313. function getLengthIntegrand(v) {
  6314. var x0 = v[0], y0 = v[1],
  6315. x1 = v[2], y1 = v[3],
  6316. x2 = v[4], y2 = v[5],
  6317. x3 = v[6], y3 = v[7],
  6318. ax = 9 * (x1 - x2) + 3 * (x3 - x0),
  6319. bx = 6 * (x0 + x2) - 12 * x1,
  6320. cx = 3 * (x1 - x0),
  6321. ay = 9 * (y1 - y2) + 3 * (y3 - y0),
  6322. by = 6 * (y0 + y2) - 12 * y1,
  6323. cy = 3 * (y1 - y0);
  6324. return function(t) {
  6325. var dx = (ax * t + bx) * t + cx,
  6326. dy = (ay * t + by) * t + cy;
  6327. return Math.sqrt(dx * dx + dy * dy);
  6328. };
  6329. }
  6330. function getIterations(a, b) {
  6331. return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
  6332. }
  6333. function evaluate(v, t, type, normalized) {
  6334. if (t == null || t < 0 || t > 1)
  6335. return null;
  6336. var x0 = v[0], y0 = v[1],
  6337. x1 = v[2], y1 = v[3],
  6338. x2 = v[4], y2 = v[5],
  6339. x3 = v[6], y3 = v[7],
  6340. isZero = Numerical.isZero;
  6341. if (isZero(x1 - x0) && isZero(y1 - y0)) {
  6342. x1 = x0;
  6343. y1 = y0;
  6344. }
  6345. if (isZero(x2 - x3) && isZero(y2 - y3)) {
  6346. x2 = x3;
  6347. y2 = y3;
  6348. }
  6349. var cx = 3 * (x1 - x0),
  6350. bx = 3 * (x2 - x1) - cx,
  6351. ax = x3 - x0 - cx - bx,
  6352. cy = 3 * (y1 - y0),
  6353. by = 3 * (y2 - y1) - cy,
  6354. ay = y3 - y0 - cy - by,
  6355. x, y;
  6356. if (type === 0) {
  6357. x = t === 0 ? x0 : t === 1 ? x3
  6358. : ((ax * t + bx) * t + cx) * t + x0;
  6359. y = t === 0 ? y0 : t === 1 ? y3
  6360. : ((ay * t + by) * t + cy) * t + y0;
  6361. } else {
  6362. var tMin = 1e-8,
  6363. tMax = 1 - tMin;
  6364. if (t < tMin) {
  6365. x = cx;
  6366. y = cy;
  6367. } else if (t > tMax) {
  6368. x = 3 * (x3 - x2);
  6369. y = 3 * (y3 - y2);
  6370. } else {
  6371. x = (3 * ax * t + 2 * bx) * t + cx;
  6372. y = (3 * ay * t + 2 * by) * t + cy;
  6373. }
  6374. if (normalized) {
  6375. if (x === 0 && y === 0 && (t < tMin || t > tMax)) {
  6376. x = x2 - x1;
  6377. y = y2 - y1;
  6378. }
  6379. var len = Math.sqrt(x * x + y * y);
  6380. if (len) {
  6381. x /= len;
  6382. y /= len;
  6383. }
  6384. }
  6385. if (type === 3) {
  6386. var x2 = 6 * ax * t + 2 * bx,
  6387. y2 = 6 * ay * t + 2 * by,
  6388. d = Math.pow(x * x + y * y, 3 / 2);
  6389. x = d !== 0 ? (x * y2 - y * x2) / d : 0;
  6390. y = 0;
  6391. }
  6392. }
  6393. return type === 2 ? new Point(y, -x) : new Point(x, y);
  6394. }
  6395. return { statics: {
  6396. classify: function(v) {
  6397. var x0 = v[0], y0 = v[1],
  6398. x1 = v[2], y1 = v[3],
  6399. x2 = v[4], y2 = v[5],
  6400. x3 = v[6], y3 = v[7],
  6401. a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2,
  6402. a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3,
  6403. a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0,
  6404. d3 = 3 * a3,
  6405. d2 = d3 - a2,
  6406. d1 = d2 - a2 + a1,
  6407. l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3),
  6408. s = l !== 0 ? 1 / l : 0,
  6409. isZero = Numerical.isZero,
  6410. serpentine = 'serpentine';
  6411. d1 *= s;
  6412. d2 *= s;
  6413. d3 *= s;
  6414. function type(type, t1, t2) {
  6415. var hasRoots = t1 !== undefined,
  6416. t1Ok = hasRoots && t1 > 0 && t1 < 1,
  6417. t2Ok = hasRoots && t2 > 0 && t2 < 1;
  6418. if (hasRoots && (!(t1Ok || t2Ok)
  6419. || type === 'loop' && !(t1Ok && t2Ok))) {
  6420. type = 'arch';
  6421. t1Ok = t2Ok = false;
  6422. }
  6423. return {
  6424. type: type,
  6425. roots: t1Ok || t2Ok
  6426. ? t1Ok && t2Ok
  6427. ? t1 < t2 ? [t1, t2] : [t2, t1]
  6428. : [t1Ok ? t1 : t2]
  6429. : null
  6430. };
  6431. }
  6432. if (isZero(d1)) {
  6433. return isZero(d2)
  6434. ? type(isZero(d3) ? 'line' : 'quadratic')
  6435. : type(serpentine, d3 / (3 * d2));
  6436. }
  6437. var d = 3 * d2 * d2 - 4 * d1 * d3;
  6438. if (isZero(d)) {
  6439. return type('cusp', d2 / (2 * d1));
  6440. }
  6441. var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d),
  6442. f2 = 2 * d1;
  6443. return type(d > 0 ? serpentine : 'loop',
  6444. (d2 + f1) / f2,
  6445. (d2 - f1) / f2);
  6446. },
  6447. getLength: function(v, a, b, ds) {
  6448. if (a === undefined)
  6449. a = 0;
  6450. if (b === undefined)
  6451. b = 1;
  6452. if (Curve.isStraight(v)) {
  6453. var c = v;
  6454. if (b < 1) {
  6455. c = Curve.subdivide(c, b)[0];
  6456. a /= b;
  6457. }
  6458. if (a > 0) {
  6459. c = Curve.subdivide(c, a)[1];
  6460. }
  6461. var dx = c[6] - c[0],
  6462. dy = c[7] - c[1];
  6463. return Math.sqrt(dx * dx + dy * dy);
  6464. }
  6465. return Numerical.integrate(ds || getLengthIntegrand(v), a, b,
  6466. getIterations(a, b));
  6467. },
  6468. getTimeAt: function(v, offset, start) {
  6469. if (start === undefined)
  6470. start = offset < 0 ? 1 : 0;
  6471. if (offset === 0)
  6472. return start;
  6473. var abs = Math.abs,
  6474. epsilon = 1e-12,
  6475. forward = offset > 0,
  6476. a = forward ? start : 0,
  6477. b = forward ? 1 : start,
  6478. ds = getLengthIntegrand(v),
  6479. rangeLength = Curve.getLength(v, a, b, ds),
  6480. diff = abs(offset) - rangeLength;
  6481. if (abs(diff) < epsilon) {
  6482. return forward ? b : a;
  6483. } else if (diff > epsilon) {
  6484. return null;
  6485. }
  6486. var guess = offset / rangeLength,
  6487. length = 0;
  6488. function f(t) {
  6489. length += Numerical.integrate(ds, start, t,
  6490. getIterations(start, t));
  6491. start = t;
  6492. return length - offset;
  6493. }
  6494. return Numerical.findRoot(f, ds, start + guess, a, b, 32,
  6495. 1e-12);
  6496. },
  6497. getPoint: function(v, t) {
  6498. return evaluate(v, t, 0, false);
  6499. },
  6500. getTangent: function(v, t) {
  6501. return evaluate(v, t, 1, true);
  6502. },
  6503. getWeightedTangent: function(v, t) {
  6504. return evaluate(v, t, 1, false);
  6505. },
  6506. getNormal: function(v, t) {
  6507. return evaluate(v, t, 2, true);
  6508. },
  6509. getWeightedNormal: function(v, t) {
  6510. return evaluate(v, t, 2, false);
  6511. },
  6512. getCurvature: function(v, t) {
  6513. return evaluate(v, t, 3, false).x;
  6514. },
  6515. getPeaks: function(v) {
  6516. var x0 = v[0], y0 = v[1],
  6517. x1 = v[2], y1 = v[3],
  6518. x2 = v[4], y2 = v[5],
  6519. x3 = v[6], y3 = v[7],
  6520. ax = -x0 + 3 * x1 - 3 * x2 + x3,
  6521. bx = 3 * x0 - 6 * x1 + 3 * x2,
  6522. cx = -3 * x0 + 3 * x1,
  6523. ay = -y0 + 3 * y1 - 3 * y2 + y3,
  6524. by = 3 * y0 - 6 * y1 + 3 * y2,
  6525. cy = -3 * y0 + 3 * y1,
  6526. tMin = 1e-8,
  6527. tMax = 1 - tMin,
  6528. roots = [];
  6529. Numerical.solveCubic(
  6530. 9 * (ax * ax + ay * ay),
  6531. 9 * (ax * bx + by * ay),
  6532. 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay),
  6533. (cx * bx + by * cy),
  6534. roots, tMin, tMax);
  6535. return roots.sort();
  6536. }
  6537. }};
  6538. },
  6539. new function() {
  6540. function addLocation(locations, include, c1, t1, c2, t2, overlap) {
  6541. var excludeStart = !overlap && c1.getPrevious() === c2,
  6542. excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2,
  6543. tMin = 1e-8,
  6544. tMax = 1 - tMin;
  6545. if (t1 !== null && t1 >= (excludeStart ? tMin : 0) &&
  6546. t1 <= (excludeEnd ? tMax : 1)) {
  6547. if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) &&
  6548. t2 <= (excludeStart ? tMax : 1)) {
  6549. var loc1 = new CurveLocation(c1, t1, null, overlap),
  6550. loc2 = new CurveLocation(c2, t2, null, overlap);
  6551. loc1._intersection = loc2;
  6552. loc2._intersection = loc1;
  6553. if (!include || include(loc1)) {
  6554. CurveLocation.insert(locations, loc1, true);
  6555. }
  6556. }
  6557. }
  6558. }
  6559. function addCurveIntersections(v1, v2, c1, c2, locations, include, flip,
  6560. recursion, calls, tMin, tMax, uMin, uMax) {
  6561. if (++calls >= 4096 || ++recursion >= 40)
  6562. return calls;
  6563. var fatLineEpsilon = 1e-9,
  6564. q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],
  6565. getSignedDistance = Line.getSignedDistance,
  6566. d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]),
  6567. d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]),
  6568. factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
  6569. dMin = factor * Math.min(0, d1, d2),
  6570. dMax = factor * Math.max(0, d1, d2),
  6571. dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),
  6572. dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),
  6573. dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),
  6574. dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),
  6575. hull = getConvexHull(dp0, dp1, dp2, dp3),
  6576. top = hull[0],
  6577. bottom = hull[1],
  6578. tMinClip,
  6579. tMaxClip;
  6580. if (d1 === 0 && d2 === 0
  6581. && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0
  6582. || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null
  6583. || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(),
  6584. dMin, dMax)) == null)
  6585. return calls;
  6586. var tMinNew = tMin + (tMax - tMin) * tMinClip,
  6587. tMaxNew = tMin + (tMax - tMin) * tMaxClip;
  6588. if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) {
  6589. var t = (tMinNew + tMaxNew) / 2,
  6590. u = (uMin + uMax) / 2;
  6591. addLocation(locations, include,
  6592. flip ? c2 : c1, flip ? u : t,
  6593. flip ? c1 : c2, flip ? t : u);
  6594. } else {
  6595. v1 = Curve.getPart(v1, tMinClip, tMaxClip);
  6596. var uDiff = uMax - uMin;
  6597. if (tMaxClip - tMinClip > 0.8) {
  6598. if (tMaxNew - tMinNew > uDiff) {
  6599. var parts = Curve.subdivide(v1, 0.5),
  6600. t = (tMinNew + tMaxNew) / 2;
  6601. calls = addCurveIntersections(
  6602. v2, parts[0], c2, c1, locations, include, !flip,
  6603. recursion, calls, uMin, uMax, tMinNew, t);
  6604. calls = addCurveIntersections(
  6605. v2, parts[1], c2, c1, locations, include, !flip,
  6606. recursion, calls, uMin, uMax, t, tMaxNew);
  6607. } else {
  6608. var parts = Curve.subdivide(v2, 0.5),
  6609. u = (uMin + uMax) / 2;
  6610. calls = addCurveIntersections(
  6611. parts[0], v1, c2, c1, locations, include, !flip,
  6612. recursion, calls, uMin, u, tMinNew, tMaxNew);
  6613. calls = addCurveIntersections(
  6614. parts[1], v1, c2, c1, locations, include, !flip,
  6615. recursion, calls, u, uMax, tMinNew, tMaxNew);
  6616. }
  6617. } else {
  6618. if (uDiff === 0 || uDiff >= fatLineEpsilon) {
  6619. calls = addCurveIntersections(
  6620. v2, v1, c2, c1, locations, include, !flip,
  6621. recursion, calls, uMin, uMax, tMinNew, tMaxNew);
  6622. } else {
  6623. calls = addCurveIntersections(
  6624. v1, v2, c1, c2, locations, include, flip,
  6625. recursion, calls, tMinNew, tMaxNew, uMin, uMax);
  6626. }
  6627. }
  6628. }
  6629. return calls;
  6630. }
  6631. function getConvexHull(dq0, dq1, dq2, dq3) {
  6632. var p0 = [ 0, dq0 ],
  6633. p1 = [ 1 / 3, dq1 ],
  6634. p2 = [ 2 / 3, dq2 ],
  6635. p3 = [ 1, dq3 ],
  6636. dist1 = dq1 - (2 * dq0 + dq3) / 3,
  6637. dist2 = dq2 - (dq0 + 2 * dq3) / 3,
  6638. hull;
  6639. if (dist1 * dist2 < 0) {
  6640. hull = [[p0, p1, p3], [p0, p2, p3]];
  6641. } else {
  6642. var distRatio = dist1 / dist2;
  6643. hull = [
  6644. distRatio >= 2 ? [p0, p1, p3]
  6645. : distRatio <= 0.5 ? [p0, p2, p3]
  6646. : [p0, p1, p2, p3],
  6647. [p0, p3]
  6648. ];
  6649. }
  6650. return (dist1 || dist2) < 0 ? hull.reverse() : hull;
  6651. }
  6652. function clipConvexHull(hullTop, hullBottom, dMin, dMax) {
  6653. if (hullTop[0][1] < dMin) {
  6654. return clipConvexHullPart(hullTop, true, dMin);
  6655. } else if (hullBottom[0][1] > dMax) {
  6656. return clipConvexHullPart(hullBottom, false, dMax);
  6657. } else {
  6658. return hullTop[0][0];
  6659. }
  6660. }
  6661. function clipConvexHullPart(part, top, threshold) {
  6662. var px = part[0][0],
  6663. py = part[0][1];
  6664. for (var i = 1, l = part.length; i < l; i++) {
  6665. var qx = part[i][0],
  6666. qy = part[i][1];
  6667. if (top ? qy >= threshold : qy <= threshold) {
  6668. return qy === threshold ? qx
  6669. : px + (threshold - py) * (qx - px) / (qy - py);
  6670. }
  6671. px = qx;
  6672. py = qy;
  6673. }
  6674. return null;
  6675. }
  6676. function getCurveLineIntersections(v, px, py, vx, vy) {
  6677. var isZero = Numerical.isZero;
  6678. if (isZero(vx) && isZero(vy)) {
  6679. var t = Curve.getTimeOf(v, new Point(px, py));
  6680. return t === null ? [] : [t];
  6681. }
  6682. var angle = Math.atan2(-vy, vx),
  6683. sin = Math.sin(angle),
  6684. cos = Math.cos(angle),
  6685. rv = [],
  6686. roots = [];
  6687. for (var i = 0; i < 8; i += 2) {
  6688. var x = v[i] - px,
  6689. y = v[i + 1] - py;
  6690. rv.push(
  6691. x * cos - y * sin,
  6692. x * sin + y * cos);
  6693. }
  6694. Curve.solveCubic(rv, 1, 0, roots, 0, 1);
  6695. return roots;
  6696. }
  6697. function addCurveLineIntersections(v1, v2, c1, c2, locations, include,
  6698. flip) {
  6699. var x1 = v2[0], y1 = v2[1],
  6700. x2 = v2[6], y2 = v2[7],
  6701. roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1);
  6702. for (var i = 0, l = roots.length; i < l; i++) {
  6703. var t1 = roots[i],
  6704. p1 = Curve.getPoint(v1, t1),
  6705. t2 = Curve.getTimeOf(v2, p1);
  6706. if (t2 !== null) {
  6707. addLocation(locations, include,
  6708. flip ? c2 : c1, flip ? t2 : t1,
  6709. flip ? c1 : c2, flip ? t1 : t2);
  6710. }
  6711. }
  6712. }
  6713. function addLineIntersection(v1, v2, c1, c2, locations, include) {
  6714. var pt = Line.intersect(
  6715. v1[0], v1[1], v1[6], v1[7],
  6716. v2[0], v2[1], v2[6], v2[7]);
  6717. if (pt) {
  6718. addLocation(locations, include,
  6719. c1, Curve.getTimeOf(v1, pt),
  6720. c2, Curve.getTimeOf(v2, pt));
  6721. }
  6722. }
  6723. function getCurveIntersections(v1, v2, c1, c2, locations, include) {
  6724. var epsilon = 1e-12,
  6725. min = Math.min,
  6726. max = Math.max;
  6727. if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon >
  6728. min(v2[0], v2[2], v2[4], v2[6]) &&
  6729. min(v1[0], v1[2], v1[4], v1[6]) - epsilon <
  6730. max(v2[0], v2[2], v2[4], v2[6]) &&
  6731. max(v1[1], v1[3], v1[5], v1[7]) + epsilon >
  6732. min(v2[1], v2[3], v2[5], v2[7]) &&
  6733. min(v1[1], v1[3], v1[5], v1[7]) - epsilon <
  6734. max(v2[1], v2[3], v2[5], v2[7])) {
  6735. var overlaps = getOverlaps(v1, v2);
  6736. if (overlaps) {
  6737. for (var i = 0; i < 2; i++) {
  6738. var overlap = overlaps[i];
  6739. addLocation(locations, include,
  6740. c1, overlap[0],
  6741. c2, overlap[1], true);
  6742. }
  6743. } else {
  6744. var straight1 = Curve.isStraight(v1),
  6745. straight2 = Curve.isStraight(v2),
  6746. straight = straight1 && straight2,
  6747. flip = straight1 && !straight2,
  6748. before = locations.length;
  6749. (straight
  6750. ? addLineIntersection
  6751. : straight1 || straight2
  6752. ? addCurveLineIntersections
  6753. : addCurveIntersections)(
  6754. flip ? v2 : v1, flip ? v1 : v2,
  6755. flip ? c2 : c1, flip ? c1 : c2,
  6756. locations, include, flip,
  6757. 0, 0, 0, 1, 0, 1);
  6758. if (!straight || locations.length === before) {
  6759. for (var i = 0; i < 4; i++) {
  6760. var t1 = i >> 1,
  6761. t2 = i & 1,
  6762. i1 = t1 * 6,
  6763. i2 = t2 * 6,
  6764. p1 = new Point(v1[i1], v1[i1 + 1]),
  6765. p2 = new Point(v2[i2], v2[i2 + 1]);
  6766. if (p1.isClose(p2, epsilon)) {
  6767. addLocation(locations, include,
  6768. c1, t1,
  6769. c2, t2);
  6770. }
  6771. }
  6772. }
  6773. }
  6774. }
  6775. return locations;
  6776. }
  6777. function getSelfIntersection(v1, c1, locations, include) {
  6778. var info = Curve.classify(v1);
  6779. if (info.type === 'loop') {
  6780. var roots = info.roots;
  6781. addLocation(locations, include,
  6782. c1, roots[0],
  6783. c1, roots[1]);
  6784. }
  6785. return locations;
  6786. }
  6787. function getIntersections(curves1, curves2, include, matrix1, matrix2,
  6788. _returnFirst) {
  6789. var epsilon = 1e-7,
  6790. self = !curves2;
  6791. if (self)
  6792. curves2 = curves1;
  6793. var length1 = curves1.length,
  6794. length2 = curves2.length,
  6795. values1 = new Array(length1),
  6796. values2 = self ? values1 : new Array(length2),
  6797. locations = [];
  6798. for (var i = 0; i < length1; i++) {
  6799. values1[i] = curves1[i].getValues(matrix1);
  6800. }
  6801. if (!self) {
  6802. for (var i = 0; i < length2; i++) {
  6803. values2[i] = curves2[i].getValues(matrix2);
  6804. }
  6805. }
  6806. var boundsCollisions = CollisionDetection.findCurveBoundsCollisions(
  6807. values1, values2, epsilon);
  6808. for (var index1 = 0; index1 < length1; index1++) {
  6809. var curve1 = curves1[index1],
  6810. v1 = values1[index1];
  6811. if (self) {
  6812. getSelfIntersection(v1, curve1, locations, include);
  6813. }
  6814. var collisions1 = boundsCollisions[index1];
  6815. if (collisions1) {
  6816. for (var j = 0; j < collisions1.length; j++) {
  6817. if (_returnFirst && locations.length)
  6818. return locations;
  6819. var index2 = collisions1[j];
  6820. if (!self || index2 > index1) {
  6821. var curve2 = curves2[index2],
  6822. v2 = values2[index2];
  6823. getCurveIntersections(
  6824. v1, v2, curve1, curve2, locations, include);
  6825. }
  6826. }
  6827. }
  6828. }
  6829. return locations;
  6830. }
  6831. function getOverlaps(v1, v2) {
  6832. function getSquaredLineLength(v) {
  6833. var x = v[6] - v[0],
  6834. y = v[7] - v[1];
  6835. return x * x + y * y;
  6836. }
  6837. var abs = Math.abs,
  6838. getDistance = Line.getDistance,
  6839. timeEpsilon = 1e-8,
  6840. geomEpsilon = 1e-7,
  6841. straight1 = Curve.isStraight(v1),
  6842. straight2 = Curve.isStraight(v2),
  6843. straightBoth = straight1 && straight2,
  6844. flip = getSquaredLineLength(v1) < getSquaredLineLength(v2),
  6845. l1 = flip ? v2 : v1,
  6846. l2 = flip ? v1 : v2,
  6847. px = l1[0], py = l1[1],
  6848. vx = l1[6] - px, vy = l1[7] - py;
  6849. if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon &&
  6850. getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) {
  6851. if (!straightBoth &&
  6852. getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon &&
  6853. getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon &&
  6854. getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon &&
  6855. getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) {
  6856. straight1 = straight2 = straightBoth = true;
  6857. }
  6858. } else if (straightBoth) {
  6859. return null;
  6860. }
  6861. if (straight1 ^ straight2) {
  6862. return null;
  6863. }
  6864. var v = [v1, v2],
  6865. pairs = [];
  6866. for (var i = 0; i < 4 && pairs.length < 2; i++) {
  6867. var i1 = i & 1,
  6868. i2 = i1 ^ 1,
  6869. t1 = i >> 1,
  6870. t2 = Curve.getTimeOf(v[i1], new Point(
  6871. v[i2][t1 ? 6 : 0],
  6872. v[i2][t1 ? 7 : 1]));
  6873. if (t2 != null) {
  6874. var pair = i1 ? [t1, t2] : [t2, t1];
  6875. if (!pairs.length ||
  6876. abs(pair[0] - pairs[0][0]) > timeEpsilon &&
  6877. abs(pair[1] - pairs[0][1]) > timeEpsilon) {
  6878. pairs.push(pair);
  6879. }
  6880. }
  6881. if (i > 2 && !pairs.length)
  6882. break;
  6883. }
  6884. if (pairs.length !== 2) {
  6885. pairs = null;
  6886. } else if (!straightBoth) {
  6887. var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]),
  6888. o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]);
  6889. if (abs(o2[2] - o1[2]) > geomEpsilon ||
  6890. abs(o2[3] - o1[3]) > geomEpsilon ||
  6891. abs(o2[4] - o1[4]) > geomEpsilon ||
  6892. abs(o2[5] - o1[5]) > geomEpsilon)
  6893. pairs = null;
  6894. }
  6895. return pairs;
  6896. }
  6897. function getTimesWithTangent(v, tangent) {
  6898. var x0 = v[0], y0 = v[1],
  6899. x1 = v[2], y1 = v[3],
  6900. x2 = v[4], y2 = v[5],
  6901. x3 = v[6], y3 = v[7],
  6902. normalized = tangent.normalize(),
  6903. tx = normalized.x,
  6904. ty = normalized.y,
  6905. ax = 3 * x3 - 9 * x2 + 9 * x1 - 3 * x0,
  6906. ay = 3 * y3 - 9 * y2 + 9 * y1 - 3 * y0,
  6907. bx = 6 * x2 - 12 * x1 + 6 * x0,
  6908. by = 6 * y2 - 12 * y1 + 6 * y0,
  6909. cx = 3 * x1 - 3 * x0,
  6910. cy = 3 * y1 - 3 * y0,
  6911. den = 2 * ax * ty - 2 * ay * tx,
  6912. times = [];
  6913. if (Math.abs(den) < Numerical.CURVETIME_EPSILON) {
  6914. var num = ax * cy - ay * cx,
  6915. den = ax * by - ay * bx;
  6916. if (den != 0) {
  6917. var t = -num / den;
  6918. if (t >= 0 && t <= 1) times.push(t);
  6919. }
  6920. } else {
  6921. var delta = (bx * bx - 4 * ax * cx) * ty * ty +
  6922. (-2 * bx * by + 4 * ay * cx + 4 * ax * cy) * tx * ty +
  6923. (by * by - 4 * ay * cy) * tx * tx,
  6924. k = bx * ty - by * tx;
  6925. if (delta >= 0 && den != 0) {
  6926. var d = Math.sqrt(delta),
  6927. t0 = -(k + d) / den,
  6928. t1 = (-k + d) / den;
  6929. if (t0 >= 0 && t0 <= 1) times.push(t0);
  6930. if (t1 >= 0 && t1 <= 1) times.push(t1);
  6931. }
  6932. }
  6933. return times;
  6934. }
  6935. return {
  6936. getIntersections: function(curve) {
  6937. var v1 = this.getValues(),
  6938. v2 = curve && curve !== this && curve.getValues();
  6939. return v2 ? getCurveIntersections(v1, v2, this, curve, [])
  6940. : getSelfIntersection(v1, this, []);
  6941. },
  6942. statics: {
  6943. getOverlaps: getOverlaps,
  6944. getIntersections: getIntersections,
  6945. getCurveLineIntersections: getCurveLineIntersections,
  6946. getTimesWithTangent: getTimesWithTangent
  6947. }
  6948. };
  6949. });
  6950. var CurveLocation = Base.extend({
  6951. _class: 'CurveLocation',
  6952. initialize: function CurveLocation(curve, time, point, _overlap, _distance) {
  6953. if (time >= 0.99999999) {
  6954. var next = curve.getNext();
  6955. if (next) {
  6956. time = 0;
  6957. curve = next;
  6958. }
  6959. }
  6960. this._setCurve(curve);
  6961. this._time = time;
  6962. this._point = point || curve.getPointAtTime(time);
  6963. this._overlap = _overlap;
  6964. this._distance = _distance;
  6965. this._intersection = this._next = this._previous = null;
  6966. },
  6967. _setPath: function(path) {
  6968. this._path = path;
  6969. this._version = path ? path._version : 0;
  6970. },
  6971. _setCurve: function(curve) {
  6972. this._setPath(curve._path);
  6973. this._curve = curve;
  6974. this._segment = null;
  6975. this._segment1 = curve._segment1;
  6976. this._segment2 = curve._segment2;
  6977. },
  6978. _setSegment: function(segment) {
  6979. var curve = segment.getCurve();
  6980. if (curve) {
  6981. this._setCurve(curve);
  6982. } else {
  6983. this._setPath(segment._path);
  6984. this._segment1 = segment;
  6985. this._segment2 = null;
  6986. }
  6987. this._segment = segment;
  6988. this._time = segment === this._segment1 ? 0 : 1;
  6989. this._point = segment._point.clone();
  6990. },
  6991. getSegment: function() {
  6992. var segment = this._segment;
  6993. if (!segment) {
  6994. var curve = this.getCurve(),
  6995. time = this.getTime();
  6996. if (time === 0) {
  6997. segment = curve._segment1;
  6998. } else if (time === 1) {
  6999. segment = curve._segment2;
  7000. } else if (time != null) {
  7001. segment = curve.getPartLength(0, time)
  7002. < curve.getPartLength(time, 1)
  7003. ? curve._segment1
  7004. : curve._segment2;
  7005. }
  7006. this._segment = segment;
  7007. }
  7008. return segment;
  7009. },
  7010. getCurve: function() {
  7011. var path = this._path,
  7012. that = this;
  7013. if (path && path._version !== this._version) {
  7014. this._time = this._offset = this._curveOffset = this._curve = null;
  7015. }
  7016. function trySegment(segment) {
  7017. var curve = segment && segment.getCurve();
  7018. if (curve && (that._time = curve.getTimeOf(that._point)) != null) {
  7019. that._setCurve(curve);
  7020. return curve;
  7021. }
  7022. }
  7023. return this._curve
  7024. || trySegment(this._segment)
  7025. || trySegment(this._segment1)
  7026. || trySegment(this._segment2.getPrevious());
  7027. },
  7028. getPath: function() {
  7029. var curve = this.getCurve();
  7030. return curve && curve._path;
  7031. },
  7032. getIndex: function() {
  7033. var curve = this.getCurve();
  7034. return curve && curve.getIndex();
  7035. },
  7036. getTime: function() {
  7037. var curve = this.getCurve(),
  7038. time = this._time;
  7039. return curve && time == null
  7040. ? this._time = curve.getTimeOf(this._point)
  7041. : time;
  7042. },
  7043. getParameter: '#getTime',
  7044. getPoint: function() {
  7045. return this._point;
  7046. },
  7047. getOffset: function() {
  7048. var offset = this._offset;
  7049. if (offset == null) {
  7050. offset = 0;
  7051. var path = this.getPath(),
  7052. index = this.getIndex();
  7053. if (path && index != null) {
  7054. var curves = path.getCurves();
  7055. for (var i = 0; i < index; i++)
  7056. offset += curves[i].getLength();
  7057. }
  7058. this._offset = offset += this.getCurveOffset();
  7059. }
  7060. return offset;
  7061. },
  7062. getCurveOffset: function() {
  7063. var offset = this._curveOffset;
  7064. if (offset == null) {
  7065. var curve = this.getCurve(),
  7066. time = this.getTime();
  7067. this._curveOffset = offset = time != null && curve
  7068. && curve.getPartLength(0, time);
  7069. }
  7070. return offset;
  7071. },
  7072. getIntersection: function() {
  7073. return this._intersection;
  7074. },
  7075. getDistance: function() {
  7076. return this._distance;
  7077. },
  7078. divide: function() {
  7079. var curve = this.getCurve(),
  7080. res = curve && curve.divideAtTime(this.getTime());
  7081. if (res) {
  7082. this._setSegment(res._segment1);
  7083. }
  7084. return res;
  7085. },
  7086. split: function() {
  7087. var curve = this.getCurve(),
  7088. path = curve._path,
  7089. res = curve && curve.splitAtTime(this.getTime());
  7090. if (res) {
  7091. this._setSegment(path.getLastSegment());
  7092. }
  7093. return res;
  7094. },
  7095. equals: function(loc, _ignoreOther) {
  7096. var res = this === loc;
  7097. if (!res && loc instanceof CurveLocation) {
  7098. var c1 = this.getCurve(),
  7099. c2 = loc.getCurve(),
  7100. p1 = c1._path,
  7101. p2 = c2._path;
  7102. if (p1 === p2) {
  7103. var abs = Math.abs,
  7104. epsilon = 1e-7,
  7105. diff = abs(this.getOffset() - loc.getOffset()),
  7106. i1 = !_ignoreOther && this._intersection,
  7107. i2 = !_ignoreOther && loc._intersection;
  7108. res = (diff < epsilon
  7109. || p1 && abs(p1.getLength() - diff) < epsilon)
  7110. && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true));
  7111. }
  7112. }
  7113. return res;
  7114. },
  7115. toString: function() {
  7116. var parts = [],
  7117. point = this.getPoint(),
  7118. f = Formatter.instance;
  7119. if (point)
  7120. parts.push('point: ' + point);
  7121. var index = this.getIndex();
  7122. if (index != null)
  7123. parts.push('index: ' + index);
  7124. var time = this.getTime();
  7125. if (time != null)
  7126. parts.push('time: ' + f.number(time));
  7127. if (this._distance != null)
  7128. parts.push('distance: ' + f.number(this._distance));
  7129. return '{ ' + parts.join(', ') + ' }';
  7130. },
  7131. isTouching: function() {
  7132. var inter = this._intersection;
  7133. if (inter && this.getTangent().isCollinear(inter.getTangent())) {
  7134. var curve1 = this.getCurve(),
  7135. curve2 = inter.getCurve();
  7136. return !(curve1.isStraight() && curve2.isStraight()
  7137. && curve1.getLine().intersect(curve2.getLine()));
  7138. }
  7139. return false;
  7140. },
  7141. isCrossing: function() {
  7142. var inter = this._intersection;
  7143. if (!inter)
  7144. return false;
  7145. var t1 = this.getTime(),
  7146. t2 = inter.getTime(),
  7147. tMin = 1e-8,
  7148. tMax = 1 - tMin,
  7149. t1Inside = t1 >= tMin && t1 <= tMax,
  7150. t2Inside = t2 >= tMin && t2 <= tMax;
  7151. if (t1Inside && t2Inside)
  7152. return !this.isTouching();
  7153. var c2 = this.getCurve(),
  7154. c1 = c2 && t1 < tMin ? c2.getPrevious() : c2,
  7155. c4 = inter.getCurve(),
  7156. c3 = c4 && t2 < tMin ? c4.getPrevious() : c4;
  7157. if (t1 > tMax)
  7158. c2 = c2.getNext();
  7159. if (t2 > tMax)
  7160. c4 = c4.getNext();
  7161. if (!c1 || !c2 || !c3 || !c4)
  7162. return false;
  7163. var offsets = [];
  7164. function addOffsets(curve, end) {
  7165. var v = curve.getValues(),
  7166. roots = Curve.classify(v).roots || Curve.getPeaks(v),
  7167. count = roots.length,
  7168. offset = Curve.getLength(v,
  7169. end && count ? roots[count - 1] : 0,
  7170. !end && count ? roots[0] : 1);
  7171. offsets.push(count ? offset : offset / 32);
  7172. }
  7173. function isInRange(angle, min, max) {
  7174. return min < max
  7175. ? angle > min && angle < max
  7176. : angle > min || angle < max;
  7177. }
  7178. if (!t1Inside) {
  7179. addOffsets(c1, true);
  7180. addOffsets(c2, false);
  7181. }
  7182. if (!t2Inside) {
  7183. addOffsets(c3, true);
  7184. addOffsets(c4, false);
  7185. }
  7186. var pt = this.getPoint(),
  7187. offset = Math.min.apply(Math, offsets),
  7188. v2 = t1Inside ? c2.getTangentAtTime(t1)
  7189. : c2.getPointAt(offset).subtract(pt),
  7190. v1 = t1Inside ? v2.negate()
  7191. : c1.getPointAt(-offset).subtract(pt),
  7192. v4 = t2Inside ? c4.getTangentAtTime(t2)
  7193. : c4.getPointAt(offset).subtract(pt),
  7194. v3 = t2Inside ? v4.negate()
  7195. : c3.getPointAt(-offset).subtract(pt),
  7196. a1 = v1.getAngle(),
  7197. a2 = v2.getAngle(),
  7198. a3 = v3.getAngle(),
  7199. a4 = v4.getAngle();
  7200. return !!(t1Inside
  7201. ? (isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4)) &&
  7202. (isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3))
  7203. : (isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2)) &&
  7204. (isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1)));
  7205. },
  7206. hasOverlap: function() {
  7207. return !!this._overlap;
  7208. }
  7209. }, Base.each(Curve._evaluateMethods, function(name) {
  7210. var get = name + 'At';
  7211. this[name] = function() {
  7212. var curve = this.getCurve(),
  7213. time = this.getTime();
  7214. return time != null && curve && curve[get](time, true);
  7215. };
  7216. }, {
  7217. preserve: true
  7218. }),
  7219. new function() {
  7220. function insert(locations, loc, merge) {
  7221. var length = locations.length,
  7222. l = 0,
  7223. r = length - 1;
  7224. function search(index, dir) {
  7225. for (var i = index + dir; i >= -1 && i <= length; i += dir) {
  7226. var loc2 = locations[((i % length) + length) % length];
  7227. if (!loc.getPoint().isClose(loc2.getPoint(),
  7228. 1e-7))
  7229. break;
  7230. if (loc.equals(loc2))
  7231. return loc2;
  7232. }
  7233. return null;
  7234. }
  7235. while (l <= r) {
  7236. var m = (l + r) >>> 1,
  7237. loc2 = locations[m],
  7238. found;
  7239. if (merge && (found = loc.equals(loc2) ? loc2
  7240. : (search(m, -1) || search(m, 1)))) {
  7241. if (loc._overlap) {
  7242. found._overlap = found._intersection._overlap = true;
  7243. }
  7244. return found;
  7245. }
  7246. var path1 = loc.getPath(),
  7247. path2 = loc2.getPath(),
  7248. diff = path1 !== path2
  7249. ? path1._id - path2._id
  7250. : (loc.getIndex() + loc.getTime())
  7251. - (loc2.getIndex() + loc2.getTime());
  7252. if (diff < 0) {
  7253. r = m - 1;
  7254. } else {
  7255. l = m + 1;
  7256. }
  7257. }
  7258. locations.splice(l, 0, loc);
  7259. return loc;
  7260. }
  7261. return { statics: {
  7262. insert: insert,
  7263. expand: function(locations) {
  7264. var expanded = locations.slice();
  7265. for (var i = locations.length - 1; i >= 0; i--) {
  7266. insert(expanded, locations[i]._intersection, false);
  7267. }
  7268. return expanded;
  7269. }
  7270. }};
  7271. });
  7272. var PathItem = Item.extend({
  7273. _class: 'PathItem',
  7274. _selectBounds: false,
  7275. _canScaleStroke: true,
  7276. beans: true,
  7277. initialize: function PathItem() {
  7278. },
  7279. statics: {
  7280. create: function(arg) {
  7281. var data,
  7282. segments,
  7283. compound;
  7284. if (Base.isPlainObject(arg)) {
  7285. segments = arg.segments;
  7286. data = arg.pathData;
  7287. } else if (Array.isArray(arg)) {
  7288. segments = arg;
  7289. } else if (typeof arg === 'string') {
  7290. data = arg;
  7291. }
  7292. if (segments) {
  7293. var first = segments[0];
  7294. compound = first && Array.isArray(first[0]);
  7295. } else if (data) {
  7296. compound = (data.match(/m/gi) || []).length > 1
  7297. || /z\s*\S+/i.test(data);
  7298. }
  7299. var ctor = compound ? CompoundPath : Path;
  7300. return new ctor(arg);
  7301. }
  7302. },
  7303. _asPathItem: function() {
  7304. return this;
  7305. },
  7306. isClockwise: function() {
  7307. return this.getArea() >= 0;
  7308. },
  7309. setClockwise: function(clockwise) {
  7310. if (this.isClockwise() != (clockwise = !!clockwise))
  7311. this.reverse();
  7312. },
  7313. setPathData: function(data) {
  7314. var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
  7315. coords,
  7316. relative = false,
  7317. previous,
  7318. control,
  7319. current = new Point(),
  7320. start = new Point();
  7321. function getCoord(index, coord) {
  7322. var val = +coords[index];
  7323. if (relative)
  7324. val += current[coord];
  7325. return val;
  7326. }
  7327. function getPoint(index) {
  7328. return new Point(
  7329. getCoord(index, 'x'),
  7330. getCoord(index + 1, 'y')
  7331. );
  7332. }
  7333. this.clear();
  7334. for (var i = 0, l = parts && parts.length; i < l; i++) {
  7335. var part = parts[i],
  7336. command = part[0],
  7337. lower = command.toLowerCase();
  7338. coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
  7339. var length = coords && coords.length;
  7340. relative = command === lower;
  7341. if (previous === 'z' && !/[mz]/.test(lower))
  7342. this.moveTo(current);
  7343. switch (lower) {
  7344. case 'm':
  7345. case 'l':
  7346. var move = lower === 'm';
  7347. for (var j = 0; j < length; j += 2) {
  7348. this[move ? 'moveTo' : 'lineTo'](current = getPoint(j));
  7349. if (move) {
  7350. start = current;
  7351. move = false;
  7352. }
  7353. }
  7354. control = current;
  7355. break;
  7356. case 'h':
  7357. case 'v':
  7358. var coord = lower === 'h' ? 'x' : 'y';
  7359. current = current.clone();
  7360. for (var j = 0; j < length; j++) {
  7361. current[coord] = getCoord(j, coord);
  7362. this.lineTo(current);
  7363. }
  7364. control = current;
  7365. break;
  7366. case 'c':
  7367. for (var j = 0; j < length; j += 6) {
  7368. this.cubicCurveTo(
  7369. getPoint(j),
  7370. control = getPoint(j + 2),
  7371. current = getPoint(j + 4));
  7372. }
  7373. break;
  7374. case 's':
  7375. for (var j = 0; j < length; j += 4) {
  7376. this.cubicCurveTo(
  7377. /[cs]/.test(previous)
  7378. ? current.multiply(2).subtract(control)
  7379. : current,
  7380. control = getPoint(j),
  7381. current = getPoint(j + 2));
  7382. previous = lower;
  7383. }
  7384. break;
  7385. case 'q':
  7386. for (var j = 0; j < length; j += 4) {
  7387. this.quadraticCurveTo(
  7388. control = getPoint(j),
  7389. current = getPoint(j + 2));
  7390. }
  7391. break;
  7392. case 't':
  7393. for (var j = 0; j < length; j += 2) {
  7394. this.quadraticCurveTo(
  7395. control = (/[qt]/.test(previous)
  7396. ? current.multiply(2).subtract(control)
  7397. : current),
  7398. current = getPoint(j));
  7399. previous = lower;
  7400. }
  7401. break;
  7402. case 'a':
  7403. for (var j = 0; j < length; j += 7) {
  7404. this.arcTo(current = getPoint(j + 5),
  7405. new Size(+coords[j], +coords[j + 1]),
  7406. +coords[j + 2], +coords[j + 4], +coords[j + 3]);
  7407. }
  7408. break;
  7409. case 'z':
  7410. this.closePath(1e-12);
  7411. current = start;
  7412. break;
  7413. }
  7414. previous = lower;
  7415. }
  7416. },
  7417. _canComposite: function() {
  7418. return !(this.hasFill() && this.hasStroke());
  7419. },
  7420. _contains: function(point) {
  7421. var winding = point.isInside(
  7422. this.getBounds({ internal: true, handle: true }))
  7423. ? this._getWinding(point)
  7424. : {};
  7425. return winding.onPath || !!(this.getFillRule() === 'evenodd'
  7426. ? winding.windingL & 1 || winding.windingR & 1
  7427. : winding.winding);
  7428. },
  7429. getIntersections: function(path, include, _matrix, _returnFirst) {
  7430. var self = this === path || !path,
  7431. matrix1 = this._matrix._orNullIfIdentity(),
  7432. matrix2 = self ? matrix1
  7433. : (_matrix || path._matrix)._orNullIfIdentity();
  7434. return self || this.getBounds(matrix1).intersects(
  7435. path.getBounds(matrix2), 1e-12)
  7436. ? Curve.getIntersections(
  7437. this.getCurves(), !self && path.getCurves(), include,
  7438. matrix1, matrix2, _returnFirst)
  7439. : [];
  7440. },
  7441. getCrossings: function(path) {
  7442. return this.getIntersections(path, function(inter) {
  7443. return inter.isCrossing();
  7444. });
  7445. },
  7446. getNearestLocation: function() {
  7447. var point = Point.read(arguments),
  7448. curves = this.getCurves(),
  7449. minDist = Infinity,
  7450. minLoc = null;
  7451. for (var i = 0, l = curves.length; i < l; i++) {
  7452. var loc = curves[i].getNearestLocation(point);
  7453. if (loc._distance < minDist) {
  7454. minDist = loc._distance;
  7455. minLoc = loc;
  7456. }
  7457. }
  7458. return minLoc;
  7459. },
  7460. getNearestPoint: function() {
  7461. var loc = this.getNearestLocation.apply(this, arguments);
  7462. return loc ? loc.getPoint() : loc;
  7463. },
  7464. interpolate: function(from, to, factor) {
  7465. var isPath = !this._children,
  7466. name = isPath ? '_segments' : '_children',
  7467. itemsFrom = from[name],
  7468. itemsTo = to[name],
  7469. items = this[name];
  7470. if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) {
  7471. throw new Error('Invalid operands in interpolate() call: ' +
  7472. from + ', ' + to);
  7473. }
  7474. var current = items.length,
  7475. length = itemsTo.length;
  7476. if (current < length) {
  7477. var ctor = isPath ? Segment : Path;
  7478. for (var i = current; i < length; i++) {
  7479. this.add(new ctor());
  7480. }
  7481. } else if (current > length) {
  7482. this[isPath ? 'removeSegments' : 'removeChildren'](length, current);
  7483. }
  7484. for (var i = 0; i < length; i++) {
  7485. items[i].interpolate(itemsFrom[i], itemsTo[i], factor);
  7486. }
  7487. if (isPath) {
  7488. this.setClosed(from._closed);
  7489. this._changed(9);
  7490. }
  7491. },
  7492. compare: function(path) {
  7493. var ok = false;
  7494. if (path) {
  7495. var paths1 = this._children || [this],
  7496. paths2 = path._children ? path._children.slice() : [path],
  7497. length1 = paths1.length,
  7498. length2 = paths2.length,
  7499. matched = [],
  7500. count = 0;
  7501. ok = true;
  7502. var boundsOverlaps = CollisionDetection.findItemBoundsCollisions(paths1, paths2, Numerical.GEOMETRIC_EPSILON);
  7503. for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) {
  7504. var path1 = paths1[i1];
  7505. ok = false;
  7506. var pathBoundsOverlaps = boundsOverlaps[i1];
  7507. if (pathBoundsOverlaps) {
  7508. for (var i2 = pathBoundsOverlaps.length - 1; i2 >= 0 && !ok; i2--) {
  7509. if (path1.compare(paths2[pathBoundsOverlaps[i2]])) {
  7510. if (!matched[pathBoundsOverlaps[i2]]) {
  7511. matched[pathBoundsOverlaps[i2]] = true;
  7512. count++;
  7513. }
  7514. ok = true;
  7515. }
  7516. }
  7517. }
  7518. }
  7519. ok = ok && count === length2;
  7520. }
  7521. return ok;
  7522. },
  7523. });
  7524. var Path = PathItem.extend({
  7525. _class: 'Path',
  7526. _serializeFields: {
  7527. segments: [],
  7528. closed: false
  7529. },
  7530. initialize: function Path(arg) {
  7531. this._closed = false;
  7532. this._segments = [];
  7533. this._version = 0;
  7534. var args = arguments,
  7535. segments = Array.isArray(arg)
  7536. ? typeof arg[0] === 'object'
  7537. ? arg
  7538. : args
  7539. : arg && (arg.size === undefined && (arg.x !== undefined
  7540. || arg.point !== undefined))
  7541. ? args
  7542. : null;
  7543. if (segments && segments.length > 0) {
  7544. this.setSegments(segments);
  7545. } else {
  7546. this._curves = undefined;
  7547. this._segmentSelection = 0;
  7548. if (!segments && typeof arg === 'string') {
  7549. this.setPathData(arg);
  7550. arg = null;
  7551. }
  7552. }
  7553. this._initialize(!segments && arg);
  7554. },
  7555. _equals: function(item) {
  7556. return this._closed === item._closed
  7557. && Base.equals(this._segments, item._segments);
  7558. },
  7559. copyContent: function(source) {
  7560. this.setSegments(source._segments);
  7561. this._closed = source._closed;
  7562. },
  7563. _changed: function _changed(flags) {
  7564. _changed.base.call(this, flags);
  7565. if (flags & 8) {
  7566. this._length = this._area = undefined;
  7567. if (flags & 32) {
  7568. this._version++;
  7569. } else if (this._curves) {
  7570. for (var i = 0, l = this._curves.length; i < l; i++)
  7571. this._curves[i]._changed();
  7572. }
  7573. } else if (flags & 64) {
  7574. this._bounds = undefined;
  7575. }
  7576. },
  7577. getStyle: function() {
  7578. var parent = this._parent;
  7579. return (parent instanceof CompoundPath ? parent : this)._style;
  7580. },
  7581. getSegments: function() {
  7582. return this._segments;
  7583. },
  7584. setSegments: function(segments) {
  7585. var fullySelected = this.isFullySelected(),
  7586. length = segments && segments.length;
  7587. this._segments.length = 0;
  7588. this._segmentSelection = 0;
  7589. this._curves = undefined;
  7590. if (length) {
  7591. var last = segments[length - 1];
  7592. if (typeof last === 'boolean') {
  7593. this.setClosed(last);
  7594. length--;
  7595. }
  7596. this._add(Segment.readList(segments, 0, {}, length));
  7597. }
  7598. if (fullySelected)
  7599. this.setFullySelected(true);
  7600. },
  7601. getFirstSegment: function() {
  7602. return this._segments[0];
  7603. },
  7604. getLastSegment: function() {
  7605. return this._segments[this._segments.length - 1];
  7606. },
  7607. getCurves: function() {
  7608. var curves = this._curves,
  7609. segments = this._segments;
  7610. if (!curves) {
  7611. var length = this._countCurves();
  7612. curves = this._curves = new Array(length);
  7613. for (var i = 0; i < length; i++)
  7614. curves[i] = new Curve(this, segments[i],
  7615. segments[i + 1] || segments[0]);
  7616. }
  7617. return curves;
  7618. },
  7619. getFirstCurve: function() {
  7620. return this.getCurves()[0];
  7621. },
  7622. getLastCurve: function() {
  7623. var curves = this.getCurves();
  7624. return curves[curves.length - 1];
  7625. },
  7626. isClosed: function() {
  7627. return this._closed;
  7628. },
  7629. setClosed: function(closed) {
  7630. if (this._closed != (closed = !!closed)) {
  7631. this._closed = closed;
  7632. if (this._curves) {
  7633. var length = this._curves.length = this._countCurves();
  7634. if (closed)
  7635. this._curves[length - 1] = new Curve(this,
  7636. this._segments[length - 1], this._segments[0]);
  7637. }
  7638. this._changed(41);
  7639. }
  7640. }
  7641. }, {
  7642. beans: true,
  7643. getPathData: function(_matrix, _precision) {
  7644. var segments = this._segments,
  7645. length = segments.length,
  7646. f = new Formatter(_precision),
  7647. coords = new Array(6),
  7648. first = true,
  7649. curX, curY,
  7650. prevX, prevY,
  7651. inX, inY,
  7652. outX, outY,
  7653. parts = [];
  7654. function addSegment(segment, skipLine) {
  7655. segment._transformCoordinates(_matrix, coords);
  7656. curX = coords[0];
  7657. curY = coords[1];
  7658. if (first) {
  7659. parts.push('M' + f.pair(curX, curY));
  7660. first = false;
  7661. } else {
  7662. inX = coords[2];
  7663. inY = coords[3];
  7664. if (inX === curX && inY === curY
  7665. && outX === prevX && outY === prevY) {
  7666. if (!skipLine) {
  7667. var dx = curX - prevX,
  7668. dy = curY - prevY;
  7669. parts.push(
  7670. dx === 0 ? 'v' + f.number(dy)
  7671. : dy === 0 ? 'h' + f.number(dx)
  7672. : 'l' + f.pair(dx, dy));
  7673. }
  7674. } else {
  7675. parts.push('c' + f.pair(outX - prevX, outY - prevY)
  7676. + ' ' + f.pair( inX - prevX, inY - prevY)
  7677. + ' ' + f.pair(curX - prevX, curY - prevY));
  7678. }
  7679. }
  7680. prevX = curX;
  7681. prevY = curY;
  7682. outX = coords[4];
  7683. outY = coords[5];
  7684. }
  7685. if (!length)
  7686. return '';
  7687. for (var i = 0; i < length; i++)
  7688. addSegment(segments[i]);
  7689. if (this._closed && length > 0) {
  7690. addSegment(segments[0], true);
  7691. parts.push('z');
  7692. }
  7693. return parts.join('');
  7694. },
  7695. isEmpty: function() {
  7696. return !this._segments.length;
  7697. },
  7698. _transformContent: function(matrix) {
  7699. var segments = this._segments,
  7700. coords = new Array(6);
  7701. for (var i = 0, l = segments.length; i < l; i++)
  7702. segments[i]._transformCoordinates(matrix, coords, true);
  7703. return true;
  7704. },
  7705. _add: function(segs, index) {
  7706. var segments = this._segments,
  7707. curves = this._curves,
  7708. amount = segs.length,
  7709. append = index == null,
  7710. index = append ? segments.length : index;
  7711. for (var i = 0; i < amount; i++) {
  7712. var segment = segs[i];
  7713. if (segment._path)
  7714. segment = segs[i] = segment.clone();
  7715. segment._path = this;
  7716. segment._index = index + i;
  7717. if (segment._selection)
  7718. this._updateSelection(segment, 0, segment._selection);
  7719. }
  7720. if (append) {
  7721. Base.push(segments, segs);
  7722. } else {
  7723. segments.splice.apply(segments, [index, 0].concat(segs));
  7724. for (var i = index + amount, l = segments.length; i < l; i++)
  7725. segments[i]._index = i;
  7726. }
  7727. if (curves) {
  7728. var total = this._countCurves(),
  7729. start = index > 0 && index + amount - 1 === total ? index - 1
  7730. : index,
  7731. insert = start,
  7732. end = Math.min(start + amount, total);
  7733. if (segs._curves) {
  7734. curves.splice.apply(curves, [start, 0].concat(segs._curves));
  7735. insert += segs._curves.length;
  7736. }
  7737. for (var i = insert; i < end; i++)
  7738. curves.splice(i, 0, new Curve(this, null, null));
  7739. this._adjustCurves(start, end);
  7740. }
  7741. this._changed(41);
  7742. return segs;
  7743. },
  7744. _adjustCurves: function(start, end) {
  7745. var segments = this._segments,
  7746. curves = this._curves,
  7747. curve;
  7748. for (var i = start; i < end; i++) {
  7749. curve = curves[i];
  7750. curve._path = this;
  7751. curve._segment1 = segments[i];
  7752. curve._segment2 = segments[i + 1] || segments[0];
  7753. curve._changed();
  7754. }
  7755. if (curve = curves[this._closed && !start ? segments.length - 1
  7756. : start - 1]) {
  7757. curve._segment2 = segments[start] || segments[0];
  7758. curve._changed();
  7759. }
  7760. if (curve = curves[end]) {
  7761. curve._segment1 = segments[end];
  7762. curve._changed();
  7763. }
  7764. },
  7765. _countCurves: function() {
  7766. var length = this._segments.length;
  7767. return !this._closed && length > 0 ? length - 1 : length;
  7768. },
  7769. add: function(segment1 ) {
  7770. var args = arguments;
  7771. return args.length > 1 && typeof segment1 !== 'number'
  7772. ? this._add(Segment.readList(args))
  7773. : this._add([ Segment.read(args) ])[0];
  7774. },
  7775. insert: function(index, segment1 ) {
  7776. var args = arguments;
  7777. return args.length > 2 && typeof segment1 !== 'number'
  7778. ? this._add(Segment.readList(args, 1), index)
  7779. : this._add([ Segment.read(args, 1) ], index)[0];
  7780. },
  7781. addSegment: function() {
  7782. return this._add([ Segment.read(arguments) ])[0];
  7783. },
  7784. insertSegment: function(index ) {
  7785. return this._add([ Segment.read(arguments, 1) ], index)[0];
  7786. },
  7787. addSegments: function(segments) {
  7788. return this._add(Segment.readList(segments));
  7789. },
  7790. insertSegments: function(index, segments) {
  7791. return this._add(Segment.readList(segments), index);
  7792. },
  7793. removeSegment: function(index) {
  7794. return this.removeSegments(index, index + 1)[0] || null;
  7795. },
  7796. removeSegments: function(start, end, _includeCurves) {
  7797. start = start || 0;
  7798. end = Base.pick(end, this._segments.length);
  7799. var segments = this._segments,
  7800. curves = this._curves,
  7801. count = segments.length,
  7802. removed = segments.splice(start, end - start),
  7803. amount = removed.length;
  7804. if (!amount)
  7805. return removed;
  7806. for (var i = 0; i < amount; i++) {
  7807. var segment = removed[i];
  7808. if (segment._selection)
  7809. this._updateSelection(segment, segment._selection, 0);
  7810. segment._index = segment._path = null;
  7811. }
  7812. for (var i = start, l = segments.length; i < l; i++)
  7813. segments[i]._index = i;
  7814. if (curves) {
  7815. var index = start > 0 && end === count + (this._closed ? 1 : 0)
  7816. ? start - 1
  7817. : start,
  7818. curves = curves.splice(index, amount);
  7819. for (var i = curves.length - 1; i >= 0; i--)
  7820. curves[i]._path = null;
  7821. if (_includeCurves)
  7822. removed._curves = curves.slice(1);
  7823. this._adjustCurves(index, index);
  7824. }
  7825. this._changed(41);
  7826. return removed;
  7827. },
  7828. clear: '#removeSegments',
  7829. hasHandles: function() {
  7830. var segments = this._segments;
  7831. for (var i = 0, l = segments.length; i < l; i++) {
  7832. if (segments[i].hasHandles())
  7833. return true;
  7834. }
  7835. return false;
  7836. },
  7837. clearHandles: function() {
  7838. var segments = this._segments;
  7839. for (var i = 0, l = segments.length; i < l; i++)
  7840. segments[i].clearHandles();
  7841. },
  7842. getLength: function() {
  7843. if (this._length == null) {
  7844. var curves = this.getCurves(),
  7845. length = 0;
  7846. for (var i = 0, l = curves.length; i < l; i++)
  7847. length += curves[i].getLength();
  7848. this._length = length;
  7849. }
  7850. return this._length;
  7851. },
  7852. getArea: function() {
  7853. var area = this._area;
  7854. if (area == null) {
  7855. var segments = this._segments,
  7856. closed = this._closed;
  7857. area = 0;
  7858. for (var i = 0, l = segments.length; i < l; i++) {
  7859. var last = i + 1 === l;
  7860. area += Curve.getArea(Curve.getValues(
  7861. segments[i], segments[last ? 0 : i + 1],
  7862. null, last && !closed));
  7863. }
  7864. this._area = area;
  7865. }
  7866. return area;
  7867. },
  7868. isFullySelected: function() {
  7869. var length = this._segments.length;
  7870. return this.isSelected() && length > 0 && this._segmentSelection
  7871. === length * 7;
  7872. },
  7873. setFullySelected: function(selected) {
  7874. if (selected)
  7875. this._selectSegments(true);
  7876. this.setSelected(selected);
  7877. },
  7878. setSelection: function setSelection(selection) {
  7879. if (!(selection & 1))
  7880. this._selectSegments(false);
  7881. setSelection.base.call(this, selection);
  7882. },
  7883. _selectSegments: function(selected) {
  7884. var segments = this._segments,
  7885. length = segments.length,
  7886. selection = selected ? 7 : 0;
  7887. this._segmentSelection = selection * length;
  7888. for (var i = 0; i < length; i++)
  7889. segments[i]._selection = selection;
  7890. },
  7891. _updateSelection: function(segment, oldSelection, newSelection) {
  7892. segment._selection = newSelection;
  7893. var selection = this._segmentSelection += newSelection - oldSelection;
  7894. if (selection > 0)
  7895. this.setSelected(true);
  7896. },
  7897. divideAt: function(location) {
  7898. var loc = this.getLocationAt(location),
  7899. curve;
  7900. return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset()))
  7901. ? curve._segment1
  7902. : null;
  7903. },
  7904. splitAt: function(location) {
  7905. var loc = this.getLocationAt(location),
  7906. index = loc && loc.index,
  7907. time = loc && loc.time,
  7908. tMin = 1e-8,
  7909. tMax = 1 - tMin;
  7910. if (time > tMax) {
  7911. index++;
  7912. time = 0;
  7913. }
  7914. var curves = this.getCurves();
  7915. if (index >= 0 && index < curves.length) {
  7916. if (time >= tMin) {
  7917. curves[index++].divideAtTime(time);
  7918. }
  7919. var segs = this.removeSegments(index, this._segments.length, true),
  7920. path;
  7921. if (this._closed) {
  7922. this.setClosed(false);
  7923. path = this;
  7924. } else {
  7925. path = new Path(Item.NO_INSERT);
  7926. path.insertAbove(this);
  7927. path.copyAttributes(this);
  7928. }
  7929. path._add(segs, 0);
  7930. this.addSegment(segs[0]);
  7931. return path;
  7932. }
  7933. return null;
  7934. },
  7935. split: function(index, time) {
  7936. var curve,
  7937. location = time === undefined ? index
  7938. : (curve = this.getCurves()[index])
  7939. && curve.getLocationAtTime(time);
  7940. return location != null ? this.splitAt(location) : null;
  7941. },
  7942. join: function(path, tolerance) {
  7943. var epsilon = tolerance || 0;
  7944. if (path && path !== this) {
  7945. var segments = path._segments,
  7946. last1 = this.getLastSegment(),
  7947. last2 = path.getLastSegment();
  7948. if (!last2)
  7949. return this;
  7950. if (last1 && last1._point.isClose(last2._point, epsilon))
  7951. path.reverse();
  7952. var first2 = path.getFirstSegment();
  7953. if (last1 && last1._point.isClose(first2._point, epsilon)) {
  7954. last1.setHandleOut(first2._handleOut);
  7955. this._add(segments.slice(1));
  7956. } else {
  7957. var first1 = this.getFirstSegment();
  7958. if (first1 && first1._point.isClose(first2._point, epsilon))
  7959. path.reverse();
  7960. last2 = path.getLastSegment();
  7961. if (first1 && first1._point.isClose(last2._point, epsilon)) {
  7962. first1.setHandleIn(last2._handleIn);
  7963. this._add(segments.slice(0, segments.length - 1), 0);
  7964. } else {
  7965. this._add(segments.slice());
  7966. }
  7967. }
  7968. if (path._closed)
  7969. this._add([segments[0]]);
  7970. path.remove();
  7971. }
  7972. var first = this.getFirstSegment(),
  7973. last = this.getLastSegment();
  7974. if (first !== last && first._point.isClose(last._point, epsilon)) {
  7975. first.setHandleIn(last._handleIn);
  7976. last.remove();
  7977. this.setClosed(true);
  7978. }
  7979. return this;
  7980. },
  7981. reduce: function(options) {
  7982. var curves = this.getCurves(),
  7983. simplify = options && options.simplify,
  7984. tolerance = simplify ? 1e-7 : 0;
  7985. for (var i = curves.length - 1; i >= 0; i--) {
  7986. var curve = curves[i];
  7987. if (!curve.hasHandles() && (!curve.hasLength(tolerance)
  7988. || simplify && curve.isCollinear(curve.getNext())))
  7989. curve.remove();
  7990. }
  7991. return this;
  7992. },
  7993. reverse: function() {
  7994. this._segments.reverse();
  7995. for (var i = 0, l = this._segments.length; i < l; i++) {
  7996. var segment = this._segments[i];
  7997. var handleIn = segment._handleIn;
  7998. segment._handleIn = segment._handleOut;
  7999. segment._handleOut = handleIn;
  8000. segment._index = i;
  8001. }
  8002. this._curves = null;
  8003. this._changed(9);
  8004. },
  8005. flatten: function(flatness) {
  8006. var flattener = new PathFlattener(this, flatness || 0.25, 256, true),
  8007. parts = flattener.parts,
  8008. length = parts.length,
  8009. segments = [];
  8010. for (var i = 0; i < length; i++) {
  8011. segments.push(new Segment(parts[i].curve.slice(0, 2)));
  8012. }
  8013. if (!this._closed && length > 0) {
  8014. segments.push(new Segment(parts[length - 1].curve.slice(6)));
  8015. }
  8016. this.setSegments(segments);
  8017. },
  8018. simplify: function(tolerance) {
  8019. var segments = new PathFitter(this).fit(tolerance || 2.5);
  8020. if (segments)
  8021. this.setSegments(segments);
  8022. return !!segments;
  8023. },
  8024. smooth: function(options) {
  8025. var that = this,
  8026. opts = options || {},
  8027. type = opts.type || 'asymmetric',
  8028. segments = this._segments,
  8029. length = segments.length,
  8030. closed = this._closed;
  8031. function getIndex(value, _default) {
  8032. var index = value && value.index;
  8033. if (index != null) {
  8034. var path = value.path;
  8035. if (path && path !== that)
  8036. throw new Error(value._class + ' ' + index + ' of ' + path
  8037. + ' is not part of ' + that);
  8038. if (_default && value instanceof Curve)
  8039. index++;
  8040. } else {
  8041. index = typeof value === 'number' ? value : _default;
  8042. }
  8043. return Math.min(index < 0 && closed
  8044. ? index % length
  8045. : index < 0 ? index + length : index, length - 1);
  8046. }
  8047. var loop = closed && opts.from === undefined && opts.to === undefined,
  8048. from = getIndex(opts.from, 0),
  8049. to = getIndex(opts.to, length - 1);
  8050. if (from > to) {
  8051. if (closed) {
  8052. from -= length;
  8053. } else {
  8054. var tmp = from;
  8055. from = to;
  8056. to = tmp;
  8057. }
  8058. }
  8059. if (/^(?:asymmetric|continuous)$/.test(type)) {
  8060. var asymmetric = type === 'asymmetric',
  8061. min = Math.min,
  8062. amount = to - from + 1,
  8063. n = amount - 1,
  8064. padding = loop ? min(amount, 4) : 1,
  8065. paddingLeft = padding,
  8066. paddingRight = padding,
  8067. knots = [];
  8068. if (!closed) {
  8069. paddingLeft = min(1, from);
  8070. paddingRight = min(1, length - to - 1);
  8071. }
  8072. n += paddingLeft + paddingRight;
  8073. if (n <= 1)
  8074. return;
  8075. for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) {
  8076. knots[i] = segments[(j < 0 ? j + length : j) % length]._point;
  8077. }
  8078. var x = knots[0]._x + 2 * knots[1]._x,
  8079. y = knots[0]._y + 2 * knots[1]._y,
  8080. f = 2,
  8081. n_1 = n - 1,
  8082. rx = [x],
  8083. ry = [y],
  8084. rf = [f],
  8085. px = [],
  8086. py = [];
  8087. for (var i = 1; i < n; i++) {
  8088. var internal = i < n_1,
  8089. a = internal ? 1 : asymmetric ? 1 : 2,
  8090. b = internal ? 4 : asymmetric ? 2 : 7,
  8091. u = internal ? 4 : asymmetric ? 3 : 8,
  8092. v = internal ? 2 : asymmetric ? 0 : 1,
  8093. m = a / f;
  8094. f = rf[i] = b - m;
  8095. x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x;
  8096. y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y;
  8097. }
  8098. px[n_1] = rx[n_1] / rf[n_1];
  8099. py[n_1] = ry[n_1] / rf[n_1];
  8100. for (var i = n - 2; i >= 0; i--) {
  8101. px[i] = (rx[i] - px[i + 1]) / rf[i];
  8102. py[i] = (ry[i] - py[i + 1]) / rf[i];
  8103. }
  8104. px[n] = (3 * knots[n]._x - px[n_1]) / 2;
  8105. py[n] = (3 * knots[n]._y - py[n_1]) / 2;
  8106. for (var i = paddingLeft, max = n - paddingRight, j = from;
  8107. i <= max; i++, j++) {
  8108. var segment = segments[j < 0 ? j + length : j],
  8109. pt = segment._point,
  8110. hx = px[i] - pt._x,
  8111. hy = py[i] - pt._y;
  8112. if (loop || i < max)
  8113. segment.setHandleOut(hx, hy);
  8114. if (loop || i > paddingLeft)
  8115. segment.setHandleIn(-hx, -hy);
  8116. }
  8117. } else {
  8118. for (var i = from; i <= to; i++) {
  8119. segments[i < 0 ? i + length : i].smooth(opts,
  8120. !loop && i === from, !loop && i === to);
  8121. }
  8122. }
  8123. },
  8124. toShape: function(insert) {
  8125. if (!this._closed)
  8126. return null;
  8127. var segments = this._segments,
  8128. type,
  8129. size,
  8130. radius,
  8131. topCenter;
  8132. function isCollinear(i, j) {
  8133. var seg1 = segments[i],
  8134. seg2 = seg1.getNext(),
  8135. seg3 = segments[j],
  8136. seg4 = seg3.getNext();
  8137. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  8138. && seg3._handleOut.isZero() && seg4._handleIn.isZero()
  8139. && seg2._point.subtract(seg1._point).isCollinear(
  8140. seg4._point.subtract(seg3._point));
  8141. }
  8142. function isOrthogonal(i) {
  8143. var seg2 = segments[i],
  8144. seg1 = seg2.getPrevious(),
  8145. seg3 = seg2.getNext();
  8146. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  8147. && seg2._handleOut.isZero() && seg3._handleIn.isZero()
  8148. && seg2._point.subtract(seg1._point).isOrthogonal(
  8149. seg3._point.subtract(seg2._point));
  8150. }
  8151. function isArc(i) {
  8152. var seg1 = segments[i],
  8153. seg2 = seg1.getNext(),
  8154. handle1 = seg1._handleOut,
  8155. handle2 = seg2._handleIn,
  8156. kappa = 0.5522847498307936;
  8157. if (handle1.isOrthogonal(handle2)) {
  8158. var pt1 = seg1._point,
  8159. pt2 = seg2._point,
  8160. corner = new Line(pt1, handle1, true).intersect(
  8161. new Line(pt2, handle2, true), true);
  8162. return corner && Numerical.isZero(handle1.getLength() /
  8163. corner.subtract(pt1).getLength() - kappa)
  8164. && Numerical.isZero(handle2.getLength() /
  8165. corner.subtract(pt2).getLength() - kappa);
  8166. }
  8167. return false;
  8168. }
  8169. function getDistance(i, j) {
  8170. return segments[i]._point.getDistance(segments[j]._point);
  8171. }
  8172. if (!this.hasHandles() && segments.length === 4
  8173. && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) {
  8174. type = Shape.Rectangle;
  8175. size = new Size(getDistance(0, 3), getDistance(0, 1));
  8176. topCenter = segments[1]._point.add(segments[2]._point).divide(2);
  8177. } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
  8178. && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) {
  8179. type = Shape.Rectangle;
  8180. size = new Size(getDistance(1, 6), getDistance(0, 3));
  8181. radius = size.subtract(new Size(getDistance(0, 7),
  8182. getDistance(1, 2))).divide(2);
  8183. topCenter = segments[3]._point.add(segments[4]._point).divide(2);
  8184. } else if (segments.length === 4
  8185. && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
  8186. if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
  8187. type = Shape.Circle;
  8188. radius = getDistance(0, 2) / 2;
  8189. } else {
  8190. type = Shape.Ellipse;
  8191. radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
  8192. }
  8193. topCenter = segments[1]._point;
  8194. }
  8195. if (type) {
  8196. var center = this.getPosition(true),
  8197. shape = new type({
  8198. center: center,
  8199. size: size,
  8200. radius: radius,
  8201. insert: false
  8202. });
  8203. shape.copyAttributes(this, true);
  8204. shape._matrix.prepend(this._matrix);
  8205. shape.rotate(topCenter.subtract(center).getAngle() + 90);
  8206. if (insert === undefined || insert)
  8207. shape.insertAbove(this);
  8208. return shape;
  8209. }
  8210. return null;
  8211. },
  8212. toPath: '#clone',
  8213. compare: function compare(path) {
  8214. if (!path || path instanceof CompoundPath)
  8215. return compare.base.call(this, path);
  8216. var curves1 = this.getCurves(),
  8217. curves2 = path.getCurves(),
  8218. length1 = curves1.length,
  8219. length2 = curves2.length;
  8220. if (!length1 || !length2) {
  8221. return length1 == length2;
  8222. }
  8223. var v1 = curves1[0].getValues(),
  8224. values2 = [],
  8225. pos1 = 0, pos2,
  8226. end1 = 0, end2;
  8227. for (var i = 0; i < length2; i++) {
  8228. var v2 = curves2[i].getValues();
  8229. values2.push(v2);
  8230. var overlaps = Curve.getOverlaps(v1, v2);
  8231. if (overlaps) {
  8232. pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i;
  8233. end2 = overlaps[0][1];
  8234. break;
  8235. }
  8236. }
  8237. var abs = Math.abs,
  8238. epsilon = 1e-8,
  8239. v2 = values2[pos2],
  8240. start2;
  8241. while (v1 && v2) {
  8242. var overlaps = Curve.getOverlaps(v1, v2);
  8243. if (overlaps) {
  8244. var t1 = overlaps[0][0];
  8245. if (abs(t1 - end1) < epsilon) {
  8246. end1 = overlaps[1][0];
  8247. if (end1 === 1) {
  8248. v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null;
  8249. end1 = 0;
  8250. }
  8251. var t2 = overlaps[0][1];
  8252. if (abs(t2 - end2) < epsilon) {
  8253. if (!start2)
  8254. start2 = [pos2, t2];
  8255. end2 = overlaps[1][1];
  8256. if (end2 === 1) {
  8257. if (++pos2 >= length2)
  8258. pos2 = 0;
  8259. v2 = values2[pos2] || curves2[pos2].getValues();
  8260. end2 = 0;
  8261. }
  8262. if (!v1) {
  8263. return start2[0] === pos2 && start2[1] === end2;
  8264. }
  8265. continue;
  8266. }
  8267. }
  8268. }
  8269. break;
  8270. }
  8271. return false;
  8272. },
  8273. _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) {
  8274. var that = this,
  8275. style = this.getStyle(),
  8276. segments = this._segments,
  8277. numSegments = segments.length,
  8278. closed = this._closed,
  8279. tolerancePadding = options._tolerancePadding,
  8280. strokePadding = tolerancePadding,
  8281. join, cap, miterLimit,
  8282. area, loc, res,
  8283. hitStroke = options.stroke && style.hasStroke(),
  8284. hitFill = options.fill && style.hasFill(),
  8285. hitCurves = options.curves,
  8286. strokeRadius = hitStroke
  8287. ? style.getStrokeWidth() / 2
  8288. : hitFill && options.tolerance > 0 || hitCurves
  8289. ? 0 : null;
  8290. if (strokeRadius !== null) {
  8291. if (strokeRadius > 0) {
  8292. join = style.getStrokeJoin();
  8293. cap = style.getStrokeCap();
  8294. miterLimit = style.getMiterLimit();
  8295. strokePadding = strokePadding.add(
  8296. Path._getStrokePadding(strokeRadius, strokeMatrix));
  8297. } else {
  8298. join = cap = 'round';
  8299. }
  8300. }
  8301. function isCloseEnough(pt, padding) {
  8302. return point.subtract(pt).divide(padding).length <= 1;
  8303. }
  8304. function checkSegmentPoint(seg, pt, name) {
  8305. if (!options.selected || pt.isSelected()) {
  8306. var anchor = seg._point;
  8307. if (pt !== anchor)
  8308. pt = pt.add(anchor);
  8309. if (isCloseEnough(pt, strokePadding)) {
  8310. return new HitResult(name, that, {
  8311. segment: seg,
  8312. point: pt
  8313. });
  8314. }
  8315. }
  8316. }
  8317. function checkSegmentPoints(seg, ends) {
  8318. return (ends || options.segments)
  8319. && checkSegmentPoint(seg, seg._point, 'segment')
  8320. || (!ends && options.handles) && (
  8321. checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||
  8322. checkSegmentPoint(seg, seg._handleOut, 'handle-out'));
  8323. }
  8324. function addToArea(point) {
  8325. area.add(point);
  8326. }
  8327. function checkSegmentStroke(segment) {
  8328. var isJoin = closed || segment._index > 0
  8329. && segment._index < numSegments - 1;
  8330. if ((isJoin ? join : cap) === 'round') {
  8331. return isCloseEnough(segment._point, strokePadding);
  8332. } else {
  8333. area = new Path({ internal: true, closed: true });
  8334. if (isJoin) {
  8335. if (!segment.isSmooth()) {
  8336. Path._addBevelJoin(segment, join, strokeRadius,
  8337. miterLimit, null, strokeMatrix, addToArea, true);
  8338. }
  8339. } else if (cap === 'square') {
  8340. Path._addSquareCap(segment, cap, strokeRadius, null,
  8341. strokeMatrix, addToArea, true);
  8342. }
  8343. if (!area.isEmpty()) {
  8344. var loc;
  8345. return area.contains(point)
  8346. || (loc = area.getNearestLocation(point))
  8347. && isCloseEnough(loc.getPoint(), tolerancePadding);
  8348. }
  8349. }
  8350. }
  8351. if (options.ends && !options.segments && !closed) {
  8352. if (res = checkSegmentPoints(segments[0], true)
  8353. || checkSegmentPoints(segments[numSegments - 1], true))
  8354. return res;
  8355. } else if (options.segments || options.handles) {
  8356. for (var i = 0; i < numSegments; i++)
  8357. if (res = checkSegmentPoints(segments[i]))
  8358. return res;
  8359. }
  8360. if (strokeRadius !== null) {
  8361. loc = this.getNearestLocation(point);
  8362. if (loc) {
  8363. var time = loc.getTime();
  8364. if (time === 0 || time === 1 && numSegments > 1) {
  8365. if (!checkSegmentStroke(loc.getSegment()))
  8366. loc = null;
  8367. } else if (!isCloseEnough(loc.getPoint(), strokePadding)) {
  8368. loc = null;
  8369. }
  8370. }
  8371. if (!loc && join === 'miter' && numSegments > 1) {
  8372. for (var i = 0; i < numSegments; i++) {
  8373. var segment = segments[i];
  8374. if (point.getDistance(segment._point)
  8375. <= miterLimit * strokeRadius
  8376. && checkSegmentStroke(segment)) {
  8377. loc = segment.getLocation();
  8378. break;
  8379. }
  8380. }
  8381. }
  8382. }
  8383. return !loc && hitFill && this._contains(point)
  8384. || loc && !hitStroke && !hitCurves
  8385. ? new HitResult('fill', this)
  8386. : loc
  8387. ? new HitResult(hitStroke ? 'stroke' : 'curve', this, {
  8388. location: loc,
  8389. point: loc.getPoint()
  8390. })
  8391. : null;
  8392. }
  8393. }, Base.each(Curve._evaluateMethods,
  8394. function(name) {
  8395. this[name + 'At'] = function(offset) {
  8396. var loc = this.getLocationAt(offset);
  8397. return loc && loc[name]();
  8398. };
  8399. },
  8400. {
  8401. beans: false,
  8402. getLocationOf: function() {
  8403. var point = Point.read(arguments),
  8404. curves = this.getCurves();
  8405. for (var i = 0, l = curves.length; i < l; i++) {
  8406. var loc = curves[i].getLocationOf(point);
  8407. if (loc)
  8408. return loc;
  8409. }
  8410. return null;
  8411. },
  8412. getOffsetOf: function() {
  8413. var loc = this.getLocationOf.apply(this, arguments);
  8414. return loc ? loc.getOffset() : null;
  8415. },
  8416. getLocationAt: function(offset) {
  8417. if (typeof offset === 'number') {
  8418. var curves = this.getCurves(),
  8419. length = 0;
  8420. for (var i = 0, l = curves.length; i < l; i++) {
  8421. var start = length,
  8422. curve = curves[i];
  8423. length += curve.getLength();
  8424. if (length > offset) {
  8425. return curve.getLocationAt(offset - start);
  8426. }
  8427. }
  8428. if (curves.length > 0 && offset <= this.getLength()) {
  8429. return new CurveLocation(curves[curves.length - 1], 1);
  8430. }
  8431. } else if (offset && offset.getPath && offset.getPath() === this) {
  8432. return offset;
  8433. }
  8434. return null;
  8435. },
  8436. getOffsetsWithTangent: function() {
  8437. var tangent = Point.read(arguments);
  8438. if (tangent.isZero()) {
  8439. return [];
  8440. }
  8441. var offsets = [];
  8442. var curveStart = 0;
  8443. var curves = this.getCurves();
  8444. for (var i = 0, l = curves.length; i < l; i++) {
  8445. var curve = curves[i];
  8446. var curveTimes = curve.getTimesWithTangent(tangent);
  8447. for (var j = 0, m = curveTimes.length; j < m; j++) {
  8448. var offset = curveStart + curve.getOffsetAtTime(curveTimes[j]);
  8449. if (offsets.indexOf(offset) < 0) {
  8450. offsets.push(offset);
  8451. }
  8452. }
  8453. curveStart += curve.length;
  8454. }
  8455. return offsets;
  8456. }
  8457. }),
  8458. new function() {
  8459. function drawHandles(ctx, segments, matrix, size) {
  8460. if (size <= 0) return;
  8461. var half = size / 2,
  8462. miniSize = size - 2,
  8463. miniHalf = half - 1,
  8464. coords = new Array(6),
  8465. pX, pY;
  8466. function drawHandle(index) {
  8467. var hX = coords[index],
  8468. hY = coords[index + 1];
  8469. if (pX != hX || pY != hY) {
  8470. ctx.beginPath();
  8471. ctx.moveTo(pX, pY);
  8472. ctx.lineTo(hX, hY);
  8473. ctx.stroke();
  8474. ctx.beginPath();
  8475. ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
  8476. ctx.fill();
  8477. }
  8478. }
  8479. for (var i = 0, l = segments.length; i < l; i++) {
  8480. var segment = segments[i],
  8481. selection = segment._selection;
  8482. segment._transformCoordinates(matrix, coords);
  8483. pX = coords[0];
  8484. pY = coords[1];
  8485. if (selection & 2)
  8486. drawHandle(2);
  8487. if (selection & 4)
  8488. drawHandle(4);
  8489. ctx.fillRect(pX - half, pY - half, size, size);
  8490. if (miniSize > 0 && !(selection & 1)) {
  8491. var fillStyle = ctx.fillStyle;
  8492. ctx.fillStyle = '#ffffff';
  8493. ctx.fillRect(pX - miniHalf, pY - miniHalf, miniSize, miniSize);
  8494. ctx.fillStyle = fillStyle;
  8495. }
  8496. }
  8497. }
  8498. function drawSegments(ctx, path, matrix) {
  8499. var segments = path._segments,
  8500. length = segments.length,
  8501. coords = new Array(6),
  8502. first = true,
  8503. curX, curY,
  8504. prevX, prevY,
  8505. inX, inY,
  8506. outX, outY;
  8507. function drawSegment(segment) {
  8508. if (matrix) {
  8509. segment._transformCoordinates(matrix, coords);
  8510. curX = coords[0];
  8511. curY = coords[1];
  8512. } else {
  8513. var point = segment._point;
  8514. curX = point._x;
  8515. curY = point._y;
  8516. }
  8517. if (first) {
  8518. ctx.moveTo(curX, curY);
  8519. first = false;
  8520. } else {
  8521. if (matrix) {
  8522. inX = coords[2];
  8523. inY = coords[3];
  8524. } else {
  8525. var handle = segment._handleIn;
  8526. inX = curX + handle._x;
  8527. inY = curY + handle._y;
  8528. }
  8529. if (inX === curX && inY === curY
  8530. && outX === prevX && outY === prevY) {
  8531. ctx.lineTo(curX, curY);
  8532. } else {
  8533. ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
  8534. }
  8535. }
  8536. prevX = curX;
  8537. prevY = curY;
  8538. if (matrix) {
  8539. outX = coords[4];
  8540. outY = coords[5];
  8541. } else {
  8542. var handle = segment._handleOut;
  8543. outX = prevX + handle._x;
  8544. outY = prevY + handle._y;
  8545. }
  8546. }
  8547. for (var i = 0; i < length; i++)
  8548. drawSegment(segments[i]);
  8549. if (path._closed && length > 0)
  8550. drawSegment(segments[0]);
  8551. }
  8552. return {
  8553. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8554. var dontStart = param.dontStart,
  8555. dontPaint = param.dontFinish || param.clip,
  8556. style = this.getStyle(),
  8557. hasFill = style.hasFill(),
  8558. hasStroke = style.hasStroke(),
  8559. dashArray = style.getDashArray(),
  8560. dashLength = !paper.support.nativeDash && hasStroke
  8561. && dashArray && dashArray.length;
  8562. if (!dontStart)
  8563. ctx.beginPath();
  8564. if (hasFill || hasStroke && !dashLength || dontPaint) {
  8565. drawSegments(ctx, this, strokeMatrix);
  8566. if (this._closed)
  8567. ctx.closePath();
  8568. }
  8569. function getOffset(i) {
  8570. return dashArray[((i % dashLength) + dashLength) % dashLength];
  8571. }
  8572. if (!dontPaint && (hasFill || hasStroke)) {
  8573. this._setStyles(ctx, param, viewMatrix);
  8574. if (hasFill) {
  8575. ctx.fill(style.getFillRule());
  8576. ctx.shadowColor = 'rgba(0,0,0,0)';
  8577. }
  8578. if (hasStroke) {
  8579. if (dashLength) {
  8580. if (!dontStart)
  8581. ctx.beginPath();
  8582. var flattener = new PathFlattener(this, 0.25, 32, false,
  8583. strokeMatrix),
  8584. length = flattener.length,
  8585. from = -style.getDashOffset(), to,
  8586. i = 0;
  8587. while (from > 0) {
  8588. from -= getOffset(i--) + getOffset(i--);
  8589. }
  8590. while (from < length) {
  8591. to = from + getOffset(i++);
  8592. if (from > 0 || to > 0)
  8593. flattener.drawPart(ctx,
  8594. Math.max(from, 0), Math.max(to, 0));
  8595. from = to + getOffset(i++);
  8596. }
  8597. }
  8598. ctx.stroke();
  8599. }
  8600. }
  8601. },
  8602. _drawSelected: function(ctx, matrix) {
  8603. ctx.beginPath();
  8604. drawSegments(ctx, this, matrix);
  8605. ctx.stroke();
  8606. drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);
  8607. }
  8608. };
  8609. },
  8610. new function() {
  8611. function getCurrentSegment(that) {
  8612. var segments = that._segments;
  8613. if (!segments.length)
  8614. throw new Error('Use a moveTo() command first');
  8615. return segments[segments.length - 1];
  8616. }
  8617. return {
  8618. moveTo: function() {
  8619. var segments = this._segments;
  8620. if (segments.length === 1)
  8621. this.removeSegment(0);
  8622. if (!segments.length)
  8623. this._add([ new Segment(Point.read(arguments)) ]);
  8624. },
  8625. moveBy: function() {
  8626. throw new Error('moveBy() is unsupported on Path items.');
  8627. },
  8628. lineTo: function() {
  8629. this._add([ new Segment(Point.read(arguments)) ]);
  8630. },
  8631. cubicCurveTo: function() {
  8632. var args = arguments,
  8633. handle1 = Point.read(args),
  8634. handle2 = Point.read(args),
  8635. to = Point.read(args),
  8636. current = getCurrentSegment(this);
  8637. current.setHandleOut(handle1.subtract(current._point));
  8638. this._add([ new Segment(to, handle2.subtract(to)) ]);
  8639. },
  8640. quadraticCurveTo: function() {
  8641. var args = arguments,
  8642. handle = Point.read(args),
  8643. to = Point.read(args),
  8644. current = getCurrentSegment(this)._point;
  8645. this.cubicCurveTo(
  8646. handle.add(current.subtract(handle).multiply(1 / 3)),
  8647. handle.add(to.subtract(handle).multiply(1 / 3)),
  8648. to
  8649. );
  8650. },
  8651. curveTo: function() {
  8652. var args = arguments,
  8653. through = Point.read(args),
  8654. to = Point.read(args),
  8655. t = Base.pick(Base.read(args), 0.5),
  8656. t1 = 1 - t,
  8657. current = getCurrentSegment(this)._point,
  8658. handle = through.subtract(current.multiply(t1 * t1))
  8659. .subtract(to.multiply(t * t)).divide(2 * t * t1);
  8660. if (handle.isNaN())
  8661. throw new Error(
  8662. 'Cannot put a curve through points with parameter = ' + t);
  8663. this.quadraticCurveTo(handle, to);
  8664. },
  8665. arcTo: function() {
  8666. var args = arguments,
  8667. abs = Math.abs,
  8668. sqrt = Math.sqrt,
  8669. current = getCurrentSegment(this),
  8670. from = current._point,
  8671. to = Point.read(args),
  8672. through,
  8673. peek = Base.peek(args),
  8674. clockwise = Base.pick(peek, true),
  8675. center, extent, vector, matrix;
  8676. if (typeof clockwise === 'boolean') {
  8677. var middle = from.add(to).divide(2),
  8678. through = middle.add(middle.subtract(from).rotate(
  8679. clockwise ? -90 : 90));
  8680. } else if (Base.remain(args) <= 2) {
  8681. through = to;
  8682. to = Point.read(args);
  8683. } else if (!from.equals(to)) {
  8684. var radius = Size.read(args),
  8685. isZero = Numerical.isZero;
  8686. if (isZero(radius.width) || isZero(radius.height))
  8687. return this.lineTo(to);
  8688. var rotation = Base.read(args),
  8689. clockwise = !!Base.read(args),
  8690. large = !!Base.read(args),
  8691. middle = from.add(to).divide(2),
  8692. pt = from.subtract(middle).rotate(-rotation),
  8693. x = pt.x,
  8694. y = pt.y,
  8695. rx = abs(radius.width),
  8696. ry = abs(radius.height),
  8697. rxSq = rx * rx,
  8698. rySq = ry * ry,
  8699. xSq = x * x,
  8700. ySq = y * y;
  8701. var factor = sqrt(xSq / rxSq + ySq / rySq);
  8702. if (factor > 1) {
  8703. rx *= factor;
  8704. ry *= factor;
  8705. rxSq = rx * rx;
  8706. rySq = ry * ry;
  8707. }
  8708. factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /
  8709. (rxSq * ySq + rySq * xSq);
  8710. if (abs(factor) < 1e-12)
  8711. factor = 0;
  8712. if (factor < 0)
  8713. throw new Error(
  8714. 'Cannot create an arc with the given arguments');
  8715. center = new Point(rx * y / ry, -ry * x / rx)
  8716. .multiply((large === clockwise ? -1 : 1) * sqrt(factor))
  8717. .rotate(rotation).add(middle);
  8718. matrix = new Matrix().translate(center).rotate(rotation)
  8719. .scale(rx, ry);
  8720. vector = matrix._inverseTransform(from);
  8721. extent = vector.getDirectedAngle(matrix._inverseTransform(to));
  8722. if (!clockwise && extent > 0)
  8723. extent -= 360;
  8724. else if (clockwise && extent < 0)
  8725. extent += 360;
  8726. }
  8727. if (through) {
  8728. var l1 = new Line(from.add(through).divide(2),
  8729. through.subtract(from).rotate(90), true),
  8730. l2 = new Line(through.add(to).divide(2),
  8731. to.subtract(through).rotate(90), true),
  8732. line = new Line(from, to),
  8733. throughSide = line.getSide(through);
  8734. center = l1.intersect(l2, true);
  8735. if (!center) {
  8736. if (!throughSide)
  8737. return this.lineTo(to);
  8738. throw new Error(
  8739. 'Cannot create an arc with the given arguments');
  8740. }
  8741. vector = from.subtract(center);
  8742. extent = vector.getDirectedAngle(to.subtract(center));
  8743. var centerSide = line.getSide(center, true);
  8744. if (centerSide === 0) {
  8745. extent = throughSide * abs(extent);
  8746. } else if (throughSide === centerSide) {
  8747. extent += extent < 0 ? 360 : -360;
  8748. }
  8749. }
  8750. if (extent) {
  8751. var epsilon = 1e-7,
  8752. ext = abs(extent),
  8753. count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90),
  8754. inc = extent / count,
  8755. half = inc * Math.PI / 360,
  8756. z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
  8757. segments = [];
  8758. for (var i = 0; i <= count; i++) {
  8759. var pt = to,
  8760. out = null;
  8761. if (i < count) {
  8762. out = vector.rotate(90).multiply(z);
  8763. if (matrix) {
  8764. pt = matrix._transformPoint(vector);
  8765. out = matrix._transformPoint(vector.add(out))
  8766. .subtract(pt);
  8767. } else {
  8768. pt = center.add(vector);
  8769. }
  8770. }
  8771. if (!i) {
  8772. current.setHandleOut(out);
  8773. } else {
  8774. var _in = vector.rotate(-90).multiply(z);
  8775. if (matrix) {
  8776. _in = matrix._transformPoint(vector.add(_in))
  8777. .subtract(pt);
  8778. }
  8779. segments.push(new Segment(pt, _in, out));
  8780. }
  8781. vector = vector.rotate(inc);
  8782. }
  8783. this._add(segments);
  8784. }
  8785. },
  8786. lineBy: function() {
  8787. var to = Point.read(arguments),
  8788. current = getCurrentSegment(this)._point;
  8789. this.lineTo(current.add(to));
  8790. },
  8791. curveBy: function() {
  8792. var args = arguments,
  8793. through = Point.read(args),
  8794. to = Point.read(args),
  8795. parameter = Base.read(args),
  8796. current = getCurrentSegment(this)._point;
  8797. this.curveTo(current.add(through), current.add(to), parameter);
  8798. },
  8799. cubicCurveBy: function() {
  8800. var args = arguments,
  8801. handle1 = Point.read(args),
  8802. handle2 = Point.read(args),
  8803. to = Point.read(args),
  8804. current = getCurrentSegment(this)._point;
  8805. this.cubicCurveTo(current.add(handle1), current.add(handle2),
  8806. current.add(to));
  8807. },
  8808. quadraticCurveBy: function() {
  8809. var args = arguments,
  8810. handle = Point.read(args),
  8811. to = Point.read(args),
  8812. current = getCurrentSegment(this)._point;
  8813. this.quadraticCurveTo(current.add(handle), current.add(to));
  8814. },
  8815. arcBy: function() {
  8816. var args = arguments,
  8817. current = getCurrentSegment(this)._point,
  8818. point = current.add(Point.read(args)),
  8819. clockwise = Base.pick(Base.peek(args), true);
  8820. if (typeof clockwise === 'boolean') {
  8821. this.arcTo(point, clockwise);
  8822. } else {
  8823. this.arcTo(point, current.add(Point.read(args)));
  8824. }
  8825. },
  8826. closePath: function(tolerance) {
  8827. this.setClosed(true);
  8828. this.join(this, tolerance);
  8829. }
  8830. };
  8831. }, {
  8832. _getBounds: function(matrix, options) {
  8833. var method = options.handle
  8834. ? 'getHandleBounds'
  8835. : options.stroke
  8836. ? 'getStrokeBounds'
  8837. : 'getBounds';
  8838. return Path[method](this._segments, this._closed, this, matrix, options);
  8839. },
  8840. statics: {
  8841. getBounds: function(segments, closed, path, matrix, options, strokePadding) {
  8842. var first = segments[0];
  8843. if (!first)
  8844. return new Rectangle();
  8845. var coords = new Array(6),
  8846. prevCoords = first._transformCoordinates(matrix, new Array(6)),
  8847. min = prevCoords.slice(0, 2),
  8848. max = min.slice(),
  8849. roots = new Array(2);
  8850. function processSegment(segment) {
  8851. segment._transformCoordinates(matrix, coords);
  8852. for (var i = 0; i < 2; i++) {
  8853. Curve._addBounds(
  8854. prevCoords[i],
  8855. prevCoords[i + 4],
  8856. coords[i + 2],
  8857. coords[i],
  8858. i, strokePadding ? strokePadding[i] : 0, min, max, roots);
  8859. }
  8860. var tmp = prevCoords;
  8861. prevCoords = coords;
  8862. coords = tmp;
  8863. }
  8864. for (var i = 1, l = segments.length; i < l; i++)
  8865. processSegment(segments[i]);
  8866. if (closed)
  8867. processSegment(first);
  8868. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  8869. },
  8870. getStrokeBounds: function(segments, closed, path, matrix, options) {
  8871. var style = path.getStyle(),
  8872. stroke = style.hasStroke(),
  8873. strokeWidth = style.getStrokeWidth(),
  8874. strokeMatrix = stroke && path._getStrokeMatrix(matrix, options),
  8875. strokePadding = stroke && Path._getStrokePadding(strokeWidth,
  8876. strokeMatrix),
  8877. bounds = Path.getBounds(segments, closed, path, matrix, options,
  8878. strokePadding);
  8879. if (!stroke)
  8880. return bounds;
  8881. var strokeRadius = strokeWidth / 2,
  8882. join = style.getStrokeJoin(),
  8883. cap = style.getStrokeCap(),
  8884. miterLimit = style.getMiterLimit(),
  8885. joinBounds = new Rectangle(new Size(strokePadding));
  8886. function addPoint(point) {
  8887. bounds = bounds.include(point);
  8888. }
  8889. function addRound(segment) {
  8890. bounds = bounds.unite(
  8891. joinBounds.setCenter(segment._point.transform(matrix)));
  8892. }
  8893. function addJoin(segment, join) {
  8894. if (join === 'round' || segment.isSmooth()) {
  8895. addRound(segment);
  8896. } else {
  8897. Path._addBevelJoin(segment, join, strokeRadius, miterLimit,
  8898. matrix, strokeMatrix, addPoint);
  8899. }
  8900. }
  8901. function addCap(segment, cap) {
  8902. if (cap === 'round') {
  8903. addRound(segment);
  8904. } else {
  8905. Path._addSquareCap(segment, cap, strokeRadius, matrix,
  8906. strokeMatrix, addPoint);
  8907. }
  8908. }
  8909. var length = segments.length - (closed ? 0 : 1);
  8910. if (length > 0) {
  8911. for (var i = 1; i < length; i++) {
  8912. addJoin(segments[i], join);
  8913. }
  8914. if (closed) {
  8915. addJoin(segments[0], join);
  8916. } else {
  8917. addCap(segments[0], cap);
  8918. addCap(segments[segments.length - 1], cap);
  8919. }
  8920. }
  8921. return bounds;
  8922. },
  8923. _getStrokePadding: function(radius, matrix) {
  8924. if (!matrix)
  8925. return [radius, radius];
  8926. var hor = new Point(radius, 0).transform(matrix),
  8927. ver = new Point(0, radius).transform(matrix),
  8928. phi = hor.getAngleInRadians(),
  8929. a = hor.getLength(),
  8930. b = ver.getLength();
  8931. var sin = Math.sin(phi),
  8932. cos = Math.cos(phi),
  8933. tan = Math.tan(phi),
  8934. tx = Math.atan2(b * tan, a),
  8935. ty = Math.atan2(b, tan * a);
  8936. return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin),
  8937. Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
  8938. },
  8939. _addBevelJoin: function(segment, join, radius, miterLimit, matrix,
  8940. strokeMatrix, addPoint, isArea) {
  8941. var curve2 = segment.getCurve(),
  8942. curve1 = curve2.getPrevious(),
  8943. point = curve2.getPoint1().transform(matrix),
  8944. normal1 = curve1.getNormalAtTime(1).multiply(radius)
  8945. .transform(strokeMatrix),
  8946. normal2 = curve2.getNormalAtTime(0).multiply(radius)
  8947. .transform(strokeMatrix),
  8948. angle = normal1.getDirectedAngle(normal2);
  8949. if (angle < 0 || angle >= 180) {
  8950. normal1 = normal1.negate();
  8951. normal2 = normal2.negate();
  8952. }
  8953. if (isArea)
  8954. addPoint(point);
  8955. addPoint(point.add(normal1));
  8956. if (join === 'miter') {
  8957. var corner = new Line(point.add(normal1),
  8958. new Point(-normal1.y, normal1.x), true
  8959. ).intersect(new Line(point.add(normal2),
  8960. new Point(-normal2.y, normal2.x), true
  8961. ), true);
  8962. if (corner && point.getDistance(corner) <= miterLimit * radius) {
  8963. addPoint(corner);
  8964. }
  8965. }
  8966. addPoint(point.add(normal2));
  8967. },
  8968. _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix,
  8969. addPoint, isArea) {
  8970. var point = segment._point.transform(matrix),
  8971. loc = segment.getLocation(),
  8972. normal = loc.getNormal()
  8973. .multiply(loc.getTime() === 0 ? radius : -radius)
  8974. .transform(strokeMatrix);
  8975. if (cap === 'square') {
  8976. if (isArea) {
  8977. addPoint(point.subtract(normal));
  8978. addPoint(point.add(normal));
  8979. }
  8980. point = point.add(normal.rotate(-90));
  8981. }
  8982. addPoint(point.add(normal));
  8983. addPoint(point.subtract(normal));
  8984. },
  8985. getHandleBounds: function(segments, closed, path, matrix, options) {
  8986. var style = path.getStyle(),
  8987. stroke = options.stroke && style.hasStroke(),
  8988. strokePadding,
  8989. joinPadding;
  8990. if (stroke) {
  8991. var strokeMatrix = path._getStrokeMatrix(matrix, options),
  8992. strokeRadius = style.getStrokeWidth() / 2,
  8993. joinRadius = strokeRadius;
  8994. if (style.getStrokeJoin() === 'miter')
  8995. joinRadius = strokeRadius * style.getMiterLimit();
  8996. if (style.getStrokeCap() === 'square')
  8997. joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2);
  8998. strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix);
  8999. joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix);
  9000. }
  9001. var coords = new Array(6),
  9002. x1 = Infinity,
  9003. x2 = -x1,
  9004. y1 = x1,
  9005. y2 = x2;
  9006. for (var i = 0, l = segments.length; i < l; i++) {
  9007. var segment = segments[i];
  9008. segment._transformCoordinates(matrix, coords);
  9009. for (var j = 0; j < 6; j += 2) {
  9010. var padding = !j ? joinPadding : strokePadding,
  9011. paddingX = padding ? padding[0] : 0,
  9012. paddingY = padding ? padding[1] : 0,
  9013. x = coords[j],
  9014. y = coords[j + 1],
  9015. xn = x - paddingX,
  9016. xx = x + paddingX,
  9017. yn = y - paddingY,
  9018. yx = y + paddingY;
  9019. if (xn < x1) x1 = xn;
  9020. if (xx > x2) x2 = xx;
  9021. if (yn < y1) y1 = yn;
  9022. if (yx > y2) y2 = yx;
  9023. }
  9024. }
  9025. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  9026. }
  9027. }});
  9028. Path.inject({ statics: new function() {
  9029. var kappa = 0.5522847498307936,
  9030. ellipseSegments = [
  9031. new Segment([-1, 0], [0, kappa ], [0, -kappa]),
  9032. new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
  9033. new Segment([1, 0], [0, -kappa], [0, kappa ]),
  9034. new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
  9035. ];
  9036. function createPath(segments, closed, args) {
  9037. var props = Base.getNamed(args),
  9038. path = new Path(props && props.insert == false && Item.NO_INSERT);
  9039. path._add(segments);
  9040. path._closed = closed;
  9041. return path.set(props, { insert: true });
  9042. }
  9043. function createEllipse(center, radius, args) {
  9044. var segments = new Array(4);
  9045. for (var i = 0; i < 4; i++) {
  9046. var segment = ellipseSegments[i];
  9047. segments[i] = new Segment(
  9048. segment._point.multiply(radius).add(center),
  9049. segment._handleIn.multiply(radius),
  9050. segment._handleOut.multiply(radius)
  9051. );
  9052. }
  9053. return createPath(segments, true, args);
  9054. }
  9055. return {
  9056. Line: function() {
  9057. var args = arguments;
  9058. return createPath([
  9059. new Segment(Point.readNamed(args, 'from')),
  9060. new Segment(Point.readNamed(args, 'to'))
  9061. ], false, args);
  9062. },
  9063. Circle: function() {
  9064. var args = arguments,
  9065. center = Point.readNamed(args, 'center'),
  9066. radius = Base.readNamed(args, 'radius');
  9067. return createEllipse(center, new Size(radius), args);
  9068. },
  9069. Rectangle: function() {
  9070. var args = arguments,
  9071. rect = Rectangle.readNamed(args, 'rectangle'),
  9072. radius = Size.readNamed(args, 'radius', 0,
  9073. { readNull: true }),
  9074. bl = rect.getBottomLeft(true),
  9075. tl = rect.getTopLeft(true),
  9076. tr = rect.getTopRight(true),
  9077. br = rect.getBottomRight(true),
  9078. segments;
  9079. if (!radius || radius.isZero()) {
  9080. segments = [
  9081. new Segment(bl),
  9082. new Segment(tl),
  9083. new Segment(tr),
  9084. new Segment(br)
  9085. ];
  9086. } else {
  9087. radius = Size.min(radius, rect.getSize(true).divide(2));
  9088. var rx = radius.width,
  9089. ry = radius.height,
  9090. hx = rx * kappa,
  9091. hy = ry * kappa;
  9092. segments = [
  9093. new Segment(bl.add(rx, 0), null, [-hx, 0]),
  9094. new Segment(bl.subtract(0, ry), [0, hy]),
  9095. new Segment(tl.add(0, ry), null, [0, -hy]),
  9096. new Segment(tl.add(rx, 0), [-hx, 0], null),
  9097. new Segment(tr.subtract(rx, 0), null, [hx, 0]),
  9098. new Segment(tr.add(0, ry), [0, -hy], null),
  9099. new Segment(br.subtract(0, ry), null, [0, hy]),
  9100. new Segment(br.subtract(rx, 0), [hx, 0])
  9101. ];
  9102. }
  9103. return createPath(segments, true, args);
  9104. },
  9105. RoundRectangle: '#Rectangle',
  9106. Ellipse: function() {
  9107. var args = arguments,
  9108. ellipse = Shape._readEllipse(args);
  9109. return createEllipse(ellipse.center, ellipse.radius, args);
  9110. },
  9111. Oval: '#Ellipse',
  9112. Arc: function() {
  9113. var args = arguments,
  9114. from = Point.readNamed(args, 'from'),
  9115. through = Point.readNamed(args, 'through'),
  9116. to = Point.readNamed(args, 'to'),
  9117. props = Base.getNamed(args),
  9118. path = new Path(props && props.insert == false
  9119. && Item.NO_INSERT);
  9120. path.moveTo(from);
  9121. path.arcTo(through, to);
  9122. return path.set(props);
  9123. },
  9124. RegularPolygon: function() {
  9125. var args = arguments,
  9126. center = Point.readNamed(args, 'center'),
  9127. sides = Base.readNamed(args, 'sides'),
  9128. radius = Base.readNamed(args, 'radius'),
  9129. step = 360 / sides,
  9130. three = sides % 3 === 0,
  9131. vector = new Point(0, three ? -radius : radius),
  9132. offset = three ? -1 : 0.5,
  9133. segments = new Array(sides);
  9134. for (var i = 0; i < sides; i++)
  9135. segments[i] = new Segment(center.add(
  9136. vector.rotate((i + offset) * step)));
  9137. return createPath(segments, true, args);
  9138. },
  9139. Star: function() {
  9140. var args = arguments,
  9141. center = Point.readNamed(args, 'center'),
  9142. points = Base.readNamed(args, 'points') * 2,
  9143. radius1 = Base.readNamed(args, 'radius1'),
  9144. radius2 = Base.readNamed(args, 'radius2'),
  9145. step = 360 / points,
  9146. vector = new Point(0, -1),
  9147. segments = new Array(points);
  9148. for (var i = 0; i < points; i++)
  9149. segments[i] = new Segment(center.add(vector.rotate(step * i)
  9150. .multiply(i % 2 ? radius2 : radius1)));
  9151. return createPath(segments, true, args);
  9152. }
  9153. };
  9154. }});
  9155. var CompoundPath = PathItem.extend({
  9156. _class: 'CompoundPath',
  9157. _serializeFields: {
  9158. children: []
  9159. },
  9160. beans: true,
  9161. initialize: function CompoundPath(arg) {
  9162. this._children = [];
  9163. this._namedChildren = {};
  9164. if (!this._initialize(arg)) {
  9165. if (typeof arg === 'string') {
  9166. this.setPathData(arg);
  9167. } else {
  9168. this.addChildren(Array.isArray(arg) ? arg : arguments);
  9169. }
  9170. }
  9171. },
  9172. insertChildren: function insertChildren(index, items) {
  9173. var list = items,
  9174. first = list[0];
  9175. if (first && typeof first[0] === 'number')
  9176. list = [list];
  9177. for (var i = items.length - 1; i >= 0; i--) {
  9178. var item = list[i];
  9179. if (list === items && !(item instanceof Path))
  9180. list = Base.slice(list);
  9181. if (Array.isArray(item)) {
  9182. list[i] = new Path({ segments: item, insert: false });
  9183. } else if (item instanceof CompoundPath) {
  9184. list.splice.apply(list, [i, 1].concat(item.removeChildren()));
  9185. item.remove();
  9186. }
  9187. }
  9188. return insertChildren.base.call(this, index, list);
  9189. },
  9190. reduce: function reduce(options) {
  9191. var children = this._children;
  9192. for (var i = children.length - 1; i >= 0; i--) {
  9193. var path = children[i].reduce(options);
  9194. if (path.isEmpty())
  9195. path.remove();
  9196. }
  9197. if (!children.length) {
  9198. var path = new Path(Item.NO_INSERT);
  9199. path.copyAttributes(this);
  9200. path.insertAbove(this);
  9201. this.remove();
  9202. return path;
  9203. }
  9204. return reduce.base.call(this);
  9205. },
  9206. isClosed: function() {
  9207. var children = this._children;
  9208. for (var i = 0, l = children.length; i < l; i++) {
  9209. if (!children[i]._closed)
  9210. return false;
  9211. }
  9212. return true;
  9213. },
  9214. setClosed: function(closed) {
  9215. var children = this._children;
  9216. for (var i = 0, l = children.length; i < l; i++) {
  9217. children[i].setClosed(closed);
  9218. }
  9219. },
  9220. getFirstSegment: function() {
  9221. var first = this.getFirstChild();
  9222. return first && first.getFirstSegment();
  9223. },
  9224. getLastSegment: function() {
  9225. var last = this.getLastChild();
  9226. return last && last.getLastSegment();
  9227. },
  9228. getCurves: function() {
  9229. var children = this._children,
  9230. curves = [];
  9231. for (var i = 0, l = children.length; i < l; i++) {
  9232. Base.push(curves, children[i].getCurves());
  9233. }
  9234. return curves;
  9235. },
  9236. getFirstCurve: function() {
  9237. var first = this.getFirstChild();
  9238. return first && first.getFirstCurve();
  9239. },
  9240. getLastCurve: function() {
  9241. var last = this.getLastChild();
  9242. return last && last.getLastCurve();
  9243. },
  9244. getArea: function() {
  9245. var children = this._children,
  9246. area = 0;
  9247. for (var i = 0, l = children.length; i < l; i++)
  9248. area += children[i].getArea();
  9249. return area;
  9250. },
  9251. getLength: function() {
  9252. var children = this._children,
  9253. length = 0;
  9254. for (var i = 0, l = children.length; i < l; i++)
  9255. length += children[i].getLength();
  9256. return length;
  9257. },
  9258. getPathData: function(_matrix, _precision) {
  9259. var children = this._children,
  9260. paths = [];
  9261. for (var i = 0, l = children.length; i < l; i++) {
  9262. var child = children[i],
  9263. mx = child._matrix;
  9264. paths.push(child.getPathData(_matrix && !mx.isIdentity()
  9265. ? _matrix.appended(mx) : _matrix, _precision));
  9266. }
  9267. return paths.join('');
  9268. },
  9269. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  9270. return _hitTestChildren.base.call(this, point,
  9271. options.class === Path || options.type === 'path' ? options
  9272. : Base.set({}, options, { fill: false }),
  9273. viewMatrix);
  9274. },
  9275. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  9276. var children = this._children;
  9277. if (!children.length)
  9278. return;
  9279. param = param.extend({ dontStart: true, dontFinish: true });
  9280. ctx.beginPath();
  9281. for (var i = 0, l = children.length; i < l; i++)
  9282. children[i].draw(ctx, param, strokeMatrix);
  9283. if (!param.clip) {
  9284. this._setStyles(ctx, param, viewMatrix);
  9285. var style = this._style;
  9286. if (style.hasFill()) {
  9287. ctx.fill(style.getFillRule());
  9288. ctx.shadowColor = 'rgba(0,0,0,0)';
  9289. }
  9290. if (style.hasStroke())
  9291. ctx.stroke();
  9292. }
  9293. },
  9294. _drawSelected: function(ctx, matrix, selectionItems) {
  9295. var children = this._children;
  9296. for (var i = 0, l = children.length; i < l; i++) {
  9297. var child = children[i],
  9298. mx = child._matrix;
  9299. if (!selectionItems[child._id]) {
  9300. child._drawSelected(ctx, mx.isIdentity() ? matrix
  9301. : matrix.appended(mx));
  9302. }
  9303. }
  9304. }
  9305. },
  9306. new function() {
  9307. function getCurrentPath(that, check) {
  9308. var children = that._children;
  9309. if (check && !children.length)
  9310. throw new Error('Use a moveTo() command first');
  9311. return children[children.length - 1];
  9312. }
  9313. return Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
  9314. 'arcTo', 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy',
  9315. 'arcBy'],
  9316. function(key) {
  9317. this[key] = function() {
  9318. var path = getCurrentPath(this, true);
  9319. path[key].apply(path, arguments);
  9320. };
  9321. }, {
  9322. moveTo: function() {
  9323. var current = getCurrentPath(this),
  9324. path = current && current.isEmpty() ? current
  9325. : new Path(Item.NO_INSERT);
  9326. if (path !== current)
  9327. this.addChild(path);
  9328. path.moveTo.apply(path, arguments);
  9329. },
  9330. moveBy: function() {
  9331. var current = getCurrentPath(this, true),
  9332. last = current && current.getLastSegment(),
  9333. point = Point.read(arguments);
  9334. this.moveTo(last ? point.add(last._point) : point);
  9335. },
  9336. closePath: function(tolerance) {
  9337. getCurrentPath(this, true).closePath(tolerance);
  9338. }
  9339. }
  9340. );
  9341. }, Base.each(['reverse', 'flatten', 'simplify', 'smooth'], function(key) {
  9342. this[key] = function(param) {
  9343. var children = this._children,
  9344. res;
  9345. for (var i = 0, l = children.length; i < l; i++) {
  9346. res = children[i][key](param) || res;
  9347. }
  9348. return res;
  9349. };
  9350. }, {}));
  9351. PathItem.inject(new function() {
  9352. var min = Math.min,
  9353. max = Math.max,
  9354. abs = Math.abs,
  9355. operators = {
  9356. unite: { '1': true, '2': true },
  9357. intersect: { '2': true },
  9358. subtract: { '1': true },
  9359. exclude: { '1': true, '-1': true }
  9360. };
  9361. function getPaths(path) {
  9362. return path._children || [path];
  9363. }
  9364. function preparePath(path, resolve) {
  9365. var res = path
  9366. .clone(false)
  9367. .reduce({ simplify: true })
  9368. .transform(null, true, true);
  9369. if (resolve) {
  9370. var paths = getPaths(res);
  9371. for (var i = 0, l = paths.length; i < l; i++) {
  9372. var path = paths[i];
  9373. if (!path._closed && !path.isEmpty()) {
  9374. path.closePath(1e-12);
  9375. path.getFirstSegment().setHandleIn(0, 0);
  9376. path.getLastSegment().setHandleOut(0, 0);
  9377. }
  9378. }
  9379. res = res
  9380. .resolveCrossings()
  9381. .reorient(res.getFillRule() === 'nonzero', true);
  9382. }
  9383. return res;
  9384. }
  9385. function createResult(paths, simplify, path1, path2, options) {
  9386. var result = new CompoundPath(Item.NO_INSERT);
  9387. result.addChildren(paths, true);
  9388. result = result.reduce({ simplify: simplify });
  9389. if (!(options && options.insert == false)) {
  9390. result.insertAbove(path2 && path1.isSibling(path2)
  9391. && path1.getIndex() < path2.getIndex() ? path2 : path1);
  9392. }
  9393. result.copyAttributes(path1, true);
  9394. return result;
  9395. }
  9396. function filterIntersection(inter) {
  9397. return inter.hasOverlap() || inter.isCrossing();
  9398. }
  9399. function traceBoolean(path1, path2, operation, options) {
  9400. if (options && (options.trace == false || options.stroke) &&
  9401. /^(subtract|intersect)$/.test(operation))
  9402. return splitBoolean(path1, path2, operation);
  9403. var _path1 = preparePath(path1, true),
  9404. _path2 = path2 && path1 !== path2 && preparePath(path2, true),
  9405. operator = operators[operation];
  9406. operator[operation] = true;
  9407. if (_path2 && (operator.subtract || operator.exclude)
  9408. ^ (_path2.isClockwise() ^ _path1.isClockwise()))
  9409. _path2.reverse();
  9410. var crossings = divideLocations(CurveLocation.expand(
  9411. _path1.getIntersections(_path2, filterIntersection))),
  9412. paths1 = getPaths(_path1),
  9413. paths2 = _path2 && getPaths(_path2),
  9414. segments = [],
  9415. curves = [],
  9416. paths;
  9417. function collectPaths(paths) {
  9418. for (var i = 0, l = paths.length; i < l; i++) {
  9419. var path = paths[i];
  9420. Base.push(segments, path._segments);
  9421. Base.push(curves, path.getCurves());
  9422. path._overlapsOnly = true;
  9423. }
  9424. }
  9425. function getCurves(indices) {
  9426. var list = [];
  9427. for (var i = 0, l = indices && indices.length; i < l; i++) {
  9428. list.push(curves[indices[i]]);
  9429. }
  9430. return list;
  9431. }
  9432. if (crossings.length) {
  9433. collectPaths(paths1);
  9434. if (paths2)
  9435. collectPaths(paths2);
  9436. var curvesValues = new Array(curves.length);
  9437. for (var i = 0, l = curves.length; i < l; i++) {
  9438. curvesValues[i] = curves[i].getValues();
  9439. }
  9440. var curveCollisions = CollisionDetection.findCurveBoundsCollisions(
  9441. curvesValues, curvesValues, 0, true);
  9442. var curveCollisionsMap = {};
  9443. for (var i = 0; i < curves.length; i++) {
  9444. var curve = curves[i],
  9445. id = curve._path._id,
  9446. map = curveCollisionsMap[id] = curveCollisionsMap[id] || {};
  9447. map[curve.getIndex()] = {
  9448. hor: getCurves(curveCollisions[i].hor),
  9449. ver: getCurves(curveCollisions[i].ver)
  9450. };
  9451. }
  9452. for (var i = 0, l = crossings.length; i < l; i++) {
  9453. propagateWinding(crossings[i]._segment, _path1, _path2,
  9454. curveCollisionsMap, operator);
  9455. }
  9456. for (var i = 0, l = segments.length; i < l; i++) {
  9457. var segment = segments[i],
  9458. inter = segment._intersection;
  9459. if (!segment._winding) {
  9460. propagateWinding(segment, _path1, _path2,
  9461. curveCollisionsMap, operator);
  9462. }
  9463. if (!(inter && inter._overlap))
  9464. segment._path._overlapsOnly = false;
  9465. }
  9466. paths = tracePaths(segments, operator);
  9467. } else {
  9468. paths = reorientPaths(
  9469. paths2 ? paths1.concat(paths2) : paths1.slice(),
  9470. function(w) {
  9471. return !!operator[w];
  9472. });
  9473. }
  9474. return createResult(paths, true, path1, path2, options);
  9475. }
  9476. function splitBoolean(path1, path2, operation) {
  9477. var _path1 = preparePath(path1),
  9478. _path2 = preparePath(path2),
  9479. crossings = _path1.getIntersections(_path2, filterIntersection),
  9480. subtract = operation === 'subtract',
  9481. divide = operation === 'divide',
  9482. added = {},
  9483. paths = [];
  9484. function addPath(path) {
  9485. if (!added[path._id] && (divide ||
  9486. _path2.contains(path.getPointAt(path.getLength() / 2))
  9487. ^ subtract)) {
  9488. paths.unshift(path);
  9489. return added[path._id] = true;
  9490. }
  9491. }
  9492. for (var i = crossings.length - 1; i >= 0; i--) {
  9493. var path = crossings[i].split();
  9494. if (path) {
  9495. if (addPath(path))
  9496. path.getFirstSegment().setHandleIn(0, 0);
  9497. _path1.getLastSegment().setHandleOut(0, 0);
  9498. }
  9499. }
  9500. addPath(_path1);
  9501. return createResult(paths, false, path1, path2);
  9502. }
  9503. function linkIntersections(from, to) {
  9504. var prev = from;
  9505. while (prev) {
  9506. if (prev === to)
  9507. return;
  9508. prev = prev._previous;
  9509. }
  9510. while (from._next && from._next !== to)
  9511. from = from._next;
  9512. if (!from._next) {
  9513. while (to._previous)
  9514. to = to._previous;
  9515. from._next = to;
  9516. to._previous = from;
  9517. }
  9518. }
  9519. function clearCurveHandles(curves) {
  9520. for (var i = curves.length - 1; i >= 0; i--)
  9521. curves[i].clearHandles();
  9522. }
  9523. function reorientPaths(paths, isInside, clockwise) {
  9524. var length = paths && paths.length;
  9525. if (length) {
  9526. var lookup = Base.each(paths, function (path, i) {
  9527. this[path._id] = {
  9528. container: null,
  9529. winding: path.isClockwise() ? 1 : -1,
  9530. index: i
  9531. };
  9532. }, {}),
  9533. sorted = paths.slice().sort(function (a, b) {
  9534. return abs(b.getArea()) - abs(a.getArea());
  9535. }),
  9536. first = sorted[0];
  9537. var collisions = CollisionDetection.findItemBoundsCollisions(sorted,
  9538. null, Numerical.GEOMETRIC_EPSILON);
  9539. if (clockwise == null)
  9540. clockwise = first.isClockwise();
  9541. for (var i = 0; i < length; i++) {
  9542. var path1 = sorted[i],
  9543. entry1 = lookup[path1._id],
  9544. containerWinding = 0,
  9545. indices = collisions[i];
  9546. if (indices) {
  9547. var point = null;
  9548. for (var j = indices.length - 1; j >= 0; j--) {
  9549. if (indices[j] < i) {
  9550. point = point || path1.getInteriorPoint();
  9551. var path2 = sorted[indices[j]];
  9552. if (path2.contains(point)) {
  9553. var entry2 = lookup[path2._id];
  9554. containerWinding = entry2.winding;
  9555. entry1.winding += containerWinding;
  9556. entry1.container = entry2.exclude
  9557. ? entry2.container : path2;
  9558. break;
  9559. }
  9560. }
  9561. }
  9562. }
  9563. if (isInside(entry1.winding) === isInside(containerWinding)) {
  9564. entry1.exclude = true;
  9565. paths[entry1.index] = null;
  9566. } else {
  9567. var container = entry1.container;
  9568. path1.setClockwise(
  9569. container ? !container.isClockwise() : clockwise);
  9570. }
  9571. }
  9572. }
  9573. return paths;
  9574. }
  9575. function divideLocations(locations, include, clearLater) {
  9576. var results = include && [],
  9577. tMin = 1e-8,
  9578. tMax = 1 - tMin,
  9579. clearHandles = false,
  9580. clearCurves = clearLater || [],
  9581. clearLookup = clearLater && {},
  9582. renormalizeLocs,
  9583. prevCurve,
  9584. prevTime;
  9585. function getId(curve) {
  9586. return curve._path._id + '.' + curve._segment1._index;
  9587. }
  9588. for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) {
  9589. var curve = clearLater[i];
  9590. if (curve._path)
  9591. clearLookup[getId(curve)] = true;
  9592. }
  9593. for (var i = locations.length - 1; i >= 0; i--) {
  9594. var loc = locations[i],
  9595. time = loc._time,
  9596. origTime = time,
  9597. exclude = include && !include(loc),
  9598. curve = loc._curve,
  9599. segment;
  9600. if (curve) {
  9601. if (curve !== prevCurve) {
  9602. clearHandles = !curve.hasHandles()
  9603. || clearLookup && clearLookup[getId(curve)];
  9604. renormalizeLocs = [];
  9605. prevTime = null;
  9606. prevCurve = curve;
  9607. } else if (prevTime >= tMin) {
  9608. time /= prevTime;
  9609. }
  9610. }
  9611. if (exclude) {
  9612. if (renormalizeLocs)
  9613. renormalizeLocs.push(loc);
  9614. continue;
  9615. } else if (include) {
  9616. results.unshift(loc);
  9617. }
  9618. prevTime = origTime;
  9619. if (time < tMin) {
  9620. segment = curve._segment1;
  9621. } else if (time > tMax) {
  9622. segment = curve._segment2;
  9623. } else {
  9624. var newCurve = curve.divideAtTime(time, true);
  9625. if (clearHandles)
  9626. clearCurves.push(curve, newCurve);
  9627. segment = newCurve._segment1;
  9628. for (var j = renormalizeLocs.length - 1; j >= 0; j--) {
  9629. var l = renormalizeLocs[j];
  9630. l._time = (l._time - time) / (1 - time);
  9631. }
  9632. }
  9633. loc._setSegment(segment);
  9634. var inter = segment._intersection,
  9635. dest = loc._intersection;
  9636. if (inter) {
  9637. linkIntersections(inter, dest);
  9638. var other = inter;
  9639. while (other) {
  9640. linkIntersections(other._intersection, inter);
  9641. other = other._next;
  9642. }
  9643. } else {
  9644. segment._intersection = dest;
  9645. }
  9646. }
  9647. if (!clearLater)
  9648. clearCurveHandles(clearCurves);
  9649. return results || locations;
  9650. }
  9651. function getWinding(point, curves, dir, closed, dontFlip) {
  9652. var curvesList = Array.isArray(curves)
  9653. ? curves
  9654. : curves[dir ? 'hor' : 'ver'];
  9655. var ia = dir ? 1 : 0,
  9656. io = ia ^ 1,
  9657. pv = [point.x, point.y],
  9658. pa = pv[ia],
  9659. po = pv[io],
  9660. windingEpsilon = 1e-9,
  9661. qualityEpsilon = 1e-6,
  9662. paL = pa - windingEpsilon,
  9663. paR = pa + windingEpsilon,
  9664. windingL = 0,
  9665. windingR = 0,
  9666. pathWindingL = 0,
  9667. pathWindingR = 0,
  9668. onPath = false,
  9669. onAnyPath = false,
  9670. quality = 1,
  9671. roots = [],
  9672. vPrev,
  9673. vClose;
  9674. function addWinding(v) {
  9675. var o0 = v[io + 0],
  9676. o3 = v[io + 6];
  9677. if (po < min(o0, o3) || po > max(o0, o3)) {
  9678. return;
  9679. }
  9680. var a0 = v[ia + 0],
  9681. a1 = v[ia + 2],
  9682. a2 = v[ia + 4],
  9683. a3 = v[ia + 6];
  9684. if (o0 === o3) {
  9685. if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) {
  9686. onPath = true;
  9687. }
  9688. return;
  9689. }
  9690. var t = po === o0 ? 0
  9691. : po === o3 ? 1
  9692. : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3)
  9693. ? 1
  9694. : Curve.solveCubic(v, io, po, roots, 0, 1) > 0
  9695. ? roots[0]
  9696. : 1,
  9697. a = t === 0 ? a0
  9698. : t === 1 ? a3
  9699. : Curve.getPoint(v, t)[dir ? 'y' : 'x'],
  9700. winding = o0 > o3 ? 1 : -1,
  9701. windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1,
  9702. a3Prev = vPrev[ia + 6];
  9703. if (po !== o0) {
  9704. if (a < paL) {
  9705. pathWindingL += winding;
  9706. } else if (a > paR) {
  9707. pathWindingR += winding;
  9708. } else {
  9709. onPath = true;
  9710. }
  9711. if (a > pa - qualityEpsilon && a < pa + qualityEpsilon)
  9712. quality /= 2;
  9713. } else {
  9714. if (winding !== windingPrev) {
  9715. if (a0 < paL) {
  9716. pathWindingL += winding;
  9717. } else if (a0 > paR) {
  9718. pathWindingR += winding;
  9719. }
  9720. } else if (a0 != a3Prev) {
  9721. if (a3Prev < paR && a > paR) {
  9722. pathWindingR += winding;
  9723. onPath = true;
  9724. } else if (a3Prev > paL && a < paL) {
  9725. pathWindingL += winding;
  9726. onPath = true;
  9727. }
  9728. }
  9729. quality /= 4;
  9730. }
  9731. vPrev = v;
  9732. return !dontFlip && a > paL && a < paR
  9733. && Curve.getTangent(v, t)[dir ? 'x' : 'y'] === 0
  9734. && getWinding(point, curves, !dir, closed, true);
  9735. }
  9736. function handleCurve(v) {
  9737. var o0 = v[io + 0],
  9738. o1 = v[io + 2],
  9739. o2 = v[io + 4],
  9740. o3 = v[io + 6];
  9741. if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) {
  9742. var a0 = v[ia + 0],
  9743. a1 = v[ia + 2],
  9744. a2 = v[ia + 4],
  9745. a3 = v[ia + 6],
  9746. monoCurves = paL > max(a0, a1, a2, a3) ||
  9747. paR < min(a0, a1, a2, a3)
  9748. ? [v] : Curve.getMonoCurves(v, dir),
  9749. res;
  9750. for (var i = 0, l = monoCurves.length; i < l; i++) {
  9751. if (res = addWinding(monoCurves[i]))
  9752. return res;
  9753. }
  9754. }
  9755. }
  9756. for (var i = 0, l = curvesList.length; i < l; i++) {
  9757. var curve = curvesList[i],
  9758. path = curve._path,
  9759. v = curve.getValues(),
  9760. res;
  9761. if (!i || curvesList[i - 1]._path !== path) {
  9762. vPrev = null;
  9763. if (!path._closed) {
  9764. vClose = Curve.getValues(
  9765. path.getLastCurve().getSegment2(),
  9766. curve.getSegment1(),
  9767. null, !closed);
  9768. if (vClose[io] !== vClose[io + 6]) {
  9769. vPrev = vClose;
  9770. }
  9771. }
  9772. if (!vPrev) {
  9773. vPrev = v;
  9774. var prev = path.getLastCurve();
  9775. while (prev && prev !== curve) {
  9776. var v2 = prev.getValues();
  9777. if (v2[io] !== v2[io + 6]) {
  9778. vPrev = v2;
  9779. break;
  9780. }
  9781. prev = prev.getPrevious();
  9782. }
  9783. }
  9784. }
  9785. if (res = handleCurve(v))
  9786. return res;
  9787. if (i + 1 === l || curvesList[i + 1]._path !== path) {
  9788. if (vClose && (res = handleCurve(vClose)))
  9789. return res;
  9790. if (onPath && !pathWindingL && !pathWindingR) {
  9791. pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir
  9792. ? 1 : -1;
  9793. }
  9794. windingL += pathWindingL;
  9795. windingR += pathWindingR;
  9796. pathWindingL = pathWindingR = 0;
  9797. if (onPath) {
  9798. onAnyPath = true;
  9799. onPath = false;
  9800. }
  9801. vClose = null;
  9802. }
  9803. }
  9804. windingL = abs(windingL);
  9805. windingR = abs(windingR);
  9806. return {
  9807. winding: max(windingL, windingR),
  9808. windingL: windingL,
  9809. windingR: windingR,
  9810. quality: quality,
  9811. onPath: onAnyPath
  9812. };
  9813. }
  9814. function propagateWinding(segment, path1, path2, curveCollisionsMap,
  9815. operator) {
  9816. var chain = [],
  9817. start = segment,
  9818. totalLength = 0,
  9819. winding;
  9820. do {
  9821. var curve = segment.getCurve();
  9822. if (curve) {
  9823. var length = curve.getLength();
  9824. chain.push({ segment: segment, curve: curve, length: length });
  9825. totalLength += length;
  9826. }
  9827. segment = segment.getNext();
  9828. } while (segment && !segment._intersection && segment !== start);
  9829. var offsets = [0.5, 0.25, 0.75],
  9830. winding = { winding: 0, quality: -1 },
  9831. tMin = 1e-3,
  9832. tMax = 1 - tMin;
  9833. for (var i = 0; i < offsets.length && winding.quality < 0.5; i++) {
  9834. var length = totalLength * offsets[i];
  9835. for (var j = 0, l = chain.length; j < l; j++) {
  9836. var entry = chain[j],
  9837. curveLength = entry.length;
  9838. if (length <= curveLength) {
  9839. var curve = entry.curve,
  9840. path = curve._path,
  9841. parent = path._parent,
  9842. operand = parent instanceof CompoundPath ? parent : path,
  9843. t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax),
  9844. pt = curve.getPointAtTime(t),
  9845. dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2;
  9846. var wind = null;
  9847. if (operator.subtract && path2) {
  9848. var otherPath = operand === path1 ? path2 : path1,
  9849. pathWinding = otherPath._getWinding(pt, dir, true);
  9850. if (operand === path1 && pathWinding.winding ||
  9851. operand === path2 && !pathWinding.winding) {
  9852. if (pathWinding.quality < 1) {
  9853. continue;
  9854. } else {
  9855. wind = { winding: 0, quality: 1 };
  9856. }
  9857. }
  9858. }
  9859. wind = wind || getWinding(
  9860. pt, curveCollisionsMap[path._id][curve.getIndex()],
  9861. dir, true);
  9862. if (wind.quality > winding.quality)
  9863. winding = wind;
  9864. break;
  9865. }
  9866. length -= curveLength;
  9867. }
  9868. }
  9869. for (var j = chain.length - 1; j >= 0; j--) {
  9870. chain[j].segment._winding = winding;
  9871. }
  9872. }
  9873. function tracePaths(segments, operator) {
  9874. var paths = [],
  9875. starts;
  9876. function isValid(seg) {
  9877. var winding;
  9878. return !!(seg && !seg._visited && (!operator
  9879. || operator[(winding = seg._winding || {}).winding]
  9880. && !(operator.unite && winding.winding === 2
  9881. && winding.windingL && winding.windingR)));
  9882. }
  9883. function isStart(seg) {
  9884. if (seg) {
  9885. for (var i = 0, l = starts.length; i < l; i++) {
  9886. if (seg === starts[i])
  9887. return true;
  9888. }
  9889. }
  9890. return false;
  9891. }
  9892. function visitPath(path) {
  9893. var segments = path._segments;
  9894. for (var i = 0, l = segments.length; i < l; i++) {
  9895. segments[i]._visited = true;
  9896. }
  9897. }
  9898. function getCrossingSegments(segment, collectStarts) {
  9899. var inter = segment._intersection,
  9900. start = inter,
  9901. crossings = [];
  9902. if (collectStarts)
  9903. starts = [segment];
  9904. function collect(inter, end) {
  9905. while (inter && inter !== end) {
  9906. var other = inter._segment,
  9907. path = other && other._path;
  9908. if (path) {
  9909. var next = other.getNext() || path.getFirstSegment(),
  9910. nextInter = next._intersection;
  9911. if (other !== segment && (isStart(other)
  9912. || isStart(next)
  9913. || next && (isValid(other) && (isValid(next)
  9914. || nextInter && isValid(nextInter._segment))))
  9915. ) {
  9916. crossings.push(other);
  9917. }
  9918. if (collectStarts)
  9919. starts.push(other);
  9920. }
  9921. inter = inter._next;
  9922. }
  9923. }
  9924. if (inter) {
  9925. collect(inter);
  9926. while (inter && inter._previous)
  9927. inter = inter._previous;
  9928. collect(inter, start);
  9929. }
  9930. return crossings;
  9931. }
  9932. segments.sort(function(seg1, seg2) {
  9933. var inter1 = seg1._intersection,
  9934. inter2 = seg2._intersection,
  9935. over1 = !!(inter1 && inter1._overlap),
  9936. over2 = !!(inter2 && inter2._overlap),
  9937. path1 = seg1._path,
  9938. path2 = seg2._path;
  9939. return over1 ^ over2
  9940. ? over1 ? 1 : -1
  9941. : !inter1 ^ !inter2
  9942. ? inter1 ? 1 : -1
  9943. : path1 !== path2
  9944. ? path1._id - path2._id
  9945. : seg1._index - seg2._index;
  9946. });
  9947. for (var i = 0, l = segments.length; i < l; i++) {
  9948. var seg = segments[i],
  9949. valid = isValid(seg),
  9950. path = null,
  9951. finished = false,
  9952. closed = true,
  9953. branches = [],
  9954. branch,
  9955. visited,
  9956. handleIn;
  9957. if (valid && seg._path._overlapsOnly) {
  9958. var path1 = seg._path,
  9959. path2 = seg._intersection._segment._path;
  9960. if (path1.compare(path2)) {
  9961. if (path1.getArea())
  9962. paths.push(path1.clone(false));
  9963. visitPath(path1);
  9964. visitPath(path2);
  9965. valid = false;
  9966. }
  9967. }
  9968. while (valid) {
  9969. var first = !path,
  9970. crossings = getCrossingSegments(seg, first),
  9971. other = crossings.shift(),
  9972. finished = !first && (isStart(seg) || isStart(other)),
  9973. cross = !finished && other;
  9974. if (first) {
  9975. path = new Path(Item.NO_INSERT);
  9976. branch = null;
  9977. }
  9978. if (finished) {
  9979. if (seg.isFirst() || seg.isLast())
  9980. closed = seg._path._closed;
  9981. seg._visited = true;
  9982. break;
  9983. }
  9984. if (cross && branch) {
  9985. branches.push(branch);
  9986. branch = null;
  9987. }
  9988. if (!branch) {
  9989. if (cross)
  9990. crossings.push(seg);
  9991. branch = {
  9992. start: path._segments.length,
  9993. crossings: crossings,
  9994. visited: visited = [],
  9995. handleIn: handleIn
  9996. };
  9997. }
  9998. if (cross)
  9999. seg = other;
  10000. if (!isValid(seg)) {
  10001. path.removeSegments(branch.start);
  10002. for (var j = 0, k = visited.length; j < k; j++) {
  10003. visited[j]._visited = false;
  10004. }
  10005. visited.length = 0;
  10006. do {
  10007. seg = branch && branch.crossings.shift();
  10008. if (!seg || !seg._path) {
  10009. seg = null;
  10010. branch = branches.pop();
  10011. if (branch) {
  10012. visited = branch.visited;
  10013. handleIn = branch.handleIn;
  10014. }
  10015. }
  10016. } while (branch && !isValid(seg));
  10017. if (!seg)
  10018. break;
  10019. }
  10020. var next = seg.getNext();
  10021. path.add(new Segment(seg._point, handleIn,
  10022. next && seg._handleOut));
  10023. seg._visited = true;
  10024. visited.push(seg);
  10025. seg = next || seg._path.getFirstSegment();
  10026. handleIn = next && next._handleIn;
  10027. }
  10028. if (finished) {
  10029. if (closed) {
  10030. path.getFirstSegment().setHandleIn(handleIn);
  10031. path.setClosed(closed);
  10032. }
  10033. if (path.getArea() !== 0) {
  10034. paths.push(path);
  10035. }
  10036. }
  10037. }
  10038. return paths;
  10039. }
  10040. return {
  10041. _getWinding: function(point, dir, closed) {
  10042. return getWinding(point, this.getCurves(), dir, closed);
  10043. },
  10044. unite: function(path, options) {
  10045. return traceBoolean(this, path, 'unite', options);
  10046. },
  10047. intersect: function(path, options) {
  10048. return traceBoolean(this, path, 'intersect', options);
  10049. },
  10050. subtract: function(path, options) {
  10051. return traceBoolean(this, path, 'subtract', options);
  10052. },
  10053. exclude: function(path, options) {
  10054. return traceBoolean(this, path, 'exclude', options);
  10055. },
  10056. divide: function(path, options) {
  10057. return options && (options.trace == false || options.stroke)
  10058. ? splitBoolean(this, path, 'divide')
  10059. : createResult([
  10060. this.subtract(path, options),
  10061. this.intersect(path, options)
  10062. ], true, this, path, options);
  10063. },
  10064. resolveCrossings: function() {
  10065. var children = this._children,
  10066. paths = children || [this];
  10067. function hasOverlap(seg, path) {
  10068. var inter = seg && seg._intersection;
  10069. return inter && inter._overlap && inter._path === path;
  10070. }
  10071. var hasOverlaps = false,
  10072. hasCrossings = false,
  10073. intersections = this.getIntersections(null, function(inter) {
  10074. return inter.hasOverlap() && (hasOverlaps = true) ||
  10075. inter.isCrossing() && (hasCrossings = true);
  10076. }),
  10077. clearCurves = hasOverlaps && hasCrossings && [];
  10078. intersections = CurveLocation.expand(intersections);
  10079. if (hasOverlaps) {
  10080. var overlaps = divideLocations(intersections, function(inter) {
  10081. return inter.hasOverlap();
  10082. }, clearCurves);
  10083. for (var i = overlaps.length - 1; i >= 0; i--) {
  10084. var overlap = overlaps[i],
  10085. path = overlap._path,
  10086. seg = overlap._segment,
  10087. prev = seg.getPrevious(),
  10088. next = seg.getNext();
  10089. if (hasOverlap(prev, path) && hasOverlap(next, path)) {
  10090. seg.remove();
  10091. prev._handleOut._set(0, 0);
  10092. next._handleIn._set(0, 0);
  10093. if (prev !== seg && !prev.getCurve().hasLength()) {
  10094. next._handleIn.set(prev._handleIn);
  10095. prev.remove();
  10096. }
  10097. }
  10098. }
  10099. }
  10100. if (hasCrossings) {
  10101. divideLocations(intersections, hasOverlaps && function(inter) {
  10102. var curve1 = inter.getCurve(),
  10103. seg1 = inter.getSegment(),
  10104. other = inter._intersection,
  10105. curve2 = other._curve,
  10106. seg2 = other._segment;
  10107. if (curve1 && curve2 && curve1._path && curve2._path)
  10108. return true;
  10109. if (seg1)
  10110. seg1._intersection = null;
  10111. if (seg2)
  10112. seg2._intersection = null;
  10113. }, clearCurves);
  10114. if (clearCurves)
  10115. clearCurveHandles(clearCurves);
  10116. paths = tracePaths(Base.each(paths, function(path) {
  10117. Base.push(this, path._segments);
  10118. }, []));
  10119. }
  10120. var length = paths.length,
  10121. item;
  10122. if (length > 1 && children) {
  10123. if (paths !== children)
  10124. this.setChildren(paths);
  10125. item = this;
  10126. } else if (length === 1 && !children) {
  10127. if (paths[0] !== this)
  10128. this.setSegments(paths[0].removeSegments());
  10129. item = this;
  10130. }
  10131. if (!item) {
  10132. item = new CompoundPath(Item.NO_INSERT);
  10133. item.addChildren(paths);
  10134. item = item.reduce();
  10135. item.copyAttributes(this);
  10136. this.replaceWith(item);
  10137. }
  10138. return item;
  10139. },
  10140. reorient: function(nonZero, clockwise) {
  10141. var children = this._children;
  10142. if (children && children.length) {
  10143. this.setChildren(reorientPaths(this.removeChildren(),
  10144. function(w) {
  10145. return !!(nonZero ? w : w & 1);
  10146. },
  10147. clockwise));
  10148. } else if (clockwise !== undefined) {
  10149. this.setClockwise(clockwise);
  10150. }
  10151. return this;
  10152. },
  10153. getInteriorPoint: function() {
  10154. var bounds = this.getBounds(),
  10155. point = bounds.getCenter(true);
  10156. if (!this.contains(point)) {
  10157. var curves = this.getCurves(),
  10158. y = point.y,
  10159. intercepts = [],
  10160. roots = [];
  10161. for (var i = 0, l = curves.length; i < l; i++) {
  10162. var v = curves[i].getValues(),
  10163. o0 = v[1],
  10164. o1 = v[3],
  10165. o2 = v[5],
  10166. o3 = v[7];
  10167. if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) {
  10168. var monoCurves = Curve.getMonoCurves(v);
  10169. for (var j = 0, m = monoCurves.length; j < m; j++) {
  10170. var mv = monoCurves[j],
  10171. mo0 = mv[1],
  10172. mo3 = mv[7];
  10173. if ((mo0 !== mo3) &&
  10174. (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)){
  10175. var x = y === mo0 ? mv[0]
  10176. : y === mo3 ? mv[6]
  10177. : Curve.solveCubic(mv, 1, y, roots, 0, 1)
  10178. === 1
  10179. ? Curve.getPoint(mv, roots[0]).x
  10180. : (mv[0] + mv[6]) / 2;
  10181. intercepts.push(x);
  10182. }
  10183. }
  10184. }
  10185. }
  10186. if (intercepts.length > 1) {
  10187. intercepts.sort(function(a, b) { return a - b; });
  10188. point.x = (intercepts[0] + intercepts[1]) / 2;
  10189. }
  10190. }
  10191. return point;
  10192. }
  10193. };
  10194. });
  10195. var PathFlattener = Base.extend({
  10196. _class: 'PathFlattener',
  10197. initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) {
  10198. var curves = [],
  10199. parts = [],
  10200. length = 0,
  10201. minSpan = 1 / (maxRecursion || 32),
  10202. segments = path._segments,
  10203. segment1 = segments[0],
  10204. segment2;
  10205. function addCurve(segment1, segment2) {
  10206. var curve = Curve.getValues(segment1, segment2, matrix);
  10207. curves.push(curve);
  10208. computeParts(curve, segment1._index, 0, 1);
  10209. }
  10210. function computeParts(curve, index, t1, t2) {
  10211. if ((t2 - t1) > minSpan
  10212. && !(ignoreStraight && Curve.isStraight(curve))
  10213. && !Curve.isFlatEnough(curve, flatness || 0.25)) {
  10214. var halves = Curve.subdivide(curve, 0.5),
  10215. tMid = (t1 + t2) / 2;
  10216. computeParts(halves[0], index, t1, tMid);
  10217. computeParts(halves[1], index, tMid, t2);
  10218. } else {
  10219. var dx = curve[6] - curve[0],
  10220. dy = curve[7] - curve[1],
  10221. dist = Math.sqrt(dx * dx + dy * dy);
  10222. if (dist > 0) {
  10223. length += dist;
  10224. parts.push({
  10225. offset: length,
  10226. curve: curve,
  10227. index: index,
  10228. time: t2,
  10229. });
  10230. }
  10231. }
  10232. }
  10233. for (var i = 1, l = segments.length; i < l; i++) {
  10234. segment2 = segments[i];
  10235. addCurve(segment1, segment2);
  10236. segment1 = segment2;
  10237. }
  10238. if (path._closed)
  10239. addCurve(segment2 || segment1, segments[0]);
  10240. this.curves = curves;
  10241. this.parts = parts;
  10242. this.length = length;
  10243. this.index = 0;
  10244. },
  10245. _get: function(offset) {
  10246. var parts = this.parts,
  10247. length = parts.length,
  10248. start,
  10249. i, j = this.index;
  10250. for (;;) {
  10251. i = j;
  10252. if (!j || parts[--j].offset < offset)
  10253. break;
  10254. }
  10255. for (; i < length; i++) {
  10256. var part = parts[i];
  10257. if (part.offset >= offset) {
  10258. this.index = i;
  10259. var prev = parts[i - 1],
  10260. prevTime = prev && prev.index === part.index ? prev.time : 0,
  10261. prevOffset = prev ? prev.offset : 0;
  10262. return {
  10263. index: part.index,
  10264. time: prevTime + (part.time - prevTime)
  10265. * (offset - prevOffset) / (part.offset - prevOffset)
  10266. };
  10267. }
  10268. }
  10269. return {
  10270. index: parts[length - 1].index,
  10271. time: 1
  10272. };
  10273. },
  10274. drawPart: function(ctx, from, to) {
  10275. var start = this._get(from),
  10276. end = this._get(to);
  10277. for (var i = start.index, l = end.index; i <= l; i++) {
  10278. var curve = Curve.getPart(this.curves[i],
  10279. i === start.index ? start.time : 0,
  10280. i === end.index ? end.time : 1);
  10281. if (i === start.index)
  10282. ctx.moveTo(curve[0], curve[1]);
  10283. ctx.bezierCurveTo.apply(ctx, curve.slice(2));
  10284. }
  10285. }
  10286. }, Base.each(Curve._evaluateMethods,
  10287. function(name) {
  10288. this[name + 'At'] = function(offset) {
  10289. var param = this._get(offset);
  10290. return Curve[name](this.curves[param.index], param.time);
  10291. };
  10292. }, {})
  10293. );
  10294. var PathFitter = Base.extend({
  10295. initialize: function(path) {
  10296. var points = this.points = [],
  10297. segments = path._segments,
  10298. closed = path._closed;
  10299. for (var i = 0, prev, l = segments.length; i < l; i++) {
  10300. var point = segments[i].point;
  10301. if (!prev || !prev.equals(point)) {
  10302. points.push(prev = point.clone());
  10303. }
  10304. }
  10305. if (closed) {
  10306. points.unshift(points[points.length - 1]);
  10307. points.push(points[1]);
  10308. }
  10309. this.closed = closed;
  10310. },
  10311. fit: function(error) {
  10312. var points = this.points,
  10313. length = points.length,
  10314. segments = null;
  10315. if (length > 0) {
  10316. segments = [new Segment(points[0])];
  10317. if (length > 1) {
  10318. this.fitCubic(segments, error, 0, length - 1,
  10319. points[1].subtract(points[0]),
  10320. points[length - 2].subtract(points[length - 1]));
  10321. if (this.closed) {
  10322. segments.shift();
  10323. segments.pop();
  10324. }
  10325. }
  10326. }
  10327. return segments;
  10328. },
  10329. fitCubic: function(segments, error, first, last, tan1, tan2) {
  10330. var points = this.points;
  10331. if (last - first === 1) {
  10332. var pt1 = points[first],
  10333. pt2 = points[last],
  10334. dist = pt1.getDistance(pt2) / 3;
  10335. this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)),
  10336. pt2.add(tan2.normalize(dist)), pt2]);
  10337. return;
  10338. }
  10339. var uPrime = this.chordLengthParameterize(first, last),
  10340. maxError = Math.max(error, error * error),
  10341. split,
  10342. parametersInOrder = true;
  10343. for (var i = 0; i <= 4; i++) {
  10344. var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
  10345. var max = this.findMaxError(first, last, curve, uPrime);
  10346. if (max.error < error && parametersInOrder) {
  10347. this.addCurve(segments, curve);
  10348. return;
  10349. }
  10350. split = max.index;
  10351. if (max.error >= maxError)
  10352. break;
  10353. parametersInOrder = this.reparameterize(first, last, uPrime, curve);
  10354. maxError = max.error;
  10355. }
  10356. var tanCenter = points[split - 1].subtract(points[split + 1]);
  10357. this.fitCubic(segments, error, first, split, tan1, tanCenter);
  10358. this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2);
  10359. },
  10360. addCurve: function(segments, curve) {
  10361. var prev = segments[segments.length - 1];
  10362. prev.setHandleOut(curve[1].subtract(curve[0]));
  10363. segments.push(new Segment(curve[3], curve[2].subtract(curve[3])));
  10364. },
  10365. generateBezier: function(first, last, uPrime, tan1, tan2) {
  10366. var epsilon = 1e-12,
  10367. abs = Math.abs,
  10368. points = this.points,
  10369. pt1 = points[first],
  10370. pt2 = points[last],
  10371. C = [[0, 0], [0, 0]],
  10372. X = [0, 0];
  10373. for (var i = 0, l = last - first + 1; i < l; i++) {
  10374. var u = uPrime[i],
  10375. t = 1 - u,
  10376. b = 3 * u * t,
  10377. b0 = t * t * t,
  10378. b1 = b * t,
  10379. b2 = b * u,
  10380. b3 = u * u * u,
  10381. a1 = tan1.normalize(b1),
  10382. a2 = tan2.normalize(b2),
  10383. tmp = points[first + i]
  10384. .subtract(pt1.multiply(b0 + b1))
  10385. .subtract(pt2.multiply(b2 + b3));
  10386. C[0][0] += a1.dot(a1);
  10387. C[0][1] += a1.dot(a2);
  10388. C[1][0] = C[0][1];
  10389. C[1][1] += a2.dot(a2);
  10390. X[0] += a1.dot(tmp);
  10391. X[1] += a2.dot(tmp);
  10392. }
  10393. var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
  10394. alpha1,
  10395. alpha2;
  10396. if (abs(detC0C1) > epsilon) {
  10397. var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
  10398. detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
  10399. alpha1 = detXC1 / detC0C1;
  10400. alpha2 = detC0X / detC0C1;
  10401. } else {
  10402. var c0 = C[0][0] + C[0][1],
  10403. c1 = C[1][0] + C[1][1];
  10404. alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0
  10405. : abs(c1) > epsilon ? X[1] / c1
  10406. : 0;
  10407. }
  10408. var segLength = pt2.getDistance(pt1),
  10409. eps = epsilon * segLength,
  10410. handle1,
  10411. handle2;
  10412. if (alpha1 < eps || alpha2 < eps) {
  10413. alpha1 = alpha2 = segLength / 3;
  10414. } else {
  10415. var line = pt2.subtract(pt1);
  10416. handle1 = tan1.normalize(alpha1);
  10417. handle2 = tan2.normalize(alpha2);
  10418. if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) {
  10419. alpha1 = alpha2 = segLength / 3;
  10420. handle1 = handle2 = null;
  10421. }
  10422. }
  10423. return [pt1,
  10424. pt1.add(handle1 || tan1.normalize(alpha1)),
  10425. pt2.add(handle2 || tan2.normalize(alpha2)),
  10426. pt2];
  10427. },
  10428. reparameterize: function(first, last, u, curve) {
  10429. for (var i = first; i <= last; i++) {
  10430. u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
  10431. }
  10432. for (var i = 1, l = u.length; i < l; i++) {
  10433. if (u[i] <= u[i - 1])
  10434. return false;
  10435. }
  10436. return true;
  10437. },
  10438. findRoot: function(curve, point, u) {
  10439. var curve1 = [],
  10440. curve2 = [];
  10441. for (var i = 0; i <= 2; i++) {
  10442. curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
  10443. }
  10444. for (var i = 0; i <= 1; i++) {
  10445. curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
  10446. }
  10447. var pt = this.evaluate(3, curve, u),
  10448. pt1 = this.evaluate(2, curve1, u),
  10449. pt2 = this.evaluate(1, curve2, u),
  10450. diff = pt.subtract(point),
  10451. df = pt1.dot(pt1) + diff.dot(pt2);
  10452. return Numerical.isMachineZero(df) ? u : u - diff.dot(pt1) / df;
  10453. },
  10454. evaluate: function(degree, curve, t) {
  10455. var tmp = curve.slice();
  10456. for (var i = 1; i <= degree; i++) {
  10457. for (var j = 0; j <= degree - i; j++) {
  10458. tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
  10459. }
  10460. }
  10461. return tmp[0];
  10462. },
  10463. chordLengthParameterize: function(first, last) {
  10464. var u = [0];
  10465. for (var i = first + 1; i <= last; i++) {
  10466. u[i - first] = u[i - first - 1]
  10467. + this.points[i].getDistance(this.points[i - 1]);
  10468. }
  10469. for (var i = 1, m = last - first; i <= m; i++) {
  10470. u[i] /= u[m];
  10471. }
  10472. return u;
  10473. },
  10474. findMaxError: function(first, last, curve, u) {
  10475. var index = Math.floor((last - first + 1) / 2),
  10476. maxDist = 0;
  10477. for (var i = first + 1; i < last; i++) {
  10478. var P = this.evaluate(3, curve, u[i - first]);
  10479. var v = P.subtract(this.points[i]);
  10480. var dist = v.x * v.x + v.y * v.y;
  10481. if (dist >= maxDist) {
  10482. maxDist = dist;
  10483. index = i;
  10484. }
  10485. }
  10486. return {
  10487. error: maxDist,
  10488. index: index
  10489. };
  10490. }
  10491. });
  10492. var TextItem = Item.extend({
  10493. _class: 'TextItem',
  10494. _applyMatrix: false,
  10495. _canApplyMatrix: false,
  10496. _serializeFields: {
  10497. content: null
  10498. },
  10499. _boundsOptions: { stroke: false, handle: false },
  10500. initialize: function TextItem(arg) {
  10501. this._content = '';
  10502. this._lines = [];
  10503. var hasProps = arg && Base.isPlainObject(arg)
  10504. && arg.x === undefined && arg.y === undefined;
  10505. this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
  10506. },
  10507. _equals: function(item) {
  10508. return this._content === item._content;
  10509. },
  10510. copyContent: function(source) {
  10511. this.setContent(source._content);
  10512. },
  10513. getContent: function() {
  10514. return this._content;
  10515. },
  10516. setContent: function(content) {
  10517. this._content = '' + content;
  10518. this._lines = this._content.split(/\r\n|\n|\r/mg);
  10519. this._changed(521);
  10520. },
  10521. isEmpty: function() {
  10522. return !this._content;
  10523. },
  10524. getCharacterStyle: '#getStyle',
  10525. setCharacterStyle: '#setStyle',
  10526. getParagraphStyle: '#getStyle',
  10527. setParagraphStyle: '#setStyle'
  10528. });
  10529. var PointText = TextItem.extend({
  10530. _class: 'PointText',
  10531. initialize: function PointText() {
  10532. TextItem.apply(this, arguments);
  10533. },
  10534. getPoint: function() {
  10535. var point = this._matrix.getTranslation();
  10536. return new LinkedPoint(point.x, point.y, this, 'setPoint');
  10537. },
  10538. setPoint: function() {
  10539. var point = Point.read(arguments);
  10540. this.translate(point.subtract(this._matrix.getTranslation()));
  10541. },
  10542. _draw: function(ctx, param, viewMatrix) {
  10543. if (!this._content)
  10544. return;
  10545. this._setStyles(ctx, param, viewMatrix);
  10546. var lines = this._lines,
  10547. style = this._style,
  10548. hasFill = style.hasFill(),
  10549. hasStroke = style.hasStroke(),
  10550. leading = style.getLeading(),
  10551. shadowColor = ctx.shadowColor;
  10552. ctx.font = style.getFontStyle();
  10553. ctx.textAlign = style.getJustification();
  10554. for (var i = 0, l = lines.length; i < l; i++) {
  10555. ctx.shadowColor = shadowColor;
  10556. var line = lines[i];
  10557. if (hasFill) {
  10558. ctx.fillText(line, 0, 0);
  10559. ctx.shadowColor = 'rgba(0,0,0,0)';
  10560. }
  10561. if (hasStroke)
  10562. ctx.strokeText(line, 0, 0);
  10563. ctx.translate(0, leading);
  10564. }
  10565. },
  10566. _getBounds: function(matrix, options) {
  10567. var style = this._style,
  10568. lines = this._lines,
  10569. numLines = lines.length,
  10570. justification = style.getJustification(),
  10571. leading = style.getLeading(),
  10572. width = this.getView().getTextWidth(style.getFontStyle(), lines),
  10573. x = 0;
  10574. if (justification !== 'left')
  10575. x -= width / (justification === 'center' ? 2: 1);
  10576. var rect = new Rectangle(x,
  10577. numLines ? - 0.75 * leading : 0,
  10578. width, numLines * leading);
  10579. return matrix ? matrix._transformBounds(rect, rect) : rect;
  10580. }
  10581. });
  10582. var Color = Base.extend(new function() {
  10583. var types = {
  10584. gray: ['gray'],
  10585. rgb: ['red', 'green', 'blue'],
  10586. hsb: ['hue', 'saturation', 'brightness'],
  10587. hsl: ['hue', 'saturation', 'lightness'],
  10588. gradient: ['gradient', 'origin', 'destination', 'highlight']
  10589. };
  10590. var componentParsers = {},
  10591. namedColors = {
  10592. transparent: [0, 0, 0, 0]
  10593. },
  10594. colorCtx;
  10595. function fromCSS(string) {
  10596. var match = string.match(
  10597. /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i
  10598. ) || string.match(
  10599. /^#([\da-f])([\da-f])([\da-f])([\da-f])?$/i
  10600. ),
  10601. type = 'rgb',
  10602. components;
  10603. if (match) {
  10604. var amount = match[4] ? 4 : 3;
  10605. components = new Array(amount);
  10606. for (var i = 0; i < amount; i++) {
  10607. var value = match[i + 1];
  10608. components[i] = parseInt(value.length == 1
  10609. ? value + value : value, 16) / 255;
  10610. }
  10611. } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) {
  10612. type = match[1];
  10613. components = match[2].trim().split(/[,\s]+/g);
  10614. var isHSL = type === 'hsl';
  10615. for (var i = 0, l = Math.min(components.length, 4); i < l; i++) {
  10616. var component = components[i];
  10617. var value = parseFloat(component);
  10618. if (isHSL) {
  10619. if (i === 0) {
  10620. var unit = component.match(/([a-z]*)$/)[1];
  10621. value *= ({
  10622. turn: 360,
  10623. rad: 180 / Math.PI,
  10624. grad: 0.9
  10625. }[unit] || 1);
  10626. } else if (i < 3) {
  10627. value /= 100;
  10628. }
  10629. } else if (i < 3) {
  10630. value /= /%$/.test(component) ? 100 : 255;
  10631. }
  10632. components[i] = value;
  10633. }
  10634. } else {
  10635. var color = namedColors[string];
  10636. if (!color) {
  10637. if (window) {
  10638. if (!colorCtx) {
  10639. colorCtx = CanvasProvider.getContext(1, 1);
  10640. colorCtx.globalCompositeOperation = 'copy';
  10641. }
  10642. colorCtx.fillStyle = 'rgba(0,0,0,0)';
  10643. colorCtx.fillStyle = string;
  10644. colorCtx.fillRect(0, 0, 1, 1);
  10645. var data = colorCtx.getImageData(0, 0, 1, 1).data;
  10646. color = namedColors[string] = [
  10647. data[0] / 255,
  10648. data[1] / 255,
  10649. data[2] / 255
  10650. ];
  10651. } else {
  10652. color = [0, 0, 0];
  10653. }
  10654. }
  10655. components = color.slice();
  10656. }
  10657. return [type, components];
  10658. }
  10659. var hsbIndices = [
  10660. [0, 3, 1],
  10661. [2, 0, 1],
  10662. [1, 0, 3],
  10663. [1, 2, 0],
  10664. [3, 1, 0],
  10665. [0, 1, 2]
  10666. ];
  10667. var converters = {
  10668. 'rgb-hsb': function(r, g, b) {
  10669. var max = Math.max(r, g, b),
  10670. min = Math.min(r, g, b),
  10671. delta = max - min,
  10672. h = delta === 0 ? 0
  10673. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10674. : max == g ? (b - r) / delta + 2
  10675. : (r - g) / delta + 4) * 60;
  10676. return [h, max === 0 ? 0 : delta / max, max];
  10677. },
  10678. 'hsb-rgb': function(h, s, b) {
  10679. h = (((h / 60) % 6) + 6) % 6;
  10680. var i = Math.floor(h),
  10681. f = h - i,
  10682. i = hsbIndices[i],
  10683. v = [
  10684. b,
  10685. b * (1 - s),
  10686. b * (1 - s * f),
  10687. b * (1 - s * (1 - f))
  10688. ];
  10689. return [v[i[0]], v[i[1]], v[i[2]]];
  10690. },
  10691. 'rgb-hsl': function(r, g, b) {
  10692. var max = Math.max(r, g, b),
  10693. min = Math.min(r, g, b),
  10694. delta = max - min,
  10695. achromatic = delta === 0,
  10696. h = achromatic ? 0
  10697. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10698. : max == g ? (b - r) / delta + 2
  10699. : (r - g) / delta + 4) * 60,
  10700. l = (max + min) / 2,
  10701. s = achromatic ? 0 : l < 0.5
  10702. ? delta / (max + min)
  10703. : delta / (2 - max - min);
  10704. return [h, s, l];
  10705. },
  10706. 'hsl-rgb': function(h, s, l) {
  10707. h = (((h / 360) % 1) + 1) % 1;
  10708. if (s === 0)
  10709. return [l, l, l];
  10710. var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
  10711. t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
  10712. t1 = 2 * l - t2,
  10713. c = [];
  10714. for (var i = 0; i < 3; i++) {
  10715. var t3 = t3s[i];
  10716. if (t3 < 0) t3 += 1;
  10717. if (t3 > 1) t3 -= 1;
  10718. c[i] = 6 * t3 < 1
  10719. ? t1 + (t2 - t1) * 6 * t3
  10720. : 2 * t3 < 1
  10721. ? t2
  10722. : 3 * t3 < 2
  10723. ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
  10724. : t1;
  10725. }
  10726. return c;
  10727. },
  10728. 'rgb-gray': function(r, g, b) {
  10729. return [r * 0.2989 + g * 0.587 + b * 0.114];
  10730. },
  10731. 'gray-rgb': function(g) {
  10732. return [g, g, g];
  10733. },
  10734. 'gray-hsb': function(g) {
  10735. return [0, 0, g];
  10736. },
  10737. 'gray-hsl': function(g) {
  10738. return [0, 0, g];
  10739. },
  10740. 'gradient-rgb': function() {
  10741. return [];
  10742. },
  10743. 'rgb-gradient': function() {
  10744. return [];
  10745. }
  10746. };
  10747. return Base.each(types, function(properties, type) {
  10748. componentParsers[type] = [];
  10749. Base.each(properties, function(name, index) {
  10750. var part = Base.capitalize(name),
  10751. hasOverlap = /^(hue|saturation)$/.test(name),
  10752. parser = componentParsers[type][index] = type === 'gradient'
  10753. ? name === 'gradient'
  10754. ? function(value) {
  10755. var current = this._components[0];
  10756. value = Gradient.read(
  10757. Array.isArray(value)
  10758. ? value
  10759. : arguments, 0, { readNull: true }
  10760. );
  10761. if (current !== value) {
  10762. if (current)
  10763. current._removeOwner(this);
  10764. if (value)
  10765. value._addOwner(this);
  10766. }
  10767. return value;
  10768. }
  10769. : function() {
  10770. return Point.read(arguments, 0, {
  10771. readNull: name === 'highlight',
  10772. clone: true
  10773. });
  10774. }
  10775. : function(value) {
  10776. return value == null || isNaN(value) ? 0 : +value;
  10777. };
  10778. this['get' + part] = function() {
  10779. return this._type === type
  10780. || hasOverlap && /^hs[bl]$/.test(this._type)
  10781. ? this._components[index]
  10782. : this._convert(type)[index];
  10783. };
  10784. this['set' + part] = function(value) {
  10785. if (this._type !== type
  10786. && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
  10787. this._components = this._convert(type);
  10788. this._properties = types[type];
  10789. this._type = type;
  10790. }
  10791. this._components[index] = parser.call(this, value);
  10792. this._changed();
  10793. };
  10794. }, this);
  10795. }, {
  10796. _class: 'Color',
  10797. _readIndex: true,
  10798. initialize: function Color(arg) {
  10799. var args = arguments,
  10800. reading = this.__read,
  10801. read = 0,
  10802. type,
  10803. components,
  10804. alpha,
  10805. values;
  10806. if (Array.isArray(arg)) {
  10807. args = arg;
  10808. arg = args[0];
  10809. }
  10810. var argType = arg != null && typeof arg;
  10811. if (argType === 'string' && arg in types) {
  10812. type = arg;
  10813. arg = args[1];
  10814. if (Array.isArray(arg)) {
  10815. components = arg;
  10816. alpha = args[2];
  10817. } else {
  10818. if (reading)
  10819. read = 1;
  10820. args = Base.slice(args, 1);
  10821. argType = typeof arg;
  10822. }
  10823. }
  10824. if (!components) {
  10825. values = argType === 'number'
  10826. ? args
  10827. : argType === 'object' && arg.length != null
  10828. ? arg
  10829. : null;
  10830. if (values) {
  10831. if (!type)
  10832. type = values.length >= 3
  10833. ? 'rgb'
  10834. : 'gray';
  10835. var length = types[type].length;
  10836. alpha = values[length];
  10837. if (reading) {
  10838. read += values === arguments
  10839. ? length + (alpha != null ? 1 : 0)
  10840. : 1;
  10841. }
  10842. if (values.length > length)
  10843. values = Base.slice(values, 0, length);
  10844. } else if (argType === 'string') {
  10845. var converted = fromCSS(arg);
  10846. type = converted[0];
  10847. components = converted[1];
  10848. if (components.length === 4) {
  10849. alpha = components[3];
  10850. components.length--;
  10851. }
  10852. } else if (argType === 'object') {
  10853. if (arg.constructor === Color) {
  10854. type = arg._type;
  10855. components = arg._components.slice();
  10856. alpha = arg._alpha;
  10857. if (type === 'gradient') {
  10858. for (var i = 1, l = components.length; i < l; i++) {
  10859. var point = components[i];
  10860. if (point)
  10861. components[i] = point.clone();
  10862. }
  10863. }
  10864. } else if (arg.constructor === Gradient) {
  10865. type = 'gradient';
  10866. values = args;
  10867. } else {
  10868. type = 'hue' in arg
  10869. ? 'lightness' in arg
  10870. ? 'hsl'
  10871. : 'hsb'
  10872. : 'gradient' in arg || 'stops' in arg
  10873. || 'radial' in arg
  10874. ? 'gradient'
  10875. : 'gray' in arg
  10876. ? 'gray'
  10877. : 'rgb';
  10878. var properties = types[type],
  10879. parsers = componentParsers[type];
  10880. this._components = components = [];
  10881. for (var i = 0, l = properties.length; i < l; i++) {
  10882. var value = arg[properties[i]];
  10883. if (value == null && !i && type === 'gradient'
  10884. && 'stops' in arg) {
  10885. value = {
  10886. stops: arg.stops,
  10887. radial: arg.radial
  10888. };
  10889. }
  10890. value = parsers[i].call(this, value);
  10891. if (value != null)
  10892. components[i] = value;
  10893. }
  10894. alpha = arg.alpha;
  10895. }
  10896. }
  10897. if (reading && type)
  10898. read = 1;
  10899. }
  10900. this._type = type || 'rgb';
  10901. if (!components) {
  10902. this._components = components = [];
  10903. var parsers = componentParsers[this._type];
  10904. for (var i = 0, l = parsers.length; i < l; i++) {
  10905. var value = parsers[i].call(this, values && values[i]);
  10906. if (value != null)
  10907. components[i] = value;
  10908. }
  10909. }
  10910. this._components = components;
  10911. this._properties = types[this._type];
  10912. this._alpha = alpha;
  10913. if (reading)
  10914. this.__read = read;
  10915. return this;
  10916. },
  10917. set: '#initialize',
  10918. _serialize: function(options, dictionary) {
  10919. var components = this.getComponents();
  10920. return Base.serialize(
  10921. /^(gray|rgb)$/.test(this._type)
  10922. ? components
  10923. : [this._type].concat(components),
  10924. options, true, dictionary);
  10925. },
  10926. _changed: function() {
  10927. this._canvasStyle = null;
  10928. if (this._owner) {
  10929. if (this._setter) {
  10930. this._owner[this._setter](this);
  10931. } else {
  10932. this._owner._changed(129);
  10933. }
  10934. }
  10935. },
  10936. _convert: function(type) {
  10937. var converter;
  10938. return this._type === type
  10939. ? this._components.slice()
  10940. : (converter = converters[this._type + '-' + type])
  10941. ? converter.apply(this, this._components)
  10942. : converters['rgb-' + type].apply(this,
  10943. converters[this._type + '-rgb'].apply(this,
  10944. this._components));
  10945. },
  10946. convert: function(type) {
  10947. return new Color(type, this._convert(type), this._alpha);
  10948. },
  10949. getType: function() {
  10950. return this._type;
  10951. },
  10952. setType: function(type) {
  10953. this._components = this._convert(type);
  10954. this._properties = types[type];
  10955. this._type = type;
  10956. },
  10957. getComponents: function() {
  10958. var components = this._components.slice();
  10959. if (this._alpha != null)
  10960. components.push(this._alpha);
  10961. return components;
  10962. },
  10963. getAlpha: function() {
  10964. return this._alpha != null ? this._alpha : 1;
  10965. },
  10966. setAlpha: function(alpha) {
  10967. this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
  10968. this._changed();
  10969. },
  10970. hasAlpha: function() {
  10971. return this._alpha != null;
  10972. },
  10973. equals: function(color) {
  10974. var col = Base.isPlainValue(color, true)
  10975. ? Color.read(arguments)
  10976. : color;
  10977. return col === this || col && this._class === col._class
  10978. && this._type === col._type
  10979. && this.getAlpha() === col.getAlpha()
  10980. && Base.equals(this._components, col._components)
  10981. || false;
  10982. },
  10983. toString: function() {
  10984. var properties = this._properties,
  10985. parts = [],
  10986. isGradient = this._type === 'gradient',
  10987. f = Formatter.instance;
  10988. for (var i = 0, l = properties.length; i < l; i++) {
  10989. var value = this._components[i];
  10990. if (value != null)
  10991. parts.push(properties[i] + ': '
  10992. + (isGradient ? value : f.number(value)));
  10993. }
  10994. if (this._alpha != null)
  10995. parts.push('alpha: ' + f.number(this._alpha));
  10996. return '{ ' + parts.join(', ') + ' }';
  10997. },
  10998. toCSS: function(hex) {
  10999. var components = this._convert('rgb'),
  11000. alpha = hex || this._alpha == null ? 1 : this._alpha;
  11001. function convert(val) {
  11002. return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);
  11003. }
  11004. components = [
  11005. convert(components[0]),
  11006. convert(components[1]),
  11007. convert(components[2])
  11008. ];
  11009. if (alpha < 1)
  11010. components.push(alpha < 0 ? 0 : alpha);
  11011. return hex
  11012. ? '#' + ((1 << 24) + (components[0] << 16)
  11013. + (components[1] << 8)
  11014. + components[2]).toString(16).slice(1)
  11015. : (components.length == 4 ? 'rgba(' : 'rgb(')
  11016. + components.join(',') + ')';
  11017. },
  11018. toCanvasStyle: function(ctx, matrix) {
  11019. if (this._canvasStyle)
  11020. return this._canvasStyle;
  11021. if (this._type !== 'gradient')
  11022. return this._canvasStyle = this.toCSS();
  11023. var components = this._components,
  11024. gradient = components[0],
  11025. stops = gradient._stops,
  11026. origin = components[1],
  11027. destination = components[2],
  11028. highlight = components[3],
  11029. inverse = matrix && matrix.inverted(),
  11030. canvasGradient;
  11031. if (inverse) {
  11032. origin = inverse._transformPoint(origin);
  11033. destination = inverse._transformPoint(destination);
  11034. if (highlight)
  11035. highlight = inverse._transformPoint(highlight);
  11036. }
  11037. if (gradient._radial) {
  11038. var radius = destination.getDistance(origin);
  11039. if (highlight) {
  11040. var vector = highlight.subtract(origin);
  11041. if (vector.getLength() > radius)
  11042. highlight = origin.add(vector.normalize(radius - 0.1));
  11043. }
  11044. var start = highlight || origin;
  11045. canvasGradient = ctx.createRadialGradient(start.x, start.y,
  11046. 0, origin.x, origin.y, radius);
  11047. } else {
  11048. canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
  11049. destination.x, destination.y);
  11050. }
  11051. for (var i = 0, l = stops.length; i < l; i++) {
  11052. var stop = stops[i],
  11053. offset = stop._offset;
  11054. canvasGradient.addColorStop(
  11055. offset == null ? i / (l - 1) : offset,
  11056. stop._color.toCanvasStyle());
  11057. }
  11058. return this._canvasStyle = canvasGradient;
  11059. },
  11060. transform: function(matrix) {
  11061. if (this._type === 'gradient') {
  11062. var components = this._components;
  11063. for (var i = 1, l = components.length; i < l; i++) {
  11064. var point = components[i];
  11065. matrix._transformPoint(point, point, true);
  11066. }
  11067. this._changed();
  11068. }
  11069. },
  11070. statics: {
  11071. _types: types,
  11072. random: function() {
  11073. var random = Math.random;
  11074. return new Color(random(), random(), random());
  11075. },
  11076. _setOwner: function(color, owner, setter) {
  11077. if (color) {
  11078. if (color._owner && owner && color._owner !== owner) {
  11079. color = color.clone();
  11080. }
  11081. if (!color._owner ^ !owner) {
  11082. color._owner = owner || null;
  11083. color._setter = setter || null;
  11084. }
  11085. }
  11086. return color;
  11087. }
  11088. }
  11089. });
  11090. },
  11091. new function() {
  11092. var operators = {
  11093. add: function(a, b) {
  11094. return a + b;
  11095. },
  11096. subtract: function(a, b) {
  11097. return a - b;
  11098. },
  11099. multiply: function(a, b) {
  11100. return a * b;
  11101. },
  11102. divide: function(a, b) {
  11103. return a / b;
  11104. }
  11105. };
  11106. return Base.each(operators, function(operator, name) {
  11107. this[name] = function(color) {
  11108. color = Color.read(arguments);
  11109. var type = this._type,
  11110. components1 = this._components,
  11111. components2 = color._convert(type);
  11112. for (var i = 0, l = components1.length; i < l; i++)
  11113. components2[i] = operator(components1[i], components2[i]);
  11114. return new Color(type, components2,
  11115. this._alpha != null
  11116. ? operator(this._alpha, color.getAlpha())
  11117. : null);
  11118. };
  11119. }, {
  11120. });
  11121. });
  11122. var Gradient = Base.extend({
  11123. _class: 'Gradient',
  11124. initialize: function Gradient(stops, radial) {
  11125. this._id = UID.get();
  11126. if (stops && Base.isPlainObject(stops)) {
  11127. this.set(stops);
  11128. stops = radial = null;
  11129. }
  11130. if (this._stops == null) {
  11131. this.setStops(stops || ['white', 'black']);
  11132. }
  11133. if (this._radial == null) {
  11134. this.setRadial(typeof radial === 'string' && radial === 'radial'
  11135. || radial || false);
  11136. }
  11137. },
  11138. _serialize: function(options, dictionary) {
  11139. return dictionary.add(this, function() {
  11140. return Base.serialize([this._stops, this._radial],
  11141. options, true, dictionary);
  11142. });
  11143. },
  11144. _changed: function() {
  11145. for (var i = 0, l = this._owners && this._owners.length; i < l; i++) {
  11146. this._owners[i]._changed();
  11147. }
  11148. },
  11149. _addOwner: function(color) {
  11150. if (!this._owners)
  11151. this._owners = [];
  11152. this._owners.push(color);
  11153. },
  11154. _removeOwner: function(color) {
  11155. var index = this._owners ? this._owners.indexOf(color) : -1;
  11156. if (index != -1) {
  11157. this._owners.splice(index, 1);
  11158. if (!this._owners.length)
  11159. this._owners = undefined;
  11160. }
  11161. },
  11162. clone: function() {
  11163. var stops = [];
  11164. for (var i = 0, l = this._stops.length; i < l; i++) {
  11165. stops[i] = this._stops[i].clone();
  11166. }
  11167. return new Gradient(stops, this._radial);
  11168. },
  11169. getStops: function() {
  11170. return this._stops;
  11171. },
  11172. setStops: function(stops) {
  11173. if (stops.length < 2) {
  11174. throw new Error(
  11175. 'Gradient stop list needs to contain at least two stops.');
  11176. }
  11177. var _stops = this._stops;
  11178. if (_stops) {
  11179. for (var i = 0, l = _stops.length; i < l; i++)
  11180. _stops[i]._owner = undefined;
  11181. }
  11182. _stops = this._stops = GradientStop.readList(stops, 0, { clone: true });
  11183. for (var i = 0, l = _stops.length; i < l; i++)
  11184. _stops[i]._owner = this;
  11185. this._changed();
  11186. },
  11187. getRadial: function() {
  11188. return this._radial;
  11189. },
  11190. setRadial: function(radial) {
  11191. this._radial = radial;
  11192. this._changed();
  11193. },
  11194. equals: function(gradient) {
  11195. if (gradient === this)
  11196. return true;
  11197. if (gradient && this._class === gradient._class) {
  11198. var stops1 = this._stops,
  11199. stops2 = gradient._stops,
  11200. length = stops1.length;
  11201. if (length === stops2.length) {
  11202. for (var i = 0; i < length; i++) {
  11203. if (!stops1[i].equals(stops2[i]))
  11204. return false;
  11205. }
  11206. return true;
  11207. }
  11208. }
  11209. return false;
  11210. }
  11211. });
  11212. var GradientStop = Base.extend({
  11213. _class: 'GradientStop',
  11214. initialize: function GradientStop(arg0, arg1) {
  11215. var color = arg0,
  11216. offset = arg1;
  11217. if (typeof arg0 === 'object' && arg1 === undefined) {
  11218. if (Array.isArray(arg0) && typeof arg0[0] !== 'number') {
  11219. color = arg0[0];
  11220. offset = arg0[1];
  11221. } else if ('color' in arg0 || 'offset' in arg0
  11222. || 'rampPoint' in arg0) {
  11223. color = arg0.color;
  11224. offset = arg0.offset || arg0.rampPoint || 0;
  11225. }
  11226. }
  11227. this.setColor(color);
  11228. this.setOffset(offset);
  11229. },
  11230. clone: function() {
  11231. return new GradientStop(this._color.clone(), this._offset);
  11232. },
  11233. _serialize: function(options, dictionary) {
  11234. var color = this._color,
  11235. offset = this._offset;
  11236. return Base.serialize(offset == null ? [color] : [color, offset],
  11237. options, true, dictionary);
  11238. },
  11239. _changed: function() {
  11240. if (this._owner)
  11241. this._owner._changed(129);
  11242. },
  11243. getOffset: function() {
  11244. return this._offset;
  11245. },
  11246. setOffset: function(offset) {
  11247. this._offset = offset;
  11248. this._changed();
  11249. },
  11250. getRampPoint: '#getOffset',
  11251. setRampPoint: '#setOffset',
  11252. getColor: function() {
  11253. return this._color;
  11254. },
  11255. setColor: function() {
  11256. Color._setOwner(this._color, null);
  11257. this._color = Color._setOwner(Color.read(arguments, 0), this,
  11258. 'setColor');
  11259. this._changed();
  11260. },
  11261. equals: function(stop) {
  11262. return stop === this || stop && this._class === stop._class
  11263. && this._color.equals(stop._color)
  11264. && this._offset == stop._offset
  11265. || false;
  11266. }
  11267. });
  11268. var Style = Base.extend(new function() {
  11269. var itemDefaults = {
  11270. fillColor: null,
  11271. fillRule: 'nonzero',
  11272. strokeColor: null,
  11273. strokeWidth: 1,
  11274. strokeCap: 'butt',
  11275. strokeJoin: 'miter',
  11276. strokeScaling: true,
  11277. miterLimit: 10,
  11278. dashOffset: 0,
  11279. dashArray: [],
  11280. shadowColor: null,
  11281. shadowBlur: 0,
  11282. shadowOffset: new Point(),
  11283. selectedColor: null
  11284. },
  11285. groupDefaults = Base.set({}, itemDefaults, {
  11286. fontFamily: 'sans-serif',
  11287. fontWeight: 'normal',
  11288. fontSize: 12,
  11289. leading: null,
  11290. justification: 'left'
  11291. }),
  11292. textDefaults = Base.set({}, groupDefaults, {
  11293. fillColor: new Color()
  11294. }),
  11295. flags = {
  11296. strokeWidth: 193,
  11297. strokeCap: 193,
  11298. strokeJoin: 193,
  11299. strokeScaling: 201,
  11300. miterLimit: 193,
  11301. fontFamily: 9,
  11302. fontWeight: 9,
  11303. fontSize: 9,
  11304. font: 9,
  11305. leading: 9,
  11306. justification: 9
  11307. },
  11308. item = {
  11309. beans: true
  11310. },
  11311. fields = {
  11312. _class: 'Style',
  11313. beans: true,
  11314. initialize: function Style(style, _owner, _project) {
  11315. this._values = {};
  11316. this._owner = _owner;
  11317. this._project = _owner && _owner._project || _project
  11318. || paper.project;
  11319. this._defaults = !_owner || _owner instanceof Group ? groupDefaults
  11320. : _owner instanceof TextItem ? textDefaults
  11321. : itemDefaults;
  11322. if (style)
  11323. this.set(style);
  11324. }
  11325. };
  11326. Base.each(groupDefaults, function(value, key) {
  11327. var isColor = /Color$/.test(key),
  11328. isPoint = key === 'shadowOffset',
  11329. part = Base.capitalize(key),
  11330. flag = flags[key],
  11331. set = 'set' + part,
  11332. get = 'get' + part;
  11333. fields[set] = function(value) {
  11334. var owner = this._owner,
  11335. children = owner && owner._children,
  11336. applyToChildren = children && children.length > 0
  11337. && !(owner instanceof CompoundPath);
  11338. if (applyToChildren) {
  11339. for (var i = 0, l = children.length; i < l; i++)
  11340. children[i]._style[set](value);
  11341. }
  11342. if ((key === 'selectedColor' || !applyToChildren)
  11343. && key in this._defaults) {
  11344. var old = this._values[key];
  11345. if (old !== value) {
  11346. if (isColor) {
  11347. if (old) {
  11348. Color._setOwner(old, null);
  11349. old._canvasStyle = null;
  11350. }
  11351. if (value && value.constructor === Color) {
  11352. value = Color._setOwner(value, owner,
  11353. applyToChildren && set);
  11354. }
  11355. }
  11356. this._values[key] = value;
  11357. if (owner)
  11358. owner._changed(flag || 129);
  11359. }
  11360. }
  11361. };
  11362. fields[get] = function(_dontMerge) {
  11363. var owner = this._owner,
  11364. children = owner && owner._children,
  11365. applyToChildren = children && children.length > 0
  11366. && !(owner instanceof CompoundPath),
  11367. value;
  11368. if (applyToChildren && !_dontMerge) {
  11369. for (var i = 0, l = children.length; i < l; i++) {
  11370. var childValue = children[i]._style[get]();
  11371. if (!i) {
  11372. value = childValue;
  11373. } else if (!Base.equals(value, childValue)) {
  11374. return undefined;
  11375. }
  11376. }
  11377. } else if (key in this._defaults) {
  11378. var value = this._values[key];
  11379. if (value === undefined) {
  11380. value = this._defaults[key];
  11381. if (value && value.clone) {
  11382. value = value.clone();
  11383. }
  11384. } else {
  11385. var ctor = isColor ? Color : isPoint ? Point : null;
  11386. if (ctor && !(value && value.constructor === ctor)) {
  11387. this._values[key] = value = ctor.read([value], 0,
  11388. { readNull: true, clone: true });
  11389. }
  11390. }
  11391. }
  11392. if (value && isColor) {
  11393. value = Color._setOwner(value, owner, applyToChildren && set);
  11394. }
  11395. return value;
  11396. };
  11397. item[get] = function(_dontMerge) {
  11398. return this._style[get](_dontMerge);
  11399. };
  11400. item[set] = function(value) {
  11401. this._style[set](value);
  11402. };
  11403. });
  11404. Base.each({
  11405. Font: 'FontFamily',
  11406. WindingRule: 'FillRule'
  11407. }, function(value, key) {
  11408. var get = 'get' + key,
  11409. set = 'set' + key;
  11410. fields[get] = item[get] = '#get' + value;
  11411. fields[set] = item[set] = '#set' + value;
  11412. });
  11413. Item.inject(item);
  11414. return fields;
  11415. }, {
  11416. set: function(style) {
  11417. var isStyle = style instanceof Style,
  11418. values = isStyle ? style._values : style;
  11419. if (values) {
  11420. for (var key in values) {
  11421. if (key in this._defaults) {
  11422. var value = values[key];
  11423. this[key] = value && isStyle && value.clone
  11424. ? value.clone() : value;
  11425. }
  11426. }
  11427. }
  11428. },
  11429. equals: function(style) {
  11430. function compare(style1, style2, secondary) {
  11431. var values1 = style1._values,
  11432. values2 = style2._values,
  11433. defaults2 = style2._defaults;
  11434. for (var key in values1) {
  11435. var value1 = values1[key],
  11436. value2 = values2[key];
  11437. if (!(secondary && key in values2) && !Base.equals(value1,
  11438. value2 === undefined ? defaults2[key] : value2))
  11439. return false;
  11440. }
  11441. return true;
  11442. }
  11443. return style === this || style && this._class === style._class
  11444. && compare(this, style)
  11445. && compare(style, this, true)
  11446. || false;
  11447. },
  11448. _dispose: function() {
  11449. var color;
  11450. color = this.getFillColor();
  11451. if (color) color._canvasStyle = null;
  11452. color = this.getStrokeColor();
  11453. if (color) color._canvasStyle = null;
  11454. color = this.getShadowColor();
  11455. if (color) color._canvasStyle = null;
  11456. },
  11457. hasFill: function() {
  11458. var color = this.getFillColor();
  11459. return !!color && color.alpha > 0;
  11460. },
  11461. hasStroke: function() {
  11462. var color = this.getStrokeColor();
  11463. return !!color && color.alpha > 0 && this.getStrokeWidth() > 0;
  11464. },
  11465. hasShadow: function() {
  11466. var color = this.getShadowColor();
  11467. return !!color && color.alpha > 0 && (this.getShadowBlur() > 0
  11468. || !this.getShadowOffset().isZero());
  11469. },
  11470. getView: function() {
  11471. return this._project._view;
  11472. },
  11473. getFontStyle: function() {
  11474. var fontSize = this.getFontSize();
  11475. return this.getFontWeight()
  11476. + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')
  11477. + this.getFontFamily();
  11478. },
  11479. getFont: '#getFontFamily',
  11480. setFont: '#setFontFamily',
  11481. getLeading: function getLeading() {
  11482. var leading = getLeading.base.call(this),
  11483. fontSize = this.getFontSize();
  11484. if (/pt|em|%|px/.test(fontSize))
  11485. fontSize = this.getView().getPixelSize(fontSize);
  11486. return leading != null ? leading : fontSize * 1.2;
  11487. }
  11488. });
  11489. var DomElement = new function() {
  11490. function handlePrefix(el, name, set, value) {
  11491. var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'],
  11492. suffix = name[0].toUpperCase() + name.substring(1);
  11493. for (var i = 0; i < 6; i++) {
  11494. var prefix = prefixes[i],
  11495. key = prefix ? prefix + suffix : name;
  11496. if (key in el) {
  11497. if (set) {
  11498. el[key] = value;
  11499. } else {
  11500. return el[key];
  11501. }
  11502. break;
  11503. }
  11504. }
  11505. }
  11506. return {
  11507. getStyles: function(el) {
  11508. var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
  11509. view = doc && doc.defaultView;
  11510. return view && view.getComputedStyle(el, '');
  11511. },
  11512. getBounds: function(el, viewport) {
  11513. var doc = el.ownerDocument,
  11514. body = doc.body,
  11515. html = doc.documentElement,
  11516. rect;
  11517. try {
  11518. rect = el.getBoundingClientRect();
  11519. } catch (e) {
  11520. rect = { left: 0, top: 0, width: 0, height: 0 };
  11521. }
  11522. var x = rect.left - (html.clientLeft || body.clientLeft || 0),
  11523. y = rect.top - (html.clientTop || body.clientTop || 0);
  11524. if (!viewport) {
  11525. var view = doc.defaultView;
  11526. x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
  11527. y += view.pageYOffset || html.scrollTop || body.scrollTop;
  11528. }
  11529. return new Rectangle(x, y, rect.width, rect.height);
  11530. },
  11531. getViewportBounds: function(el) {
  11532. var doc = el.ownerDocument,
  11533. view = doc.defaultView,
  11534. html = doc.documentElement;
  11535. return new Rectangle(0, 0,
  11536. view.innerWidth || html.clientWidth,
  11537. view.innerHeight || html.clientHeight
  11538. );
  11539. },
  11540. getOffset: function(el, viewport) {
  11541. return DomElement.getBounds(el, viewport).getPoint();
  11542. },
  11543. getSize: function(el) {
  11544. return DomElement.getBounds(el, true).getSize();
  11545. },
  11546. isInvisible: function(el) {
  11547. return DomElement.getSize(el).equals(new Size(0, 0));
  11548. },
  11549. isInView: function(el) {
  11550. return !DomElement.isInvisible(el)
  11551. && DomElement.getViewportBounds(el).intersects(
  11552. DomElement.getBounds(el, true));
  11553. },
  11554. isInserted: function(el) {
  11555. return document.body.contains(el);
  11556. },
  11557. getPrefixed: function(el, name) {
  11558. return el && handlePrefix(el, name);
  11559. },
  11560. setPrefixed: function(el, name, value) {
  11561. if (typeof name === 'object') {
  11562. for (var key in name)
  11563. handlePrefix(el, key, true, name[key]);
  11564. } else {
  11565. handlePrefix(el, name, true, value);
  11566. }
  11567. }
  11568. };
  11569. };
  11570. var DomEvent = {
  11571. add: function(el, events) {
  11572. if (el) {
  11573. for (var type in events) {
  11574. var func = events[type],
  11575. parts = type.split(/[\s,]+/g);
  11576. for (var i = 0, l = parts.length; i < l; i++) {
  11577. var name = parts[i];
  11578. var options = (
  11579. el === document
  11580. && (name === 'touchstart' || name === 'touchmove')
  11581. ) ? { passive: false } : false;
  11582. el.addEventListener(name, func, options);
  11583. }
  11584. }
  11585. }
  11586. },
  11587. remove: function(el, events) {
  11588. if (el) {
  11589. for (var type in events) {
  11590. var func = events[type],
  11591. parts = type.split(/[\s,]+/g);
  11592. for (var i = 0, l = parts.length; i < l; i++)
  11593. el.removeEventListener(parts[i], func, false);
  11594. }
  11595. }
  11596. },
  11597. getPoint: function(event) {
  11598. var pos = event.targetTouches
  11599. ? event.targetTouches.length
  11600. ? event.targetTouches[0]
  11601. : event.changedTouches[0]
  11602. : event;
  11603. return new Point(
  11604. pos.pageX || pos.clientX + document.documentElement.scrollLeft,
  11605. pos.pageY || pos.clientY + document.documentElement.scrollTop
  11606. );
  11607. },
  11608. getTarget: function(event) {
  11609. return event.target || event.srcElement;
  11610. },
  11611. getRelatedTarget: function(event) {
  11612. return event.relatedTarget || event.toElement;
  11613. },
  11614. getOffset: function(event, target) {
  11615. return DomEvent.getPoint(event).subtract(DomElement.getOffset(
  11616. target || DomEvent.getTarget(event)));
  11617. }
  11618. };
  11619. DomEvent.requestAnimationFrame = new function() {
  11620. var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),
  11621. requested = false,
  11622. callbacks = [],
  11623. timer;
  11624. function handleCallbacks() {
  11625. var functions = callbacks;
  11626. callbacks = [];
  11627. for (var i = 0, l = functions.length; i < l; i++)
  11628. functions[i]();
  11629. requested = nativeRequest && callbacks.length;
  11630. if (requested)
  11631. nativeRequest(handleCallbacks);
  11632. }
  11633. return function(callback) {
  11634. callbacks.push(callback);
  11635. if (nativeRequest) {
  11636. if (!requested) {
  11637. nativeRequest(handleCallbacks);
  11638. requested = true;
  11639. }
  11640. } else if (!timer) {
  11641. timer = setInterval(handleCallbacks, 1000 / 60);
  11642. }
  11643. };
  11644. };
  11645. var View = Base.extend(Emitter, {
  11646. _class: 'View',
  11647. initialize: function View(project, element) {
  11648. function getSize(name) {
  11649. return element[name] || parseInt(element.getAttribute(name), 10);
  11650. }
  11651. function getCanvasSize() {
  11652. var size = DomElement.getSize(element);
  11653. return size.isNaN() || size.isZero()
  11654. ? new Size(getSize('width'), getSize('height'))
  11655. : size;
  11656. }
  11657. var size;
  11658. if (window && element) {
  11659. this._id = element.getAttribute('id');
  11660. if (this._id == null)
  11661. element.setAttribute('id', this._id = 'paper-view-' + View._id++);
  11662. DomEvent.add(element, this._viewEvents);
  11663. var none = 'none';
  11664. DomElement.setPrefixed(element.style, {
  11665. userDrag: none,
  11666. userSelect: none,
  11667. touchCallout: none,
  11668. contentZooming: none,
  11669. tapHighlightColor: 'rgba(0,0,0,0)'
  11670. });
  11671. if (PaperScope.hasAttribute(element, 'resize')) {
  11672. var that = this;
  11673. DomEvent.add(window, this._windowEvents = {
  11674. resize: function() {
  11675. that.setViewSize(getCanvasSize());
  11676. }
  11677. });
  11678. }
  11679. size = getCanvasSize();
  11680. if (PaperScope.hasAttribute(element, 'stats')
  11681. && typeof Stats !== 'undefined') {
  11682. this._stats = new Stats();
  11683. var stats = this._stats.domElement,
  11684. style = stats.style,
  11685. offset = DomElement.getOffset(element);
  11686. style.position = 'absolute';
  11687. style.left = offset.x + 'px';
  11688. style.top = offset.y + 'px';
  11689. document.body.appendChild(stats);
  11690. }
  11691. } else {
  11692. size = new Size(element);
  11693. element = null;
  11694. }
  11695. this._project = project;
  11696. this._scope = project._scope;
  11697. this._element = element;
  11698. if (!this._pixelRatio)
  11699. this._pixelRatio = window && window.devicePixelRatio || 1;
  11700. this._setElementSize(size.width, size.height);
  11701. this._viewSize = size;
  11702. View._views.push(this);
  11703. View._viewsById[this._id] = this;
  11704. (this._matrix = new Matrix())._owner = this;
  11705. if (!View._focused)
  11706. View._focused = this;
  11707. this._frameItems = {};
  11708. this._frameItemCount = 0;
  11709. this._itemEvents = { native: {}, virtual: {} };
  11710. this._autoUpdate = !paper.agent.node;
  11711. this._needsUpdate = false;
  11712. },
  11713. remove: function() {
  11714. if (!this._project)
  11715. return false;
  11716. if (View._focused === this)
  11717. View._focused = null;
  11718. View._views.splice(View._views.indexOf(this), 1);
  11719. delete View._viewsById[this._id];
  11720. var project = this._project;
  11721. if (project._view === this)
  11722. project._view = null;
  11723. DomEvent.remove(this._element, this._viewEvents);
  11724. DomEvent.remove(window, this._windowEvents);
  11725. this._element = this._project = null;
  11726. this.off('frame');
  11727. this._animate = false;
  11728. this._frameItems = {};
  11729. return true;
  11730. },
  11731. _events: Base.each(
  11732. Item._itemHandlers.concat(['onResize', 'onKeyDown', 'onKeyUp']),
  11733. function(name) {
  11734. this[name] = {};
  11735. }, {
  11736. onFrame: {
  11737. install: function() {
  11738. this.play();
  11739. },
  11740. uninstall: function() {
  11741. this.pause();
  11742. }
  11743. }
  11744. }
  11745. ),
  11746. _animate: false,
  11747. _time: 0,
  11748. _count: 0,
  11749. getAutoUpdate: function() {
  11750. return this._autoUpdate;
  11751. },
  11752. setAutoUpdate: function(autoUpdate) {
  11753. this._autoUpdate = autoUpdate;
  11754. if (autoUpdate)
  11755. this.requestUpdate();
  11756. },
  11757. update: function() {
  11758. },
  11759. draw: function() {
  11760. this.update();
  11761. },
  11762. requestUpdate: function() {
  11763. if (!this._requested) {
  11764. var that = this;
  11765. DomEvent.requestAnimationFrame(function() {
  11766. that._requested = false;
  11767. if (that._animate) {
  11768. that.requestUpdate();
  11769. var element = that._element;
  11770. if ((!DomElement.getPrefixed(document, 'hidden')
  11771. || PaperScope.getAttribute(element, 'keepalive')
  11772. === 'true') && DomElement.isInView(element)) {
  11773. that._handleFrame();
  11774. }
  11775. }
  11776. if (that._autoUpdate)
  11777. that.update();
  11778. });
  11779. this._requested = true;
  11780. }
  11781. },
  11782. play: function() {
  11783. this._animate = true;
  11784. this.requestUpdate();
  11785. },
  11786. pause: function() {
  11787. this._animate = false;
  11788. },
  11789. _handleFrame: function() {
  11790. paper = this._scope;
  11791. var now = Date.now() / 1000,
  11792. delta = this._last ? now - this._last : 0;
  11793. this._last = now;
  11794. this.emit('frame', new Base({
  11795. delta: delta,
  11796. time: this._time += delta,
  11797. count: this._count++
  11798. }));
  11799. if (this._stats)
  11800. this._stats.update();
  11801. },
  11802. _animateItem: function(item, animate) {
  11803. var items = this._frameItems;
  11804. if (animate) {
  11805. items[item._id] = {
  11806. item: item,
  11807. time: 0,
  11808. count: 0
  11809. };
  11810. if (++this._frameItemCount === 1)
  11811. this.on('frame', this._handleFrameItems);
  11812. } else {
  11813. delete items[item._id];
  11814. if (--this._frameItemCount === 0) {
  11815. this.off('frame', this._handleFrameItems);
  11816. }
  11817. }
  11818. },
  11819. _handleFrameItems: function(event) {
  11820. for (var i in this._frameItems) {
  11821. var entry = this._frameItems[i];
  11822. entry.item.emit('frame', new Base(event, {
  11823. time: entry.time += event.delta,
  11824. count: entry.count++
  11825. }));
  11826. }
  11827. },
  11828. _changed: function() {
  11829. this._project._changed(4097);
  11830. this._bounds = this._decomposed = undefined;
  11831. },
  11832. getElement: function() {
  11833. return this._element;
  11834. },
  11835. getPixelRatio: function() {
  11836. return this._pixelRatio;
  11837. },
  11838. getResolution: function() {
  11839. return this._pixelRatio * 72;
  11840. },
  11841. getViewSize: function() {
  11842. var size = this._viewSize;
  11843. return new LinkedSize(size.width, size.height, this, 'setViewSize');
  11844. },
  11845. setViewSize: function() {
  11846. var size = Size.read(arguments),
  11847. delta = size.subtract(this._viewSize);
  11848. if (delta.isZero())
  11849. return;
  11850. this._setElementSize(size.width, size.height);
  11851. this._viewSize.set(size);
  11852. this._changed();
  11853. this.emit('resize', { size: size, delta: delta });
  11854. if (this._autoUpdate) {
  11855. this.update();
  11856. }
  11857. },
  11858. _setElementSize: function(width, height) {
  11859. var element = this._element;
  11860. if (element) {
  11861. if (element.width !== width)
  11862. element.width = width;
  11863. if (element.height !== height)
  11864. element.height = height;
  11865. }
  11866. },
  11867. getBounds: function() {
  11868. if (!this._bounds)
  11869. this._bounds = this._matrix.inverted()._transformBounds(
  11870. new Rectangle(new Point(), this._viewSize));
  11871. return this._bounds;
  11872. },
  11873. getSize: function() {
  11874. return this.getBounds().getSize();
  11875. },
  11876. isVisible: function() {
  11877. return DomElement.isInView(this._element);
  11878. },
  11879. isInserted: function() {
  11880. return DomElement.isInserted(this._element);
  11881. },
  11882. getPixelSize: function(size) {
  11883. var element = this._element,
  11884. pixels;
  11885. if (element) {
  11886. var parent = element.parentNode,
  11887. temp = document.createElement('div');
  11888. temp.style.fontSize = size;
  11889. parent.appendChild(temp);
  11890. pixels = parseFloat(DomElement.getStyles(temp).fontSize);
  11891. parent.removeChild(temp);
  11892. } else {
  11893. pixels = parseFloat(pixels);
  11894. }
  11895. return pixels;
  11896. },
  11897. getTextWidth: function(font, lines) {
  11898. return 0;
  11899. }
  11900. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  11901. var rotate = key === 'rotate';
  11902. this[key] = function() {
  11903. var args = arguments,
  11904. value = (rotate ? Base : Point).read(args),
  11905. center = Point.read(args, 0, { readNull: true });
  11906. return this.transform(new Matrix()[key](value,
  11907. center || this.getCenter(true)));
  11908. };
  11909. }, {
  11910. _decompose: function() {
  11911. return this._decomposed || (this._decomposed = this._matrix.decompose());
  11912. },
  11913. translate: function() {
  11914. var mx = new Matrix();
  11915. return this.transform(mx.translate.apply(mx, arguments));
  11916. },
  11917. getCenter: function() {
  11918. return this.getBounds().getCenter();
  11919. },
  11920. setCenter: function() {
  11921. var center = Point.read(arguments);
  11922. this.translate(this.getCenter().subtract(center));
  11923. },
  11924. getZoom: function() {
  11925. var scaling = this._decompose().scaling;
  11926. return (scaling.x + scaling.y) / 2;
  11927. },
  11928. setZoom: function(zoom) {
  11929. this.transform(new Matrix().scale(zoom / this.getZoom(),
  11930. this.getCenter()));
  11931. },
  11932. getRotation: function() {
  11933. return this._decompose().rotation;
  11934. },
  11935. setRotation: function(rotation) {
  11936. var current = this.getRotation();
  11937. if (current != null && rotation != null) {
  11938. this.rotate(rotation - current);
  11939. }
  11940. },
  11941. getScaling: function() {
  11942. var scaling = this._decompose().scaling;
  11943. return new LinkedPoint(scaling.x, scaling.y, this, 'setScaling');
  11944. },
  11945. setScaling: function() {
  11946. var current = this.getScaling(),
  11947. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  11948. if (current && scaling) {
  11949. this.scale(scaling.x / current.x, scaling.y / current.y);
  11950. }
  11951. },
  11952. getMatrix: function() {
  11953. return this._matrix;
  11954. },
  11955. setMatrix: function() {
  11956. var matrix = this._matrix;
  11957. matrix.set.apply(matrix, arguments);
  11958. },
  11959. transform: function(matrix) {
  11960. this._matrix.append(matrix);
  11961. },
  11962. scrollBy: function() {
  11963. this.translate(Point.read(arguments).negate());
  11964. }
  11965. }), {
  11966. projectToView: function() {
  11967. return this._matrix._transformPoint(Point.read(arguments));
  11968. },
  11969. viewToProject: function() {
  11970. return this._matrix._inverseTransform(Point.read(arguments));
  11971. },
  11972. getEventPoint: function(event) {
  11973. return this.viewToProject(DomEvent.getOffset(event, this._element));
  11974. },
  11975. }, {
  11976. statics: {
  11977. _views: [],
  11978. _viewsById: {},
  11979. _id: 0,
  11980. create: function(project, element) {
  11981. if (document && typeof element === 'string')
  11982. element = document.getElementById(element);
  11983. var ctor = window ? CanvasView : View;
  11984. return new ctor(project, element);
  11985. }
  11986. }
  11987. },
  11988. new function() {
  11989. if (!window)
  11990. return;
  11991. var prevFocus,
  11992. tempFocus,
  11993. dragging = false,
  11994. mouseDown = false;
  11995. function getView(event) {
  11996. var target = DomEvent.getTarget(event);
  11997. return target.getAttribute && View._viewsById[
  11998. target.getAttribute('id')];
  11999. }
  12000. function updateFocus() {
  12001. var view = View._focused;
  12002. if (!view || !view.isVisible()) {
  12003. for (var i = 0, l = View._views.length; i < l; i++) {
  12004. if ((view = View._views[i]).isVisible()) {
  12005. View._focused = tempFocus = view;
  12006. break;
  12007. }
  12008. }
  12009. }
  12010. }
  12011. function handleMouseMove(view, event, point) {
  12012. view._handleMouseEvent('mousemove', event, point);
  12013. }
  12014. var navigator = window.navigator,
  12015. mousedown, mousemove, mouseup;
  12016. if (navigator.pointerEnabled || navigator.msPointerEnabled) {
  12017. mousedown = 'pointerdown MSPointerDown';
  12018. mousemove = 'pointermove MSPointerMove';
  12019. mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';
  12020. } else {
  12021. mousedown = 'touchstart';
  12022. mousemove = 'touchmove';
  12023. mouseup = 'touchend touchcancel';
  12024. if (!('ontouchstart' in window && navigator.userAgent.match(
  12025. /mobile|tablet|ip(ad|hone|od)|android|silk/i))) {
  12026. mousedown += ' mousedown';
  12027. mousemove += ' mousemove';
  12028. mouseup += ' mouseup';
  12029. }
  12030. }
  12031. var viewEvents = {},
  12032. docEvents = {
  12033. mouseout: function(event) {
  12034. var view = View._focused,
  12035. target = DomEvent.getRelatedTarget(event);
  12036. if (view && (!target || target.nodeName === 'HTML')) {
  12037. var offset = DomEvent.getOffset(event, view._element),
  12038. x = offset.x,
  12039. abs = Math.abs,
  12040. ax = abs(x),
  12041. max = 1 << 25,
  12042. diff = ax - max;
  12043. offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x;
  12044. handleMouseMove(view, event, view.viewToProject(offset));
  12045. }
  12046. },
  12047. scroll: updateFocus
  12048. };
  12049. viewEvents[mousedown] = function(event) {
  12050. var view = View._focused = getView(event);
  12051. if (!dragging) {
  12052. dragging = true;
  12053. view._handleMouseEvent('mousedown', event);
  12054. }
  12055. };
  12056. docEvents[mousemove] = function(event) {
  12057. var view = View._focused;
  12058. if (!mouseDown) {
  12059. var target = getView(event);
  12060. if (target) {
  12061. if (view !== target) {
  12062. if (view)
  12063. handleMouseMove(view, event);
  12064. if (!prevFocus)
  12065. prevFocus = view;
  12066. view = View._focused = tempFocus = target;
  12067. }
  12068. } else if (tempFocus && tempFocus === view) {
  12069. if (prevFocus && !prevFocus.isInserted())
  12070. prevFocus = null;
  12071. view = View._focused = prevFocus;
  12072. prevFocus = null;
  12073. updateFocus();
  12074. }
  12075. }
  12076. if (view)
  12077. handleMouseMove(view, event);
  12078. };
  12079. docEvents[mousedown] = function() {
  12080. mouseDown = true;
  12081. };
  12082. docEvents[mouseup] = function(event) {
  12083. var view = View._focused;
  12084. if (view && dragging)
  12085. view._handleMouseEvent('mouseup', event);
  12086. mouseDown = dragging = false;
  12087. };
  12088. DomEvent.add(document, docEvents);
  12089. DomEvent.add(window, {
  12090. load: updateFocus
  12091. });
  12092. var called = false,
  12093. prevented = false,
  12094. fallbacks = {
  12095. doubleclick: 'click',
  12096. mousedrag: 'mousemove'
  12097. },
  12098. wasInView = false,
  12099. overView,
  12100. downPoint,
  12101. lastPoint,
  12102. downItem,
  12103. overItem,
  12104. dragItem,
  12105. clickItem,
  12106. clickTime,
  12107. dblClick;
  12108. function emitMouseEvent(obj, target, type, event, point, prevPoint,
  12109. stopItem) {
  12110. var stopped = false,
  12111. mouseEvent;
  12112. function emit(obj, type) {
  12113. if (obj.responds(type)) {
  12114. if (!mouseEvent) {
  12115. mouseEvent = new MouseEvent(type, event, point,
  12116. target || obj,
  12117. prevPoint ? point.subtract(prevPoint) : null);
  12118. }
  12119. if (obj.emit(type, mouseEvent)) {
  12120. called = true;
  12121. if (mouseEvent.prevented)
  12122. prevented = true;
  12123. if (mouseEvent.stopped)
  12124. return stopped = true;
  12125. }
  12126. } else {
  12127. var fallback = fallbacks[type];
  12128. if (fallback)
  12129. return emit(obj, fallback);
  12130. }
  12131. }
  12132. while (obj && obj !== stopItem) {
  12133. if (emit(obj, type))
  12134. break;
  12135. obj = obj._parent;
  12136. }
  12137. return stopped;
  12138. }
  12139. function emitMouseEvents(view, hitItem, type, event, point, prevPoint) {
  12140. view._project.removeOn(type);
  12141. prevented = called = false;
  12142. return (dragItem && emitMouseEvent(dragItem, null, type, event,
  12143. point, prevPoint)
  12144. || hitItem && hitItem !== dragItem
  12145. && !hitItem.isDescendant(dragItem)
  12146. && emitMouseEvent(hitItem, null, type === 'mousedrag' ?
  12147. 'mousemove' : type, event, point, prevPoint, dragItem)
  12148. || emitMouseEvent(view, dragItem || hitItem || view, type, event,
  12149. point, prevPoint));
  12150. }
  12151. var itemEventsMap = {
  12152. mousedown: {
  12153. mousedown: 1,
  12154. mousedrag: 1,
  12155. click: 1,
  12156. doubleclick: 1
  12157. },
  12158. mouseup: {
  12159. mouseup: 1,
  12160. mousedrag: 1,
  12161. click: 1,
  12162. doubleclick: 1
  12163. },
  12164. mousemove: {
  12165. mousedrag: 1,
  12166. mousemove: 1,
  12167. mouseenter: 1,
  12168. mouseleave: 1
  12169. }
  12170. };
  12171. return {
  12172. _viewEvents: viewEvents,
  12173. _handleMouseEvent: function(type, event, point) {
  12174. var itemEvents = this._itemEvents,
  12175. hitItems = itemEvents.native[type],
  12176. nativeMove = type === 'mousemove',
  12177. tool = this._scope.tool,
  12178. view = this;
  12179. function responds(type) {
  12180. return itemEvents.virtual[type] || view.responds(type)
  12181. || tool && tool.responds(type);
  12182. }
  12183. if (nativeMove && dragging && responds('mousedrag'))
  12184. type = 'mousedrag';
  12185. if (!point)
  12186. point = this.getEventPoint(event);
  12187. var inView = this.getBounds().contains(point),
  12188. hit = hitItems && inView && view._project.hitTest(point, {
  12189. tolerance: 0,
  12190. fill: true,
  12191. stroke: true
  12192. }),
  12193. hitItem = hit && hit.item || null,
  12194. handle = false,
  12195. mouse = {};
  12196. mouse[type.substr(5)] = true;
  12197. if (hitItems && hitItem !== overItem) {
  12198. if (overItem) {
  12199. emitMouseEvent(overItem, null, 'mouseleave', event, point);
  12200. }
  12201. if (hitItem) {
  12202. emitMouseEvent(hitItem, null, 'mouseenter', event, point);
  12203. }
  12204. overItem = hitItem;
  12205. }
  12206. if (wasInView ^ inView) {
  12207. emitMouseEvent(this, null, inView ? 'mouseenter' : 'mouseleave',
  12208. event, point);
  12209. overView = inView ? this : null;
  12210. handle = true;
  12211. }
  12212. if ((inView || mouse.drag) && !point.equals(lastPoint)) {
  12213. emitMouseEvents(this, hitItem, nativeMove ? type : 'mousemove',
  12214. event, point, lastPoint);
  12215. handle = true;
  12216. }
  12217. wasInView = inView;
  12218. if (mouse.down && inView || mouse.up && downPoint) {
  12219. emitMouseEvents(this, hitItem, type, event, point, downPoint);
  12220. if (mouse.down) {
  12221. dblClick = hitItem === clickItem
  12222. && (Date.now() - clickTime < 300);
  12223. downItem = clickItem = hitItem;
  12224. if (!prevented && hitItem) {
  12225. var item = hitItem;
  12226. while (item && !item.responds('mousedrag'))
  12227. item = item._parent;
  12228. if (item)
  12229. dragItem = hitItem;
  12230. }
  12231. downPoint = point;
  12232. } else if (mouse.up) {
  12233. if (!prevented && hitItem === downItem) {
  12234. clickTime = Date.now();
  12235. emitMouseEvents(this, hitItem, dblClick ? 'doubleclick'
  12236. : 'click', event, point, downPoint);
  12237. dblClick = false;
  12238. }
  12239. downItem = dragItem = null;
  12240. }
  12241. wasInView = false;
  12242. handle = true;
  12243. }
  12244. lastPoint = point;
  12245. if (handle && tool) {
  12246. called = tool._handleMouseEvent(type, event, point, mouse)
  12247. || called;
  12248. }
  12249. if (
  12250. event.cancelable !== false
  12251. && (called && !mouse.move || mouse.down && responds('mouseup'))
  12252. ) {
  12253. event.preventDefault();
  12254. }
  12255. },
  12256. _handleKeyEvent: function(type, event, key, character) {
  12257. var scope = this._scope,
  12258. tool = scope.tool,
  12259. keyEvent;
  12260. function emit(obj) {
  12261. if (obj.responds(type)) {
  12262. paper = scope;
  12263. obj.emit(type, keyEvent = keyEvent
  12264. || new KeyEvent(type, event, key, character));
  12265. }
  12266. }
  12267. if (this.isVisible()) {
  12268. emit(this);
  12269. if (tool && tool.responds(type))
  12270. emit(tool);
  12271. }
  12272. },
  12273. _countItemEvent: function(type, sign) {
  12274. var itemEvents = this._itemEvents,
  12275. native = itemEvents.native,
  12276. virtual = itemEvents.virtual;
  12277. for (var key in itemEventsMap) {
  12278. native[key] = (native[key] || 0)
  12279. + (itemEventsMap[key][type] || 0) * sign;
  12280. }
  12281. virtual[type] = (virtual[type] || 0) + sign;
  12282. },
  12283. statics: {
  12284. updateFocus: updateFocus,
  12285. _resetState: function() {
  12286. dragging = mouseDown = called = wasInView = false;
  12287. prevFocus = tempFocus = overView = downPoint = lastPoint =
  12288. downItem = overItem = dragItem = clickItem = clickTime =
  12289. dblClick = null;
  12290. }
  12291. }
  12292. };
  12293. });
  12294. var CanvasView = View.extend({
  12295. _class: 'CanvasView',
  12296. initialize: function CanvasView(project, canvas) {
  12297. if (!(canvas instanceof window.HTMLCanvasElement)) {
  12298. var size = Size.read(arguments, 1);
  12299. if (size.isZero())
  12300. throw new Error(
  12301. 'Cannot create CanvasView with the provided argument: '
  12302. + Base.slice(arguments, 1));
  12303. canvas = CanvasProvider.getCanvas(size);
  12304. }
  12305. var ctx = this._context = canvas.getContext('2d');
  12306. ctx.save();
  12307. this._pixelRatio = 1;
  12308. if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) {
  12309. var deviceRatio = window.devicePixelRatio || 1,
  12310. backingStoreRatio = DomElement.getPrefixed(ctx,
  12311. 'backingStorePixelRatio') || 1;
  12312. this._pixelRatio = deviceRatio / backingStoreRatio;
  12313. }
  12314. View.call(this, project, canvas);
  12315. this._needsUpdate = true;
  12316. },
  12317. remove: function remove() {
  12318. this._context.restore();
  12319. return remove.base.call(this);
  12320. },
  12321. _setElementSize: function _setElementSize(width, height) {
  12322. var pixelRatio = this._pixelRatio;
  12323. _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio);
  12324. if (pixelRatio !== 1) {
  12325. var element = this._element,
  12326. ctx = this._context;
  12327. if (!PaperScope.hasAttribute(element, 'resize')) {
  12328. var style = element.style;
  12329. style.width = width + 'px';
  12330. style.height = height + 'px';
  12331. }
  12332. ctx.restore();
  12333. ctx.save();
  12334. ctx.scale(pixelRatio, pixelRatio);
  12335. }
  12336. },
  12337. getContext: function() {
  12338. return this._context;
  12339. },
  12340. getPixelSize: function getPixelSize(size) {
  12341. var agent = paper.agent,
  12342. pixels;
  12343. if (agent && agent.firefox) {
  12344. pixels = getPixelSize.base.call(this, size);
  12345. } else {
  12346. var ctx = this._context,
  12347. prevFont = ctx.font;
  12348. ctx.font = size + ' serif';
  12349. pixels = parseFloat(ctx.font);
  12350. ctx.font = prevFont;
  12351. }
  12352. return pixels;
  12353. },
  12354. getTextWidth: function(font, lines) {
  12355. var ctx = this._context,
  12356. prevFont = ctx.font,
  12357. width = 0;
  12358. ctx.font = font;
  12359. for (var i = 0, l = lines.length; i < l; i++)
  12360. width = Math.max(width, ctx.measureText(lines[i]).width);
  12361. ctx.font = prevFont;
  12362. return width;
  12363. },
  12364. update: function() {
  12365. if (!this._needsUpdate)
  12366. return false;
  12367. var project = this._project,
  12368. ctx = this._context,
  12369. size = this._viewSize;
  12370. ctx.clearRect(0, 0, size.width + 1, size.height + 1);
  12371. if (project)
  12372. project.draw(ctx, this._matrix, this._pixelRatio);
  12373. this._needsUpdate = false;
  12374. return true;
  12375. }
  12376. });
  12377. var Event = Base.extend({
  12378. _class: 'Event',
  12379. initialize: function Event(event) {
  12380. this.event = event;
  12381. this.type = event && event.type;
  12382. },
  12383. prevented: false,
  12384. stopped: false,
  12385. preventDefault: function() {
  12386. this.prevented = true;
  12387. this.event.preventDefault();
  12388. },
  12389. stopPropagation: function() {
  12390. this.stopped = true;
  12391. this.event.stopPropagation();
  12392. },
  12393. stop: function() {
  12394. this.stopPropagation();
  12395. this.preventDefault();
  12396. },
  12397. getTimeStamp: function() {
  12398. return this.event.timeStamp;
  12399. },
  12400. getModifiers: function() {
  12401. return Key.modifiers;
  12402. }
  12403. });
  12404. var KeyEvent = Event.extend({
  12405. _class: 'KeyEvent',
  12406. initialize: function KeyEvent(type, event, key, character) {
  12407. this.type = type;
  12408. this.event = event;
  12409. this.key = key;
  12410. this.character = character;
  12411. },
  12412. toString: function() {
  12413. return "{ type: '" + this.type
  12414. + "', key: '" + this.key
  12415. + "', character: '" + this.character
  12416. + "', modifiers: " + this.getModifiers()
  12417. + " }";
  12418. }
  12419. });
  12420. var Key = new function() {
  12421. var keyLookup = {
  12422. '\t': 'tab',
  12423. ' ': 'space',
  12424. '\b': 'backspace',
  12425. '\x7f': 'delete',
  12426. 'Spacebar': 'space',
  12427. 'Del': 'delete',
  12428. 'Win': 'meta',
  12429. 'Esc': 'escape'
  12430. },
  12431. charLookup = {
  12432. 'tab': '\t',
  12433. 'space': ' ',
  12434. 'enter': '\r'
  12435. },
  12436. keyMap = {},
  12437. charMap = {},
  12438. metaFixMap,
  12439. downKey,
  12440. modifiers = new Base({
  12441. shift: false,
  12442. control: false,
  12443. alt: false,
  12444. meta: false,
  12445. capsLock: false,
  12446. space: false
  12447. }).inject({
  12448. option: {
  12449. get: function() {
  12450. return this.alt;
  12451. }
  12452. },
  12453. command: {
  12454. get: function() {
  12455. var agent = paper && paper.agent;
  12456. return agent && agent.mac ? this.meta : this.control;
  12457. }
  12458. }
  12459. });
  12460. function getKey(event) {
  12461. var key = event.key || event.keyIdentifier;
  12462. key = /^U\+/.test(key)
  12463. ? String.fromCharCode(parseInt(key.substr(2), 16))
  12464. : /^Arrow[A-Z]/.test(key) ? key.substr(5)
  12465. : key === 'Unidentified' || key === undefined
  12466. ? String.fromCharCode(event.keyCode)
  12467. : key;
  12468. return keyLookup[key] ||
  12469. (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase());
  12470. }
  12471. function handleKey(down, key, character, event) {
  12472. var type = down ? 'keydown' : 'keyup',
  12473. view = View._focused,
  12474. name;
  12475. keyMap[key] = down;
  12476. if (down) {
  12477. charMap[key] = character;
  12478. } else {
  12479. delete charMap[key];
  12480. }
  12481. if (key.length > 1 && (name = Base.camelize(key)) in modifiers) {
  12482. modifiers[name] = down;
  12483. var agent = paper && paper.agent;
  12484. if (name === 'meta' && agent && agent.mac) {
  12485. if (down) {
  12486. metaFixMap = {};
  12487. } else {
  12488. for (var k in metaFixMap) {
  12489. if (k in charMap)
  12490. handleKey(false, k, metaFixMap[k], event);
  12491. }
  12492. metaFixMap = null;
  12493. }
  12494. }
  12495. } else if (down && metaFixMap) {
  12496. metaFixMap[key] = character;
  12497. }
  12498. if (view) {
  12499. view._handleKeyEvent(down ? 'keydown' : 'keyup', event, key,
  12500. character);
  12501. }
  12502. }
  12503. DomEvent.add(document, {
  12504. keydown: function(event) {
  12505. var key = getKey(event),
  12506. agent = paper && paper.agent;
  12507. if (key.length > 1 || agent && (agent.chrome && (event.altKey
  12508. || agent.mac && event.metaKey
  12509. || !agent.mac && event.ctrlKey))) {
  12510. handleKey(true, key,
  12511. charLookup[key] || (key.length > 1 ? '' : key), event);
  12512. } else {
  12513. downKey = key;
  12514. }
  12515. },
  12516. keypress: function(event) {
  12517. if (downKey) {
  12518. var key = getKey(event),
  12519. code = event.charCode,
  12520. character = code >= 32 ? String.fromCharCode(code)
  12521. : key.length > 1 ? '' : key;
  12522. if (key !== downKey) {
  12523. key = character.toLowerCase();
  12524. }
  12525. handleKey(true, key, character, event);
  12526. downKey = null;
  12527. }
  12528. },
  12529. keyup: function(event) {
  12530. var key = getKey(event);
  12531. if (key in charMap)
  12532. handleKey(false, key, charMap[key], event);
  12533. }
  12534. });
  12535. DomEvent.add(window, {
  12536. blur: function(event) {
  12537. for (var key in charMap)
  12538. handleKey(false, key, charMap[key], event);
  12539. }
  12540. });
  12541. return {
  12542. modifiers: modifiers,
  12543. isDown: function(key) {
  12544. return !!keyMap[key];
  12545. }
  12546. };
  12547. };
  12548. var MouseEvent = Event.extend({
  12549. _class: 'MouseEvent',
  12550. initialize: function MouseEvent(type, event, point, target, delta) {
  12551. this.type = type;
  12552. this.event = event;
  12553. this.point = point;
  12554. this.target = target;
  12555. this.delta = delta;
  12556. },
  12557. toString: function() {
  12558. return "{ type: '" + this.type
  12559. + "', point: " + this.point
  12560. + ', target: ' + this.target
  12561. + (this.delta ? ', delta: ' + this.delta : '')
  12562. + ', modifiers: ' + this.getModifiers()
  12563. + ' }';
  12564. }
  12565. });
  12566. var ToolEvent = Event.extend({
  12567. _class: 'ToolEvent',
  12568. _item: null,
  12569. initialize: function ToolEvent(tool, type, event) {
  12570. this.tool = tool;
  12571. this.type = type;
  12572. this.event = event;
  12573. },
  12574. _choosePoint: function(point, toolPoint) {
  12575. return point ? point : toolPoint ? toolPoint.clone() : null;
  12576. },
  12577. getPoint: function() {
  12578. return this._choosePoint(this._point, this.tool._point);
  12579. },
  12580. setPoint: function(point) {
  12581. this._point = point;
  12582. },
  12583. getLastPoint: function() {
  12584. return this._choosePoint(this._lastPoint, this.tool._lastPoint);
  12585. },
  12586. setLastPoint: function(lastPoint) {
  12587. this._lastPoint = lastPoint;
  12588. },
  12589. getDownPoint: function() {
  12590. return this._choosePoint(this._downPoint, this.tool._downPoint);
  12591. },
  12592. setDownPoint: function(downPoint) {
  12593. this._downPoint = downPoint;
  12594. },
  12595. getMiddlePoint: function() {
  12596. if (!this._middlePoint && this.tool._lastPoint) {
  12597. return this.tool._point.add(this.tool._lastPoint).divide(2);
  12598. }
  12599. return this._middlePoint;
  12600. },
  12601. setMiddlePoint: function(middlePoint) {
  12602. this._middlePoint = middlePoint;
  12603. },
  12604. getDelta: function() {
  12605. return !this._delta && this.tool._lastPoint
  12606. ? this.tool._point.subtract(this.tool._lastPoint)
  12607. : this._delta;
  12608. },
  12609. setDelta: function(delta) {
  12610. this._delta = delta;
  12611. },
  12612. getCount: function() {
  12613. return this.tool[/^mouse(down|up)$/.test(this.type)
  12614. ? '_downCount' : '_moveCount'];
  12615. },
  12616. setCount: function(count) {
  12617. this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
  12618. = count;
  12619. },
  12620. getItem: function() {
  12621. if (!this._item) {
  12622. var result = this.tool._scope.project.hitTest(this.getPoint());
  12623. if (result) {
  12624. var item = result.item,
  12625. parent = item._parent;
  12626. while (/^(Group|CompoundPath)$/.test(parent._class)) {
  12627. item = parent;
  12628. parent = parent._parent;
  12629. }
  12630. this._item = item;
  12631. }
  12632. }
  12633. return this._item;
  12634. },
  12635. setItem: function(item) {
  12636. this._item = item;
  12637. },
  12638. toString: function() {
  12639. return '{ type: ' + this.type
  12640. + ', point: ' + this.getPoint()
  12641. + ', count: ' + this.getCount()
  12642. + ', modifiers: ' + this.getModifiers()
  12643. + ' }';
  12644. }
  12645. });
  12646. var Tool = PaperScopeItem.extend({
  12647. _class: 'Tool',
  12648. _list: 'tools',
  12649. _reference: 'tool',
  12650. _events: ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
  12651. 'onActivate', 'onDeactivate', 'onEditOptions', 'onKeyDown',
  12652. 'onKeyUp'],
  12653. initialize: function Tool(props) {
  12654. PaperScopeItem.call(this);
  12655. this._moveCount = -1;
  12656. this._downCount = -1;
  12657. this.set(props);
  12658. },
  12659. getMinDistance: function() {
  12660. return this._minDistance;
  12661. },
  12662. setMinDistance: function(minDistance) {
  12663. this._minDistance = minDistance;
  12664. if (minDistance != null && this._maxDistance != null
  12665. && minDistance > this._maxDistance) {
  12666. this._maxDistance = minDistance;
  12667. }
  12668. },
  12669. getMaxDistance: function() {
  12670. return this._maxDistance;
  12671. },
  12672. setMaxDistance: function(maxDistance) {
  12673. this._maxDistance = maxDistance;
  12674. if (this._minDistance != null && maxDistance != null
  12675. && maxDistance < this._minDistance) {
  12676. this._minDistance = maxDistance;
  12677. }
  12678. },
  12679. getFixedDistance: function() {
  12680. return this._minDistance == this._maxDistance
  12681. ? this._minDistance : null;
  12682. },
  12683. setFixedDistance: function(distance) {
  12684. this._minDistance = this._maxDistance = distance;
  12685. },
  12686. _handleMouseEvent: function(type, event, point, mouse) {
  12687. paper = this._scope;
  12688. if (mouse.drag && !this.responds(type))
  12689. type = 'mousemove';
  12690. var move = mouse.move || mouse.drag,
  12691. responds = this.responds(type),
  12692. minDistance = this.minDistance,
  12693. maxDistance = this.maxDistance,
  12694. called = false,
  12695. tool = this;
  12696. function update(minDistance, maxDistance) {
  12697. var pt = point,
  12698. toolPoint = move ? tool._point : (tool._downPoint || pt);
  12699. if (move) {
  12700. if (tool._moveCount >= 0 && pt.equals(toolPoint)) {
  12701. return false;
  12702. }
  12703. if (toolPoint && (minDistance != null || maxDistance != null)) {
  12704. var vector = pt.subtract(toolPoint),
  12705. distance = vector.getLength();
  12706. if (distance < (minDistance || 0))
  12707. return false;
  12708. if (maxDistance) {
  12709. pt = toolPoint.add(vector.normalize(
  12710. Math.min(distance, maxDistance)));
  12711. }
  12712. }
  12713. tool._moveCount++;
  12714. }
  12715. tool._point = pt;
  12716. tool._lastPoint = toolPoint || pt;
  12717. if (mouse.down) {
  12718. tool._moveCount = -1;
  12719. tool._downPoint = pt;
  12720. tool._downCount++;
  12721. }
  12722. return true;
  12723. }
  12724. function emit() {
  12725. if (responds) {
  12726. called = tool.emit(type, new ToolEvent(tool, type, event))
  12727. || called;
  12728. }
  12729. }
  12730. if (mouse.down) {
  12731. update();
  12732. emit();
  12733. } else if (mouse.up) {
  12734. update(null, maxDistance);
  12735. emit();
  12736. } else if (responds) {
  12737. while (update(minDistance, maxDistance))
  12738. emit();
  12739. }
  12740. return called;
  12741. }
  12742. });
  12743. var Tween = Base.extend(Emitter, {
  12744. _class: 'Tween',
  12745. statics: {
  12746. easings: new Base({
  12747. linear: function(t) {
  12748. return t;
  12749. },
  12750. easeInQuad: function(t) {
  12751. return t * t;
  12752. },
  12753. easeOutQuad: function(t) {
  12754. return t * (2 - t);
  12755. },
  12756. easeInOutQuad: function(t) {
  12757. return t < 0.5
  12758. ? 2 * t * t
  12759. : -1 + 2 * (2 - t) * t;
  12760. },
  12761. easeInCubic: function(t) {
  12762. return t * t * t;
  12763. },
  12764. easeOutCubic: function(t) {
  12765. return --t * t * t + 1;
  12766. },
  12767. easeInOutCubic: function(t) {
  12768. return t < 0.5
  12769. ? 4 * t * t * t
  12770. : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  12771. },
  12772. easeInQuart: function(t) {
  12773. return t * t * t * t;
  12774. },
  12775. easeOutQuart: function(t) {
  12776. return 1 - (--t) * t * t * t;
  12777. },
  12778. easeInOutQuart: function(t) {
  12779. return t < 0.5
  12780. ? 8 * t * t * t * t
  12781. : 1 - 8 * (--t) * t * t * t;
  12782. },
  12783. easeInQuint: function(t) {
  12784. return t * t * t * t * t;
  12785. },
  12786. easeOutQuint: function(t) {
  12787. return 1 + --t * t * t * t * t;
  12788. },
  12789. easeInOutQuint: function(t) {
  12790. return t < 0.5
  12791. ? 16 * t * t * t * t * t
  12792. : 1 + 16 * (--t) * t * t * t * t;
  12793. }
  12794. })
  12795. },
  12796. initialize: function Tween(object, from, to, duration, easing, start) {
  12797. this.object = object;
  12798. var type = typeof easing;
  12799. var isFunction = type === 'function';
  12800. this.type = isFunction
  12801. ? type
  12802. : type === 'string'
  12803. ? easing
  12804. : 'linear';
  12805. this.easing = isFunction ? easing : Tween.easings[this.type];
  12806. this.duration = duration;
  12807. this.running = false;
  12808. this._then = null;
  12809. this._startTime = null;
  12810. var state = from || to;
  12811. this._keys = state ? Object.keys(state) : [];
  12812. this._parsedKeys = this._parseKeys(this._keys);
  12813. this._from = state && this._getState(from);
  12814. this._to = state && this._getState(to);
  12815. if (start !== false) {
  12816. this.start();
  12817. }
  12818. },
  12819. then: function(then) {
  12820. this._then = then;
  12821. return this;
  12822. },
  12823. start: function() {
  12824. this._startTime = null;
  12825. this.running = true;
  12826. return this;
  12827. },
  12828. stop: function() {
  12829. this.running = false;
  12830. return this;
  12831. },
  12832. update: function(progress) {
  12833. if (this.running) {
  12834. if (progress >= 1) {
  12835. progress = 1;
  12836. this.running = false;
  12837. }
  12838. var factor = this.easing(progress),
  12839. keys = this._keys,
  12840. getValue = function(value) {
  12841. return typeof value === 'function'
  12842. ? value(factor, progress)
  12843. : value;
  12844. };
  12845. for (var i = 0, l = keys && keys.length; i < l; i++) {
  12846. var key = keys[i],
  12847. from = getValue(this._from[key]),
  12848. to = getValue(this._to[key]),
  12849. value = (from && to && from.__add && to.__add)
  12850. ? to.__subtract(from).__multiply(factor).__add(from)
  12851. : ((to - from) * factor) + from;
  12852. this._setProperty(this._parsedKeys[key], value);
  12853. }
  12854. if (this.responds('update')) {
  12855. this.emit('update', new Base({
  12856. progress: progress,
  12857. factor: factor
  12858. }));
  12859. }
  12860. if (!this.running && this._then) {
  12861. this._then(this.object);
  12862. }
  12863. }
  12864. return this;
  12865. },
  12866. _events: {
  12867. onUpdate: {}
  12868. },
  12869. _handleFrame: function(time) {
  12870. var startTime = this._startTime,
  12871. progress = startTime
  12872. ? (time - startTime) / this.duration
  12873. : 0;
  12874. if (!startTime) {
  12875. this._startTime = time;
  12876. }
  12877. this.update(progress);
  12878. },
  12879. _getState: function(state) {
  12880. var keys = this._keys,
  12881. result = {};
  12882. for (var i = 0, l = keys.length; i < l; i++) {
  12883. var key = keys[i],
  12884. path = this._parsedKeys[key],
  12885. current = this._getProperty(path),
  12886. value;
  12887. if (state) {
  12888. var resolved = this._resolveValue(current, state[key]);
  12889. this._setProperty(path, resolved);
  12890. value = this._getProperty(path);
  12891. value = value && value.clone ? value.clone() : value;
  12892. this._setProperty(path, current);
  12893. } else {
  12894. value = current && current.clone ? current.clone() : current;
  12895. }
  12896. result[key] = value;
  12897. }
  12898. return result;
  12899. },
  12900. _resolveValue: function(current, value) {
  12901. if (value) {
  12902. if (Array.isArray(value) && value.length === 2) {
  12903. var operator = value[0];
  12904. return (
  12905. operator &&
  12906. operator.match &&
  12907. operator.match(/^[+\-\*\/]=/)
  12908. )
  12909. ? this._calculate(current, operator[0], value[1])
  12910. : value;
  12911. } else if (typeof value === 'string') {
  12912. var match = value.match(/^[+\-*/]=(.*)/);
  12913. if (match) {
  12914. var parsed = JSON.parse(match[1].replace(
  12915. /(['"])?([a-zA-Z0-9_]+)(['"])?:/g,
  12916. '"$2": '
  12917. ));
  12918. return this._calculate(current, value[0], parsed);
  12919. }
  12920. }
  12921. }
  12922. return value;
  12923. },
  12924. _calculate: function(left, operator, right) {
  12925. return paper.PaperScript.calculateBinary(left, operator, right);
  12926. },
  12927. _parseKeys: function(keys) {
  12928. var parsed = {};
  12929. for (var i = 0, l = keys.length; i < l; i++) {
  12930. var key = keys[i],
  12931. path = key
  12932. .replace(/\.([^.]*)/g, '/$1')
  12933. .replace(/\[['"]?([^'"\]]*)['"]?\]/g, '/$1');
  12934. parsed[key] = path.split('/');
  12935. }
  12936. return parsed;
  12937. },
  12938. _getProperty: function(path, offset) {
  12939. var obj = this.object;
  12940. for (var i = 0, l = path.length - (offset || 0); i < l && obj; i++) {
  12941. obj = obj[path[i]];
  12942. }
  12943. return obj;
  12944. },
  12945. _setProperty: function(path, value) {
  12946. var dest = this._getProperty(path, 1);
  12947. if (dest) {
  12948. dest[path[path.length - 1]] = value;
  12949. }
  12950. }
  12951. });
  12952. var Http = {
  12953. request: function(options) {
  12954. var xhr = new self.XMLHttpRequest();
  12955. xhr.open((options.method || 'get').toUpperCase(), options.url,
  12956. Base.pick(options.async, true));
  12957. if (options.mimeType)
  12958. xhr.overrideMimeType(options.mimeType);
  12959. xhr.onload = function() {
  12960. var status = xhr.status;
  12961. if (status === 0 || status === 200) {
  12962. if (options.onLoad) {
  12963. options.onLoad.call(xhr, xhr.responseText);
  12964. }
  12965. } else {
  12966. xhr.onerror();
  12967. }
  12968. };
  12969. xhr.onerror = function() {
  12970. var status = xhr.status,
  12971. message = 'Could not load "' + options.url + '" (Status: '
  12972. + status + ')';
  12973. if (options.onError) {
  12974. options.onError(message, status);
  12975. } else {
  12976. throw new Error(message);
  12977. }
  12978. };
  12979. return xhr.send(null);
  12980. }
  12981. };
  12982. var CanvasProvider = Base.exports.CanvasProvider = {
  12983. canvases: [],
  12984. getCanvas: function(width, height) {
  12985. if (!window)
  12986. return null;
  12987. var canvas,
  12988. clear = true;
  12989. if (typeof width === 'object') {
  12990. height = width.height;
  12991. width = width.width;
  12992. }
  12993. if (this.canvases.length) {
  12994. canvas = this.canvases.pop();
  12995. } else {
  12996. canvas = document.createElement('canvas');
  12997. clear = false;
  12998. }
  12999. var ctx = canvas.getContext('2d');
  13000. if (!ctx) {
  13001. throw new Error('Canvas ' + canvas +
  13002. ' is unable to provide a 2D context.');
  13003. }
  13004. if (canvas.width === width && canvas.height === height) {
  13005. if (clear)
  13006. ctx.clearRect(0, 0, width + 1, height + 1);
  13007. } else {
  13008. canvas.width = width;
  13009. canvas.height = height;
  13010. }
  13011. ctx.save();
  13012. return canvas;
  13013. },
  13014. getContext: function(width, height) {
  13015. var canvas = this.getCanvas(width, height);
  13016. return canvas ? canvas.getContext('2d') : null;
  13017. },
  13018. release: function(obj) {
  13019. var canvas = obj && obj.canvas ? obj.canvas : obj;
  13020. if (canvas && canvas.getContext) {
  13021. canvas.getContext('2d').restore();
  13022. this.canvases.push(canvas);
  13023. }
  13024. }
  13025. };
  13026. var BlendMode = new function() {
  13027. var min = Math.min,
  13028. max = Math.max,
  13029. abs = Math.abs,
  13030. sr, sg, sb, sa,
  13031. br, bg, bb, ba,
  13032. dr, dg, db;
  13033. function getLum(r, g, b) {
  13034. return 0.2989 * r + 0.587 * g + 0.114 * b;
  13035. }
  13036. function setLum(r, g, b, l) {
  13037. var d = l - getLum(r, g, b);
  13038. dr = r + d;
  13039. dg = g + d;
  13040. db = b + d;
  13041. var l = getLum(dr, dg, db),
  13042. mn = min(dr, dg, db),
  13043. mx = max(dr, dg, db);
  13044. if (mn < 0) {
  13045. var lmn = l - mn;
  13046. dr = l + (dr - l) * l / lmn;
  13047. dg = l + (dg - l) * l / lmn;
  13048. db = l + (db - l) * l / lmn;
  13049. }
  13050. if (mx > 255) {
  13051. var ln = 255 - l,
  13052. mxl = mx - l;
  13053. dr = l + (dr - l) * ln / mxl;
  13054. dg = l + (dg - l) * ln / mxl;
  13055. db = l + (db - l) * ln / mxl;
  13056. }
  13057. }
  13058. function getSat(r, g, b) {
  13059. return max(r, g, b) - min(r, g, b);
  13060. }
  13061. function setSat(r, g, b, s) {
  13062. var col = [r, g, b],
  13063. mx = max(r, g, b),
  13064. mn = min(r, g, b),
  13065. md;
  13066. mn = mn === r ? 0 : mn === g ? 1 : 2;
  13067. mx = mx === r ? 0 : mx === g ? 1 : 2;
  13068. md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
  13069. if (col[mx] > col[mn]) {
  13070. col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
  13071. col[mx] = s;
  13072. } else {
  13073. col[md] = col[mx] = 0;
  13074. }
  13075. col[mn] = 0;
  13076. dr = col[0];
  13077. dg = col[1];
  13078. db = col[2];
  13079. }
  13080. var modes = {
  13081. multiply: function() {
  13082. dr = br * sr / 255;
  13083. dg = bg * sg / 255;
  13084. db = bb * sb / 255;
  13085. },
  13086. screen: function() {
  13087. dr = br + sr - (br * sr / 255);
  13088. dg = bg + sg - (bg * sg / 255);
  13089. db = bb + sb - (bb * sb / 255);
  13090. },
  13091. overlay: function() {
  13092. dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
  13093. dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
  13094. db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
  13095. },
  13096. 'soft-light': function() {
  13097. var t = sr * br / 255;
  13098. dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
  13099. t = sg * bg / 255;
  13100. dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
  13101. t = sb * bb / 255;
  13102. db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
  13103. },
  13104. 'hard-light': function() {
  13105. dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
  13106. dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
  13107. db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
  13108. },
  13109. 'color-dodge': function() {
  13110. dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
  13111. dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
  13112. db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
  13113. },
  13114. 'color-burn': function() {
  13115. dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
  13116. dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
  13117. db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
  13118. },
  13119. darken: function() {
  13120. dr = br < sr ? br : sr;
  13121. dg = bg < sg ? bg : sg;
  13122. db = bb < sb ? bb : sb;
  13123. },
  13124. lighten: function() {
  13125. dr = br > sr ? br : sr;
  13126. dg = bg > sg ? bg : sg;
  13127. db = bb > sb ? bb : sb;
  13128. },
  13129. difference: function() {
  13130. dr = br - sr;
  13131. if (dr < 0)
  13132. dr = -dr;
  13133. dg = bg - sg;
  13134. if (dg < 0)
  13135. dg = -dg;
  13136. db = bb - sb;
  13137. if (db < 0)
  13138. db = -db;
  13139. },
  13140. exclusion: function() {
  13141. dr = br + sr * (255 - br - br) / 255;
  13142. dg = bg + sg * (255 - bg - bg) / 255;
  13143. db = bb + sb * (255 - bb - bb) / 255;
  13144. },
  13145. hue: function() {
  13146. setSat(sr, sg, sb, getSat(br, bg, bb));
  13147. setLum(dr, dg, db, getLum(br, bg, bb));
  13148. },
  13149. saturation: function() {
  13150. setSat(br, bg, bb, getSat(sr, sg, sb));
  13151. setLum(dr, dg, db, getLum(br, bg, bb));
  13152. },
  13153. luminosity: function() {
  13154. setLum(br, bg, bb, getLum(sr, sg, sb));
  13155. },
  13156. color: function() {
  13157. setLum(sr, sg, sb, getLum(br, bg, bb));
  13158. },
  13159. add: function() {
  13160. dr = min(br + sr, 255);
  13161. dg = min(bg + sg, 255);
  13162. db = min(bb + sb, 255);
  13163. },
  13164. subtract: function() {
  13165. dr = max(br - sr, 0);
  13166. dg = max(bg - sg, 0);
  13167. db = max(bb - sb, 0);
  13168. },
  13169. average: function() {
  13170. dr = (br + sr) / 2;
  13171. dg = (bg + sg) / 2;
  13172. db = (bb + sb) / 2;
  13173. },
  13174. negation: function() {
  13175. dr = 255 - abs(255 - sr - br);
  13176. dg = 255 - abs(255 - sg - bg);
  13177. db = 255 - abs(255 - sb - bb);
  13178. }
  13179. };
  13180. var nativeModes = this.nativeModes = Base.each([
  13181. 'source-over', 'source-in', 'source-out', 'source-atop',
  13182. 'destination-over', 'destination-in', 'destination-out',
  13183. 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
  13184. ], function(mode) {
  13185. this[mode] = true;
  13186. }, {});
  13187. var ctx = CanvasProvider.getContext(1, 1);
  13188. if (ctx) {
  13189. Base.each(modes, function(func, mode) {
  13190. var darken = mode === 'darken',
  13191. ok = false;
  13192. ctx.save();
  13193. try {
  13194. ctx.fillStyle = darken ? '#300' : '#a00';
  13195. ctx.fillRect(0, 0, 1, 1);
  13196. ctx.globalCompositeOperation = mode;
  13197. if (ctx.globalCompositeOperation === mode) {
  13198. ctx.fillStyle = darken ? '#a00' : '#300';
  13199. ctx.fillRect(0, 0, 1, 1);
  13200. ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken
  13201. ? 170 : 51;
  13202. }
  13203. } catch (e) {}
  13204. ctx.restore();
  13205. nativeModes[mode] = ok;
  13206. });
  13207. CanvasProvider.release(ctx);
  13208. }
  13209. this.process = function(mode, srcContext, dstContext, alpha, offset) {
  13210. var srcCanvas = srcContext.canvas,
  13211. normal = mode === 'normal';
  13212. if (normal || nativeModes[mode]) {
  13213. dstContext.save();
  13214. dstContext.setTransform(1, 0, 0, 1, 0, 0);
  13215. dstContext.globalAlpha = alpha;
  13216. if (!normal)
  13217. dstContext.globalCompositeOperation = mode;
  13218. dstContext.drawImage(srcCanvas, offset.x, offset.y);
  13219. dstContext.restore();
  13220. } else {
  13221. var process = modes[mode];
  13222. if (!process)
  13223. return;
  13224. var dstData = dstContext.getImageData(offset.x, offset.y,
  13225. srcCanvas.width, srcCanvas.height),
  13226. dst = dstData.data,
  13227. src = srcContext.getImageData(0, 0,
  13228. srcCanvas.width, srcCanvas.height).data;
  13229. for (var i = 0, l = dst.length; i < l; i += 4) {
  13230. sr = src[i];
  13231. br = dst[i];
  13232. sg = src[i + 1];
  13233. bg = dst[i + 1];
  13234. sb = src[i + 2];
  13235. bb = dst[i + 2];
  13236. sa = src[i + 3];
  13237. ba = dst[i + 3];
  13238. process();
  13239. var a1 = sa * alpha / 255,
  13240. a2 = 1 - a1;
  13241. dst[i] = a1 * dr + a2 * br;
  13242. dst[i + 1] = a1 * dg + a2 * bg;
  13243. dst[i + 2] = a1 * db + a2 * bb;
  13244. dst[i + 3] = sa * alpha + a2 * ba;
  13245. }
  13246. dstContext.putImageData(dstData, offset.x, offset.y);
  13247. }
  13248. };
  13249. };
  13250. var SvgElement = new function() {
  13251. var svg = 'http://www.w3.org/2000/svg',
  13252. xmlns = 'http://www.w3.org/2000/xmlns',
  13253. xlink = 'http://www.w3.org/1999/xlink',
  13254. attributeNamespace = {
  13255. href: xlink,
  13256. xlink: xmlns,
  13257. xmlns: xmlns + '/',
  13258. 'xmlns:xlink': xmlns + '/'
  13259. };
  13260. function create(tag, attributes, formatter) {
  13261. return set(document.createElementNS(svg, tag), attributes, formatter);
  13262. }
  13263. function get(node, name) {
  13264. var namespace = attributeNamespace[name],
  13265. value = namespace
  13266. ? node.getAttributeNS(namespace, name)
  13267. : node.getAttribute(name);
  13268. return value === 'null' ? null : value;
  13269. }
  13270. function set(node, attributes, formatter) {
  13271. for (var name in attributes) {
  13272. var value = attributes[name],
  13273. namespace = attributeNamespace[name];
  13274. if (typeof value === 'number' && formatter)
  13275. value = formatter.number(value);
  13276. if (namespace) {
  13277. node.setAttributeNS(namespace, name, value);
  13278. } else {
  13279. node.setAttribute(name, value);
  13280. }
  13281. }
  13282. return node;
  13283. }
  13284. return {
  13285. svg: svg,
  13286. xmlns: xmlns,
  13287. xlink: xlink,
  13288. create: create,
  13289. get: get,
  13290. set: set
  13291. };
  13292. };
  13293. var SvgStyles = Base.each({
  13294. fillColor: ['fill', 'color'],
  13295. fillRule: ['fill-rule', 'string'],
  13296. strokeColor: ['stroke', 'color'],
  13297. strokeWidth: ['stroke-width', 'number'],
  13298. strokeCap: ['stroke-linecap', 'string'],
  13299. strokeJoin: ['stroke-linejoin', 'string'],
  13300. strokeScaling: ['vector-effect', 'lookup', {
  13301. true: 'none',
  13302. false: 'non-scaling-stroke'
  13303. }, function(item, value) {
  13304. return !value
  13305. && (item instanceof PathItem
  13306. || item instanceof Shape
  13307. || item instanceof TextItem);
  13308. }],
  13309. miterLimit: ['stroke-miterlimit', 'number'],
  13310. dashArray: ['stroke-dasharray', 'array'],
  13311. dashOffset: ['stroke-dashoffset', 'number'],
  13312. fontFamily: ['font-family', 'string'],
  13313. fontWeight: ['font-weight', 'string'],
  13314. fontSize: ['font-size', 'number'],
  13315. justification: ['text-anchor', 'lookup', {
  13316. left: 'start',
  13317. center: 'middle',
  13318. right: 'end'
  13319. }],
  13320. opacity: ['opacity', 'number'],
  13321. blendMode: ['mix-blend-mode', 'style']
  13322. }, function(entry, key) {
  13323. var part = Base.capitalize(key),
  13324. lookup = entry[2];
  13325. this[key] = {
  13326. type: entry[1],
  13327. property: key,
  13328. attribute: entry[0],
  13329. toSVG: lookup,
  13330. fromSVG: lookup && Base.each(lookup, function(value, name) {
  13331. this[value] = name;
  13332. }, {}),
  13333. exportFilter: entry[3],
  13334. get: 'get' + part,
  13335. set: 'set' + part
  13336. };
  13337. }, {});
  13338. new function() {
  13339. var formatter;
  13340. function getTransform(matrix, coordinates, center) {
  13341. var attrs = new Base(),
  13342. trans = matrix.getTranslation();
  13343. if (coordinates) {
  13344. var point;
  13345. if (matrix.isInvertible()) {
  13346. matrix = matrix._shiftless();
  13347. point = matrix._inverseTransform(trans);
  13348. trans = null;
  13349. } else {
  13350. point = new Point();
  13351. }
  13352. attrs[center ? 'cx' : 'x'] = point.x;
  13353. attrs[center ? 'cy' : 'y'] = point.y;
  13354. }
  13355. if (!matrix.isIdentity()) {
  13356. var decomposed = matrix.decompose();
  13357. if (decomposed) {
  13358. var parts = [],
  13359. angle = decomposed.rotation,
  13360. scale = decomposed.scaling,
  13361. skew = decomposed.skewing;
  13362. if (trans && !trans.isZero())
  13363. parts.push('translate(' + formatter.point(trans) + ')');
  13364. if (angle)
  13365. parts.push('rotate(' + formatter.number(angle) + ')');
  13366. if (!Numerical.isZero(scale.x - 1)
  13367. || !Numerical.isZero(scale.y - 1))
  13368. parts.push('scale(' + formatter.point(scale) +')');
  13369. if (skew.x)
  13370. parts.push('skewX(' + formatter.number(skew.x) + ')');
  13371. if (skew.y)
  13372. parts.push('skewY(' + formatter.number(skew.y) + ')');
  13373. attrs.transform = parts.join(' ');
  13374. } else {
  13375. attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
  13376. }
  13377. }
  13378. return attrs;
  13379. }
  13380. function exportGroup(item, options) {
  13381. var attrs = getTransform(item._matrix),
  13382. children = item._children;
  13383. var node = SvgElement.create('g', attrs, formatter);
  13384. for (var i = 0, l = children.length; i < l; i++) {
  13385. var child = children[i];
  13386. var childNode = exportSVG(child, options);
  13387. if (childNode) {
  13388. if (child.isClipMask()) {
  13389. var clip = SvgElement.create('clipPath');
  13390. clip.appendChild(childNode);
  13391. setDefinition(child, clip, 'clip');
  13392. SvgElement.set(node, {
  13393. 'clip-path': 'url(#' + clip.id + ')'
  13394. });
  13395. } else {
  13396. node.appendChild(childNode);
  13397. }
  13398. }
  13399. }
  13400. return node;
  13401. }
  13402. function exportRaster(item, options) {
  13403. var attrs = getTransform(item._matrix, true),
  13404. size = item.getSize(),
  13405. image = item.getImage();
  13406. attrs.x -= size.width / 2;
  13407. attrs.y -= size.height / 2;
  13408. attrs.width = size.width;
  13409. attrs.height = size.height;
  13410. attrs.href = options.embedImages == false && image && image.src
  13411. || item.toDataURL();
  13412. return SvgElement.create('image', attrs, formatter);
  13413. }
  13414. function exportPath(item, options) {
  13415. var matchShapes = options.matchShapes;
  13416. if (matchShapes) {
  13417. var shape = item.toShape(false);
  13418. if (shape)
  13419. return exportShape(shape, options);
  13420. }
  13421. var segments = item._segments,
  13422. length = segments.length,
  13423. type,
  13424. attrs = getTransform(item._matrix);
  13425. if (matchShapes && length >= 2 && !item.hasHandles()) {
  13426. if (length > 2) {
  13427. type = item._closed ? 'polygon' : 'polyline';
  13428. var parts = [];
  13429. for (var i = 0; i < length; i++) {
  13430. parts.push(formatter.point(segments[i]._point));
  13431. }
  13432. attrs.points = parts.join(' ');
  13433. } else {
  13434. type = 'line';
  13435. var start = segments[0]._point,
  13436. end = segments[1]._point;
  13437. attrs.set({
  13438. x1: start.x,
  13439. y1: start.y,
  13440. x2: end.x,
  13441. y2: end.y
  13442. });
  13443. }
  13444. } else {
  13445. type = 'path';
  13446. attrs.d = item.getPathData(null, options.precision);
  13447. }
  13448. return SvgElement.create(type, attrs, formatter);
  13449. }
  13450. function exportShape(item) {
  13451. var type = item._type,
  13452. radius = item._radius,
  13453. attrs = getTransform(item._matrix, true, type !== 'rectangle');
  13454. if (type === 'rectangle') {
  13455. type = 'rect';
  13456. var size = item._size,
  13457. width = size.width,
  13458. height = size.height;
  13459. attrs.x -= width / 2;
  13460. attrs.y -= height / 2;
  13461. attrs.width = width;
  13462. attrs.height = height;
  13463. if (radius.isZero())
  13464. radius = null;
  13465. }
  13466. if (radius) {
  13467. if (type === 'circle') {
  13468. attrs.r = radius;
  13469. } else {
  13470. attrs.rx = radius.width;
  13471. attrs.ry = radius.height;
  13472. }
  13473. }
  13474. return SvgElement.create(type, attrs, formatter);
  13475. }
  13476. function exportCompoundPath(item, options) {
  13477. var attrs = getTransform(item._matrix);
  13478. var data = item.getPathData(null, options.precision);
  13479. if (data)
  13480. attrs.d = data;
  13481. return SvgElement.create('path', attrs, formatter);
  13482. }
  13483. function exportSymbolItem(item, options) {
  13484. var attrs = getTransform(item._matrix, true),
  13485. definition = item._definition,
  13486. node = getDefinition(definition, 'symbol'),
  13487. definitionItem = definition._item,
  13488. bounds = definitionItem.getStrokeBounds();
  13489. if (!node) {
  13490. node = SvgElement.create('symbol', {
  13491. viewBox: formatter.rectangle(bounds)
  13492. });
  13493. node.appendChild(exportSVG(definitionItem, options));
  13494. setDefinition(definition, node, 'symbol');
  13495. }
  13496. attrs.href = '#' + node.id;
  13497. attrs.x += bounds.x;
  13498. attrs.y += bounds.y;
  13499. attrs.width = bounds.width;
  13500. attrs.height = bounds.height;
  13501. attrs.overflow = 'visible';
  13502. return SvgElement.create('use', attrs, formatter);
  13503. }
  13504. function exportGradient(color) {
  13505. var gradientNode = getDefinition(color, 'color');
  13506. if (!gradientNode) {
  13507. var gradient = color.getGradient(),
  13508. radial = gradient._radial,
  13509. origin = color.getOrigin(),
  13510. destination = color.getDestination(),
  13511. attrs;
  13512. if (radial) {
  13513. attrs = {
  13514. cx: origin.x,
  13515. cy: origin.y,
  13516. r: origin.getDistance(destination)
  13517. };
  13518. var highlight = color.getHighlight();
  13519. if (highlight) {
  13520. attrs.fx = highlight.x;
  13521. attrs.fy = highlight.y;
  13522. }
  13523. } else {
  13524. attrs = {
  13525. x1: origin.x,
  13526. y1: origin.y,
  13527. x2: destination.x,
  13528. y2: destination.y
  13529. };
  13530. }
  13531. attrs.gradientUnits = 'userSpaceOnUse';
  13532. gradientNode = SvgElement.create((radial ? 'radial' : 'linear')
  13533. + 'Gradient', attrs, formatter);
  13534. var stops = gradient._stops;
  13535. for (var i = 0, l = stops.length; i < l; i++) {
  13536. var stop = stops[i],
  13537. stopColor = stop._color,
  13538. alpha = stopColor.getAlpha(),
  13539. offset = stop._offset;
  13540. attrs = {
  13541. offset: offset == null ? i / (l - 1) : offset
  13542. };
  13543. if (stopColor)
  13544. attrs['stop-color'] = stopColor.toCSS(true);
  13545. if (alpha < 1)
  13546. attrs['stop-opacity'] = alpha;
  13547. gradientNode.appendChild(
  13548. SvgElement.create('stop', attrs, formatter));
  13549. }
  13550. setDefinition(color, gradientNode, 'color');
  13551. }
  13552. return 'url(#' + gradientNode.id + ')';
  13553. }
  13554. function exportText(item) {
  13555. var node = SvgElement.create('text', getTransform(item._matrix, true),
  13556. formatter);
  13557. node.textContent = item._content;
  13558. return node;
  13559. }
  13560. var exporters = {
  13561. Group: exportGroup,
  13562. Layer: exportGroup,
  13563. Raster: exportRaster,
  13564. Path: exportPath,
  13565. Shape: exportShape,
  13566. CompoundPath: exportCompoundPath,
  13567. SymbolItem: exportSymbolItem,
  13568. PointText: exportText
  13569. };
  13570. function applyStyle(item, node, isRoot) {
  13571. var attrs = {},
  13572. parent = !isRoot && item.getParent(),
  13573. style = [];
  13574. if (item._name != null)
  13575. attrs.id = item._name;
  13576. Base.each(SvgStyles, function(entry) {
  13577. var get = entry.get,
  13578. type = entry.type,
  13579. value = item[get]();
  13580. if (entry.exportFilter
  13581. ? entry.exportFilter(item, value)
  13582. : !parent || !Base.equals(parent[get](), value)) {
  13583. if (type === 'color' && value != null) {
  13584. var alpha = value.getAlpha();
  13585. if (alpha < 1)
  13586. attrs[entry.attribute + '-opacity'] = alpha;
  13587. }
  13588. if (type === 'style') {
  13589. style.push(entry.attribute + ': ' + value);
  13590. } else {
  13591. attrs[entry.attribute] = value == null ? 'none'
  13592. : type === 'color' ? value.gradient
  13593. ? exportGradient(value, item)
  13594. : value.toCSS(true)
  13595. : type === 'array' ? value.join(',')
  13596. : type === 'lookup' ? entry.toSVG[value]
  13597. : value;
  13598. }
  13599. }
  13600. });
  13601. if (style.length)
  13602. attrs.style = style.join(';');
  13603. if (attrs.opacity === 1)
  13604. delete attrs.opacity;
  13605. if (!item._visible)
  13606. attrs.visibility = 'hidden';
  13607. return SvgElement.set(node, attrs, formatter);
  13608. }
  13609. var definitions;
  13610. function getDefinition(item, type) {
  13611. if (!definitions)
  13612. definitions = { ids: {}, svgs: {} };
  13613. return item && definitions.svgs[type + '-'
  13614. + (item._id || item.__id || (item.__id = UID.get('svg')))];
  13615. }
  13616. function setDefinition(item, node, type) {
  13617. if (!definitions)
  13618. getDefinition();
  13619. var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
  13620. node.id = type + '-' + typeId;
  13621. definitions.svgs[type + '-' + (item._id || item.__id)] = node;
  13622. }
  13623. function exportDefinitions(node, options) {
  13624. var svg = node,
  13625. defs = null;
  13626. if (definitions) {
  13627. svg = node.nodeName.toLowerCase() === 'svg' && node;
  13628. for (var i in definitions.svgs) {
  13629. if (!defs) {
  13630. if (!svg) {
  13631. svg = SvgElement.create('svg');
  13632. svg.appendChild(node);
  13633. }
  13634. defs = svg.insertBefore(SvgElement.create('defs'),
  13635. svg.firstChild);
  13636. }
  13637. defs.appendChild(definitions.svgs[i]);
  13638. }
  13639. definitions = null;
  13640. }
  13641. return options.asString
  13642. ? new self.XMLSerializer().serializeToString(svg)
  13643. : svg;
  13644. }
  13645. function exportSVG(item, options, isRoot) {
  13646. var exporter = exporters[item._class],
  13647. node = exporter && exporter(item, options);
  13648. if (node) {
  13649. var onExport = options.onExport;
  13650. if (onExport)
  13651. node = onExport(item, node, options) || node;
  13652. var data = JSON.stringify(item._data);
  13653. if (data && data !== '{}' && data !== 'null')
  13654. node.setAttribute('data-paper-data', data);
  13655. }
  13656. return node && applyStyle(item, node, isRoot);
  13657. }
  13658. function setOptions(options) {
  13659. if (!options)
  13660. options = {};
  13661. formatter = new Formatter(options.precision);
  13662. return options;
  13663. }
  13664. Item.inject({
  13665. exportSVG: function(options) {
  13666. options = setOptions(options);
  13667. return exportDefinitions(exportSVG(this, options, true), options);
  13668. }
  13669. });
  13670. Project.inject({
  13671. exportSVG: function(options) {
  13672. options = setOptions(options);
  13673. var children = this._children,
  13674. view = this.getView(),
  13675. bounds = Base.pick(options.bounds, 'view'),
  13676. mx = options.matrix || bounds === 'view' && view._matrix,
  13677. matrix = mx && Matrix.read([mx]),
  13678. rect = bounds === 'view'
  13679. ? new Rectangle([0, 0], view.getViewSize())
  13680. : bounds === 'content'
  13681. ? Item._getBounds(children, matrix, { stroke: true })
  13682. .rect
  13683. : Rectangle.read([bounds], 0, { readNull: true }),
  13684. attrs = {
  13685. version: '1.1',
  13686. xmlns: SvgElement.svg,
  13687. 'xmlns:xlink': SvgElement.xlink,
  13688. };
  13689. if (rect) {
  13690. attrs.width = rect.width;
  13691. attrs.height = rect.height;
  13692. if (rect.x || rect.x === 0 || rect.y || rect.y === 0)
  13693. attrs.viewBox = formatter.rectangle(rect);
  13694. }
  13695. var node = SvgElement.create('svg', attrs, formatter),
  13696. parent = node;
  13697. if (matrix && !matrix.isIdentity()) {
  13698. parent = node.appendChild(SvgElement.create('g',
  13699. getTransform(matrix), formatter));
  13700. }
  13701. for (var i = 0, l = children.length; i < l; i++) {
  13702. parent.appendChild(exportSVG(children[i], options, true));
  13703. }
  13704. return exportDefinitions(node, options);
  13705. }
  13706. });
  13707. };
  13708. new function() {
  13709. var definitions = {},
  13710. rootSize;
  13711. function getValue(node, name, isString, allowNull, allowPercent,
  13712. defaultValue) {
  13713. var value = SvgElement.get(node, name) || defaultValue,
  13714. res = value == null
  13715. ? allowNull
  13716. ? null
  13717. : isString ? '' : 0
  13718. : isString
  13719. ? value
  13720. : parseFloat(value);
  13721. return /%\s*$/.test(value)
  13722. ? (res / 100) * (allowPercent ? 1
  13723. : rootSize[/x|^width/.test(name) ? 'width' : 'height'])
  13724. : res;
  13725. }
  13726. function getPoint(node, x, y, allowNull, allowPercent, defaultX, defaultY) {
  13727. x = getValue(node, x || 'x', false, allowNull, allowPercent, defaultX);
  13728. y = getValue(node, y || 'y', false, allowNull, allowPercent, defaultY);
  13729. return allowNull && (x == null || y == null) ? null
  13730. : new Point(x, y);
  13731. }
  13732. function getSize(node, w, h, allowNull, allowPercent) {
  13733. w = getValue(node, w || 'width', false, allowNull, allowPercent);
  13734. h = getValue(node, h || 'height', false, allowNull, allowPercent);
  13735. return allowNull && (w == null || h == null) ? null
  13736. : new Size(w, h);
  13737. }
  13738. function convertValue(value, type, lookup) {
  13739. return value === 'none' ? null
  13740. : type === 'number' ? parseFloat(value)
  13741. : type === 'array' ?
  13742. value ? value.split(/[\s,]+/g).map(parseFloat) : []
  13743. : type === 'color' ? getDefinition(value) || value
  13744. : type === 'lookup' ? lookup[value]
  13745. : value;
  13746. }
  13747. function importGroup(node, type, options, isRoot) {
  13748. var nodes = node.childNodes,
  13749. isClip = type === 'clippath',
  13750. isDefs = type === 'defs',
  13751. item = new Group(),
  13752. project = item._project,
  13753. currentStyle = project._currentStyle,
  13754. children = [];
  13755. if (!isClip && !isDefs) {
  13756. item = applyAttributes(item, node, isRoot);
  13757. project._currentStyle = item._style.clone();
  13758. }
  13759. if (isRoot) {
  13760. var defs = node.querySelectorAll('defs');
  13761. for (var i = 0, l = defs.length; i < l; i++) {
  13762. importNode(defs[i], options, false);
  13763. }
  13764. }
  13765. for (var i = 0, l = nodes.length; i < l; i++) {
  13766. var childNode = nodes[i],
  13767. child;
  13768. if (childNode.nodeType === 1
  13769. && !/^defs$/i.test(childNode.nodeName)
  13770. && (child = importNode(childNode, options, false))
  13771. && !(child instanceof SymbolDefinition))
  13772. children.push(child);
  13773. }
  13774. item.addChildren(children);
  13775. if (isClip)
  13776. item = applyAttributes(item.reduce(), node, isRoot);
  13777. project._currentStyle = currentStyle;
  13778. if (isClip || isDefs) {
  13779. item.remove();
  13780. item = null;
  13781. }
  13782. return item;
  13783. }
  13784. function importPoly(node, type) {
  13785. var coords = node.getAttribute('points').match(
  13786. /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),
  13787. points = [];
  13788. for (var i = 0, l = coords.length; i < l; i += 2)
  13789. points.push(new Point(
  13790. parseFloat(coords[i]),
  13791. parseFloat(coords[i + 1])));
  13792. var path = new Path(points);
  13793. if (type === 'polygon')
  13794. path.closePath();
  13795. return path;
  13796. }
  13797. function importPath(node) {
  13798. return PathItem.create(node.getAttribute('d'));
  13799. }
  13800. function importGradient(node, type) {
  13801. var id = (getValue(node, 'href', true) || '').substring(1),
  13802. radial = type === 'radialgradient',
  13803. gradient;
  13804. if (id) {
  13805. gradient = definitions[id].getGradient();
  13806. if (gradient._radial ^ radial) {
  13807. gradient = gradient.clone();
  13808. gradient._radial = radial;
  13809. }
  13810. } else {
  13811. var nodes = node.childNodes,
  13812. stops = [];
  13813. for (var i = 0, l = nodes.length; i < l; i++) {
  13814. var child = nodes[i];
  13815. if (child.nodeType === 1)
  13816. stops.push(applyAttributes(new GradientStop(), child));
  13817. }
  13818. gradient = new Gradient(stops, radial);
  13819. }
  13820. var origin, destination, highlight,
  13821. scaleToBounds = getValue(node, 'gradientUnits', true) !==
  13822. 'userSpaceOnUse';
  13823. if (radial) {
  13824. origin = getPoint(node, 'cx', 'cy', false, scaleToBounds,
  13825. '50%', '50%');
  13826. destination = origin.add(
  13827. getValue(node, 'r', false, false, scaleToBounds, '50%'), 0);
  13828. highlight = getPoint(node, 'fx', 'fy', true, scaleToBounds);
  13829. } else {
  13830. origin = getPoint(node, 'x1', 'y1', false, scaleToBounds,
  13831. '0%', '0%');
  13832. destination = getPoint(node, 'x2', 'y2', false, scaleToBounds,
  13833. '100%', '0%');
  13834. }
  13835. var color = applyAttributes(
  13836. new Color(gradient, origin, destination, highlight), node);
  13837. color._scaleToBounds = scaleToBounds;
  13838. return null;
  13839. }
  13840. var importers = {
  13841. '#document': function (node, type, options, isRoot) {
  13842. var nodes = node.childNodes;
  13843. for (var i = 0, l = nodes.length; i < l; i++) {
  13844. var child = nodes[i];
  13845. if (child.nodeType === 1)
  13846. return importNode(child, options, isRoot);
  13847. }
  13848. },
  13849. g: importGroup,
  13850. svg: importGroup,
  13851. clippath: importGroup,
  13852. polygon: importPoly,
  13853. polyline: importPoly,
  13854. path: importPath,
  13855. lineargradient: importGradient,
  13856. radialgradient: importGradient,
  13857. image: function (node) {
  13858. var raster = new Raster(getValue(node, 'href', true));
  13859. raster.on('load', function() {
  13860. var size = getSize(node);
  13861. this.setSize(size);
  13862. var center = getPoint(node).add(size.divide(2));
  13863. this._matrix.append(new Matrix().translate(center));
  13864. });
  13865. return raster;
  13866. },
  13867. symbol: function(node, type, options, isRoot) {
  13868. return new SymbolDefinition(
  13869. importGroup(node, type, options, isRoot), true);
  13870. },
  13871. defs: importGroup,
  13872. use: function(node) {
  13873. var id = (getValue(node, 'href', true) || '').substring(1),
  13874. definition = definitions[id],
  13875. point = getPoint(node);
  13876. return definition
  13877. ? definition instanceof SymbolDefinition
  13878. ? definition.place(point)
  13879. : definition.clone().translate(point)
  13880. : null;
  13881. },
  13882. circle: function(node) {
  13883. return new Shape.Circle(
  13884. getPoint(node, 'cx', 'cy'),
  13885. getValue(node, 'r'));
  13886. },
  13887. ellipse: function(node) {
  13888. return new Shape.Ellipse({
  13889. center: getPoint(node, 'cx', 'cy'),
  13890. radius: getSize(node, 'rx', 'ry')
  13891. });
  13892. },
  13893. rect: function(node) {
  13894. return new Shape.Rectangle(new Rectangle(
  13895. getPoint(node),
  13896. getSize(node)
  13897. ), getSize(node, 'rx', 'ry'));
  13898. },
  13899. line: function(node) {
  13900. return new Path.Line(
  13901. getPoint(node, 'x1', 'y1'),
  13902. getPoint(node, 'x2', 'y2'));
  13903. },
  13904. text: function(node) {
  13905. var text = new PointText(getPoint(node).add(
  13906. getPoint(node, 'dx', 'dy')));
  13907. text.setContent(node.textContent.trim() || '');
  13908. return text;
  13909. },
  13910. switch: importGroup
  13911. };
  13912. function applyTransform(item, value, name, node) {
  13913. if (item.transform) {
  13914. var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
  13915. matrix = new Matrix();
  13916. for (var i = 0, l = transforms.length; i < l; i++) {
  13917. var transform = transforms[i];
  13918. if (!transform)
  13919. break;
  13920. var parts = transform.split(/\(\s*/),
  13921. command = parts[0],
  13922. v = parts[1].split(/[\s,]+/g);
  13923. for (var j = 0, m = v.length; j < m; j++)
  13924. v[j] = parseFloat(v[j]);
  13925. switch (command) {
  13926. case 'matrix':
  13927. matrix.append(
  13928. new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
  13929. break;
  13930. case 'rotate':
  13931. matrix.rotate(v[0], v[1] || 0, v[2] || 0);
  13932. break;
  13933. case 'translate':
  13934. matrix.translate(v[0], v[1] || 0);
  13935. break;
  13936. case 'scale':
  13937. matrix.scale(v);
  13938. break;
  13939. case 'skewX':
  13940. matrix.skew(v[0], 0);
  13941. break;
  13942. case 'skewY':
  13943. matrix.skew(0, v[0]);
  13944. break;
  13945. }
  13946. }
  13947. item.transform(matrix);
  13948. }
  13949. }
  13950. function applyOpacity(item, value, name) {
  13951. var key = name === 'fill-opacity' ? 'getFillColor' : 'getStrokeColor',
  13952. color = item[key] && item[key]();
  13953. if (color)
  13954. color.setAlpha(parseFloat(value));
  13955. }
  13956. var attributes = Base.set(Base.each(SvgStyles, function(entry) {
  13957. this[entry.attribute] = function(item, value) {
  13958. if (item[entry.set]) {
  13959. item[entry.set](convertValue(value, entry.type, entry.fromSVG));
  13960. if (entry.type === 'color') {
  13961. var color = item[entry.get]();
  13962. if (color) {
  13963. if (color._scaleToBounds) {
  13964. var bounds = item.getBounds();
  13965. color.transform(new Matrix()
  13966. .translate(bounds.getPoint())
  13967. .scale(bounds.getSize()));
  13968. }
  13969. }
  13970. }
  13971. }
  13972. };
  13973. }, {}), {
  13974. id: function(item, value) {
  13975. definitions[value] = item;
  13976. if (item.setName)
  13977. item.setName(value);
  13978. },
  13979. 'clip-path': function(item, value) {
  13980. var clip = getDefinition(value);
  13981. if (clip) {
  13982. clip = clip.clone();
  13983. clip.setClipMask(true);
  13984. if (item instanceof Group) {
  13985. item.insertChild(0, clip);
  13986. } else {
  13987. return new Group(clip, item);
  13988. }
  13989. }
  13990. },
  13991. gradientTransform: applyTransform,
  13992. transform: applyTransform,
  13993. 'fill-opacity': applyOpacity,
  13994. 'stroke-opacity': applyOpacity,
  13995. visibility: function(item, value) {
  13996. if (item.setVisible)
  13997. item.setVisible(value === 'visible');
  13998. },
  13999. display: function(item, value) {
  14000. if (item.setVisible)
  14001. item.setVisible(value !== null);
  14002. },
  14003. 'stop-color': function(item, value) {
  14004. if (item.setColor)
  14005. item.setColor(value);
  14006. },
  14007. 'stop-opacity': function(item, value) {
  14008. if (item._color)
  14009. item._color.setAlpha(parseFloat(value));
  14010. },
  14011. offset: function(item, value) {
  14012. if (item.setOffset) {
  14013. var percent = value.match(/(.*)%$/);
  14014. item.setOffset(percent ? percent[1] / 100 : parseFloat(value));
  14015. }
  14016. },
  14017. viewBox: function(item, value, name, node, styles) {
  14018. var rect = new Rectangle(convertValue(value, 'array')),
  14019. size = getSize(node, null, null, true),
  14020. group,
  14021. matrix;
  14022. if (item instanceof Group) {
  14023. var scale = size ? size.divide(rect.getSize()) : 1,
  14024. matrix = new Matrix().scale(scale)
  14025. .translate(rect.getPoint().negate());
  14026. group = item;
  14027. } else if (item instanceof SymbolDefinition) {
  14028. if (size)
  14029. rect.setSize(size);
  14030. group = item._item;
  14031. }
  14032. if (group) {
  14033. if (getAttribute(node, 'overflow', styles) !== 'visible') {
  14034. var clip = new Shape.Rectangle(rect);
  14035. clip.setClipMask(true);
  14036. group.addChild(clip);
  14037. }
  14038. if (matrix)
  14039. group.transform(matrix);
  14040. }
  14041. }
  14042. });
  14043. function getAttribute(node, name, styles) {
  14044. var attr = node.attributes[name],
  14045. value = attr && attr.value;
  14046. if (!value && node.style) {
  14047. var style = Base.camelize(name);
  14048. value = node.style[style];
  14049. if (!value && styles.node[style] !== styles.parent[style])
  14050. value = styles.node[style];
  14051. }
  14052. return !value ? undefined
  14053. : value === 'none' ? null
  14054. : value;
  14055. }
  14056. function applyAttributes(item, node, isRoot) {
  14057. var parent = node.parentNode,
  14058. styles = {
  14059. node: DomElement.getStyles(node) || {},
  14060. parent: !isRoot && !/^defs$/i.test(parent.tagName)
  14061. && DomElement.getStyles(parent) || {}
  14062. };
  14063. Base.each(attributes, function(apply, name) {
  14064. var value = getAttribute(node, name, styles);
  14065. item = value !== undefined
  14066. && apply(item, value, name, node, styles) || item;
  14067. });
  14068. return item;
  14069. }
  14070. function getDefinition(value) {
  14071. var match = value && value.match(/\((?:["'#]*)([^"')]+)/),
  14072. name = match && match[1],
  14073. res = name && definitions[window
  14074. ? name.replace(window.location.href.split('#')[0] + '#', '')
  14075. : name];
  14076. if (res && res._scaleToBounds) {
  14077. res = res.clone();
  14078. res._scaleToBounds = true;
  14079. }
  14080. return res;
  14081. }
  14082. function importNode(node, options, isRoot) {
  14083. var type = node.nodeName.toLowerCase(),
  14084. isElement = type !== '#document',
  14085. body = document.body,
  14086. container,
  14087. parent,
  14088. next;
  14089. if (isRoot && isElement) {
  14090. rootSize = paper.getView().getSize();
  14091. rootSize = getSize(node, null, null, true) || rootSize;
  14092. container = SvgElement.create('svg', {
  14093. style: 'stroke-width: 1px; stroke-miterlimit: 10'
  14094. });
  14095. parent = node.parentNode;
  14096. next = node.nextSibling;
  14097. container.appendChild(node);
  14098. body.appendChild(container);
  14099. }
  14100. var settings = paper.settings,
  14101. applyMatrix = settings.applyMatrix,
  14102. insertItems = settings.insertItems;
  14103. settings.applyMatrix = false;
  14104. settings.insertItems = false;
  14105. var importer = importers[type],
  14106. item = importer && importer(node, type, options, isRoot) || null;
  14107. settings.insertItems = insertItems;
  14108. settings.applyMatrix = applyMatrix;
  14109. if (item) {
  14110. if (isElement && !(item instanceof Group))
  14111. item = applyAttributes(item, node, isRoot);
  14112. var onImport = options.onImport,
  14113. data = isElement && node.getAttribute('data-paper-data');
  14114. if (onImport)
  14115. item = onImport(node, item, options) || item;
  14116. if (options.expandShapes && item instanceof Shape) {
  14117. item.remove();
  14118. item = item.toPath();
  14119. }
  14120. if (data)
  14121. item._data = JSON.parse(data);
  14122. }
  14123. if (container) {
  14124. body.removeChild(container);
  14125. if (parent) {
  14126. if (next) {
  14127. parent.insertBefore(node, next);
  14128. } else {
  14129. parent.appendChild(node);
  14130. }
  14131. }
  14132. }
  14133. if (isRoot) {
  14134. definitions = {};
  14135. if (item && Base.pick(options.applyMatrix, applyMatrix))
  14136. item.matrix.apply(true, true);
  14137. }
  14138. return item;
  14139. }
  14140. function importSVG(source, options, owner) {
  14141. if (!source)
  14142. return null;
  14143. options = typeof options === 'function' ? { onLoad: options }
  14144. : options || {};
  14145. var scope = paper,
  14146. item = null;
  14147. function onLoad(svg) {
  14148. try {
  14149. var node = typeof svg === 'object'
  14150. ? svg
  14151. : new self.DOMParser().parseFromString(
  14152. svg.trim(),
  14153. 'image/svg+xml'
  14154. );
  14155. if (!node.nodeName) {
  14156. node = null;
  14157. throw new Error('Unsupported SVG source: ' + source);
  14158. }
  14159. paper = scope;
  14160. item = importNode(node, options, true);
  14161. if (!options || options.insert !== false) {
  14162. owner._insertItem(undefined, item);
  14163. }
  14164. var onLoad = options.onLoad;
  14165. if (onLoad)
  14166. onLoad(item, svg);
  14167. } catch (e) {
  14168. onError(e);
  14169. }
  14170. }
  14171. function onError(message, status) {
  14172. var onError = options.onError;
  14173. if (onError) {
  14174. onError(message, status);
  14175. } else {
  14176. throw new Error(message);
  14177. }
  14178. }
  14179. if (typeof source === 'string' && !/^[\s\S]*</.test(source)) {
  14180. var node = document.getElementById(source);
  14181. if (node) {
  14182. onLoad(node);
  14183. } else {
  14184. Http.request({
  14185. url: source,
  14186. async: true,
  14187. onLoad: onLoad,
  14188. onError: onError
  14189. });
  14190. }
  14191. } else if (typeof File !== 'undefined' && source instanceof File) {
  14192. var reader = new FileReader();
  14193. reader.onload = function() {
  14194. onLoad(reader.result);
  14195. };
  14196. reader.onerror = function() {
  14197. onError(reader.error);
  14198. };
  14199. return reader.readAsText(source);
  14200. } else {
  14201. onLoad(source);
  14202. }
  14203. return item;
  14204. }
  14205. Item.inject({
  14206. importSVG: function(node, options) {
  14207. return importSVG(node, options, this);
  14208. }
  14209. });
  14210. Project.inject({
  14211. importSVG: function(node, options) {
  14212. this.activate();
  14213. return importSVG(node, options, this);
  14214. }
  14215. });
  14216. };
  14217. var paper = new (PaperScope.inject(Base.exports, {
  14218. Base: Base,
  14219. Numerical: Numerical,
  14220. Key: Key,
  14221. DomEvent: DomEvent,
  14222. DomElement: DomElement,
  14223. document: document,
  14224. window: window,
  14225. Symbol: SymbolDefinition,
  14226. PlacedSymbol: SymbolItem
  14227. }))();
  14228. if (paper.agent.node) {
  14229. require('./node/extend.js')(paper);
  14230. }
  14231. if (typeof define === 'function' && define.amd) {
  14232. define('paper', paper);
  14233. } else if (typeof module === 'object' && module) {
  14234. module.exports = paper;
  14235. }
  14236. return paper;
  14237. }.call(this, typeof self === 'object' ? self : null);