EditorUi.js 155 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899
/**
 * Copyright (c) 2006-2012, JGraph Ltd
 */
/**
 * Constructs a new graph editor
 */
EditorUi = function(editor, container, lightbox)
{
	mxEventSource.call(this);
	
	this.destroyFunctions = [];
	this.editor = editor || new Editor();
	this.container = container || document.body;
	
	var graph = this.editor.graph;
	graph.lightbox = lightbox;

	// Overrides graph bounds to include background images
	var graphGetGraphBounds = graph.getGraphBounds;

	graph.getGraphBounds = function()
	{
		var bounds = graphGetGraphBounds.apply(this, arguments);
		var img = this.backgroundImage;
		
		if (img != null && img.width != null && img.height != null)
		{
			var t = this.view.translate;
			var s = this.view.scale;

			bounds = mxRectangle.fromRectangle(bounds);
			bounds.add(new mxRectangle(
				(t.x + img.x) * s, (t.y + img.y) * s,
				img.width * s, img.height * s));
		}

		return bounds;
	};

	// Faster scrollwheel zoom is possible with CSS transforms
	if (graph.useCssTransforms)
	{
		this.lazyZoomDelay = 0;
	}
	
	// Pre-fetches submenu image or replaces with embedded image if supported
	if (mxClient.IS_SVG)
	{
		mxPopupMenu.prototype.submenuImage = 'data:image/gif;base64,R0lGODlhCQAJAIAAAP///zMzMyH5BAEAAAAALAAAAAAJAAkAAAIPhI8WebHsHopSOVgb26AAADs=';
	}
	else
	{
		new Image().src = mxPopupMenu.prototype.submenuImage;
	}

	// Pre-fetches connect image
	if (!mxClient.IS_SVG && mxConnectionHandler.prototype.connectImage != null)
	{
		new Image().src = mxConnectionHandler.prototype.connectImage.src;
	}

	// Installs selection state listener
	this.selectionStateListener = mxUtils.bind(this, function(sender, evt)
	{
		this.clearSelectionState();
	});
	
	graph.getSelectionModel().addListener(mxEvent.CHANGE, this.selectionStateListener);
	graph.getModel().addListener(mxEvent.CHANGE, this.selectionStateListener);
	graph.addListener(mxEvent.EDITING_STARTED, this.selectionStateListener);
	graph.addListener(mxEvent.EDITING_STOPPED, this.selectionStateListener);
	graph.getView().addListener('unitChanged', this.selectionStateListener);

	// Disables graph and forced panning in chromeless mode
	if (this.editor.chromeless && !this.editor.editable)
	{
		this.footerHeight = 0;
		graph.isEnabled = function() { return false; };
		graph.panningHandler.isForcePanningEvent = function(me)
		{
			return !mxEvent.isPopupTrigger(me.getEvent());
		};
	}
	
    // Creates the user interface
	this.actions = new Actions(this);
	this.menus = this.createMenus();
	
	if (!graph.standalone)
	{
		// Stores the current style and assigns it to new cells
		var styles = ['rounded', 'shadow', 'glass', 'dashed', 'dashPattern', 'labelBackgroundColor',
			'labelBorderColor', 'comic', 'sketch', 'fillWeight', 'hachureGap', 'hachureAngle', 'jiggle',
			'disableMultiStroke', 'disableMultiStrokeFill', 'fillStyle', 'curveFitting',
			'simplification', 'sketchStyle', 'pointerEvents'];
		var connectStyles = ['shape', 'edgeStyle', 'curved', 'rounded', 'elbow', 'jumpStyle', 'jumpSize',
			'comic', 'sketch', 'fillWeight', 'hachureGap', 'hachureAngle', 'jiggle',
			'disableMultiStroke', 'disableMultiStrokeFill', 'fillStyle', 'curveFitting',
			'simplification', 'sketchStyle'];
		// Styles to be ignored if applyAll is false
		var ignoredEdgeStyles = ['curved', 'sourcePerimeterSpacing', 'targetPerimeterSpacing',
			'startArrow', 'startFill', 'startSize', 'endArrow', 'endFill', 'endSize'];
		
		// Note: Everything that is not in styles is ignored (styles is augmented below)
		this.setDefaultStyle = function(cell)
		{
			try
			{
				var style = graph.getCellStyle(cell, false);
				var values = [];
				var keys = [];

				for (var key in style)
				{
					values.push(style[key]);
					keys.push(key);
				}

				// Resets current style
				if (graph.getModel().isEdge(cell))
				{
					graph.currentEdgeStyle = {};
				}
				else
				{
					graph.currentVertexStyle = {}
				}
	
				this.fireEvent(new mxEventObject('styleChanged',
					'keys', keys, 'values', values,
					'cells', [cell]));
			}
			catch (e)
			{
				this.handleError(e);
			}
		};

		this.clearDefaultStyle = function()
		{
			graph.currentEdgeStyle = mxUtils.clone(graph.defaultEdgeStyle);
			graph.currentVertexStyle = mxUtils.clone(graph.defaultVertexStyle);
			
			// Updates UI
			this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
		};
	
		// Keys that should be ignored if the cell has a value (known: new default for all cells is html=1 so
	    // for the html key this effecticely only works for edges inserted via the connection handler)
		var valueStyles = ['fontFamily', 'fontSource', 'fontSize', 'fontColor'];
				
		for (var i = 0; i < valueStyles.length; i++)
		{
			if (mxUtils.indexOf(styles, valueStyles[i]) < 0)
			{
				styles.push(valueStyles[i]);
			}
		}
		
		// Keys that always update the current edge style regardless of selection
		var alwaysEdgeStyles = ['edgeStyle', 'startArrow', 'startFill', 'startSize', 'endArrow',
			'endFill', 'endSize'];
		
		// Keys that are ignored together (if one appears all are ignored)
		var keyGroups = [['startArrow', 'startFill', 'endArrow', 'endFill'],
						 ['startSize', 'endSize'],
						 ['sourcePerimeterSpacing', 'targetPerimeterSpacing'],
		                 ['strokeColor', 'strokeWidth'],
		                 ['fillColor', 'gradientColor', 'gradientDirection'],
		                 ['opacity'],
		                 ['html']];
		
		// Adds all keys used above to the styles array
		for (var i = 0; i < keyGroups.length; i++)
		{
			for (var j = 0; j < keyGroups[i].length; j++)
			{
				styles.push(keyGroups[i][j]);
			}
		}
		
		for (var i = 0; i < connectStyles.length; i++)
		{
			if (mxUtils.indexOf(styles, connectStyles[i]) < 0)
			{
				styles.push(connectStyles[i]);
			}
		}
		
		// Implements a global current style for edges and vertices that is applied to new cells
		var insertHandler = function(cells, asText, model, vertexStyle, edgeStyle, applyAll, recurse)
		{
			vertexStyle = (vertexStyle != null) ? vertexStyle : graph.currentVertexStyle;
			edgeStyle = (edgeStyle != null) ? edgeStyle : graph.currentEdgeStyle;
			applyAll = (applyAll != null) ? applyAll : true;
			
			model = (model != null) ? model : graph.getModel();
			
			if (recurse)
			{
				var temp = [];
				
				for (var i = 0; i < cells.length; i++)
				{
					temp = temp.concat(model.getDescendants(cells[i]));
				}
				
				cells = temp;				
			}
			
			model.beginUpdate();
			try
			{
				for (var i = 0; i < cells.length; i++)
				{
					var cell = cells[i];
					var appliedStyles;

					if (asText)
					{
						// Applies only basic text styles
						appliedStyles = ['fontSize', 'fontFamily', 'fontColor'];
					}
					else
					{
						// Removes styles defined in the cell style from the styles to be applied
						var cellStyle = model.getStyle(cell);
						var tokens = (cellStyle != null) ? cellStyle.split(';') : [];
						appliedStyles = styles.slice();
						
						for (var j = 0; j < tokens.length; j++)
						{
							var tmp = tokens[j];
					 		var pos = tmp.indexOf('=');
					 					 		
					 		if (pos >= 0)
					 		{
					 			var key = tmp.substring(0, pos);
					 			var index = mxUtils.indexOf(appliedStyles, key);
					 			
					 			if (index >= 0)
					 			{
					 				appliedStyles.splice(index, 1);
					 			}
					 			
					 			// Handles special cases where one defined style ignores other styles
					 			for (var k = 0; k < keyGroups.length; k++)
					 			{
					 				var group = keyGroups[k];
					 				
					 				if (mxUtils.indexOf(group, key) >= 0)
					 				{
					 					for (var l = 0; l < group.length; l++)
					 					{
								 			var index2 = mxUtils.indexOf(appliedStyles, group[l]);
								 			
								 			if (index2 >= 0)
								 			{
								 				appliedStyles.splice(index2, 1);
								 			}
					 					}
					 				}
					 			}
					 		}
						}
					}
					
					// Applies the current style to the cell
					var edge = model.isEdge(cell);
					var current = (edge) ? edgeStyle : vertexStyle;
					var newStyle = model.getStyle(cell);

					for (var j = 0; j < appliedStyles.length; j++)
					{
						var key = appliedStyles[j];
						var styleValue = current[key];
	
						if (styleValue != null && key != 'edgeStyle' && (key != 'shape' || edge))
						{
							// Special case: Connect styles are not applied here but in the connection handler
							if (!edge || applyAll || mxUtils.indexOf(ignoredEdgeStyles, key) < 0)
							{
								newStyle = mxUtils.setStyle(newStyle, key, styleValue);
							}
						}
					}

					if (Editor.simpleLabels)
					{
						newStyle = mxUtils.setStyle(mxUtils.setStyle(
							newStyle, 'html', null), 'whiteSpace', null);
					}
					
					model.setStyle(cell, newStyle);
				}
			}
			finally
			{
				model.endUpdate();
			}

			return cells;
		};
	
		graph.addListener('cellsInserted', function(sender, evt)
		{
			insertHandler(evt.getProperty('cells'), null, null, null, null, true, true);
		});
		
		graph.addListener('textInserted', function(sender, evt)
		{
			insertHandler(evt.getProperty('cells'), true);
		});
		
		this.insertHandler = insertHandler;
		
		this.createDivs();
		this.createUi();
		this.refresh();

		// Disables HTML and text selection
		var textEditing =  mxUtils.bind(this, function(evt)
		{
			if (evt == null)
			{
				evt = window.event;
			}
			
			return graph.isEditing() || (evt != null && this.isSelectionAllowed(evt));
		});
	
		// Disables text selection while not editing and no dialog visible
		if (this.container == document.body)
		{
			this.menubarContainer.onselectstart = textEditing;
			this.menubarContainer.onmousedown = textEditing;
			this.toolbarContainer.onselectstart = textEditing;
			this.toolbarContainer.onmousedown = textEditing;
			this.diagramContainer.onselectstart = textEditing;
			this.diagramContainer.onmousedown = textEditing;
			this.sidebarContainer.onselectstart = textEditing;
			this.sidebarContainer.onmousedown = textEditing;
			this.formatContainer.onselectstart = textEditing;
			this.formatContainer.onmousedown = textEditing;
			this.footerContainer.onselectstart = textEditing;
			this.footerContainer.onmousedown = textEditing;
			
			if (this.tabContainer != null)
			{
				// Mouse down is needed for drag and drop
				this.tabContainer.onselectstart = textEditing;
			}
		}
		
		// And uses built-in context menu while editing
		if (!this.editor.chromeless || this.editor.editable)
		{
			// Allows context menu for links in hints
			var linkHandler = function(evt)
			{
				if (evt != null)
				{
					var source = mxEvent.getSource(evt);
					
					if (source.nodeName == 'A')
					{
						while (source != null)
						{
							if (source.className == 'geHint')
							{
								return true;
							}
							
							source = source.parentNode;
						}
					}
				}
				
				return textEditing(evt);
			};
			
			if (mxClient.IS_IE && (typeof(document.documentMode) === 'undefined' || document.documentMode < 9))
			{
				mxEvent.addListener(this.diagramContainer, 'contextmenu', linkHandler);
			}
			else
			{
				// Allows browser context menu outside of diagram and sidebar
				this.diagramContainer.oncontextmenu = linkHandler;
			}
		}
		else
		{
			graph.panningHandler.usePopupTrigger = false;
		}
	
		// Contains the main graph instance inside the given panel
		graph.init(this.diagramContainer);
	
	    // Improves line wrapping for in-place editor
	    if (mxClient.IS_SVG && graph.view.getDrawPane() != null)
	    {
	        var root = graph.view.getDrawPane().ownerSVGElement;
	        
	        if (root != null)
	        {
	            root.style.position = 'absolute';
	        }
	    }
	    
		// Creates hover icons
		this.hoverIcons = this.createHoverIcons();
		
		// Hides hover icons when cells are moved
		if (graph.graphHandler != null)
		{
			var graphHandlerStart = graph.graphHandler.start;
			
			graph.graphHandler.start = function()
			{
				if (ui.hoverIcons != null)
				{
					ui.hoverIcons.reset();
				}
				
				graphHandlerStart.apply(this, arguments);
			};
		}
		
		// Adds tooltip when mouse is over scrollbars to show space-drag panning option
		mxEvent.addListener(this.diagramContainer, 'mousemove', mxUtils.bind(this, function(evt)
		{
			var off = mxUtils.getOffset(this.diagramContainer);
			
			if (mxEvent.getClientX(evt) - off.x - this.diagramContainer.clientWidth > 0 ||
				mxEvent.getClientY(evt) - off.y - this.diagramContainer.clientHeight > 0)
			{
				this.diagramContainer.setAttribute('title', mxResources.get('panTooltip'));
			}
			else
			{
				this.diagramContainer.removeAttribute('title');
			}
		}));
	
	   	// Escape key hides dialogs, adds space+drag panning
		var spaceKeyPressed = false;
		
		// Overrides hovericons to disable while space key is pressed
		var hoverIconsIsResetEvent = this.hoverIcons.isResetEvent;
		
		this.hoverIcons.isResetEvent = function(evt, allowShift)
		{
			return spaceKeyPressed || hoverIconsIsResetEvent.apply(this, arguments);
		};
		
		this.keydownHandler = mxUtils.bind(this, function(evt)
		{
			if (evt.which == 32 /* Space */ && !graph.isEditing())
			{
				spaceKeyPressed = true;
				this.hoverIcons.reset();
				graph.container.style.cursor = 'move';
				
				// Disables scroll after space keystroke with scrollbars
				if (!graph.isEditing() && mxEvent.getSource(evt) == graph.container)
				{
					mxEvent.consume(evt);
				}
			}
			else if (!mxEvent.isConsumed(evt) && evt.keyCode == 27 /* Escape */)
			{
				this.hideDialog(null, true);
			}
		});
	   	
		mxEvent.addListener(document, 'keydown', this.keydownHandler);
		
		this.keyupHandler = mxUtils.bind(this, function(evt)
		{
			graph.container.style.cursor = '';
			spaceKeyPressed = false;
		});
	
		mxEvent.addListener(document, 'keyup', this.keyupHandler);
	    
	    // Forces panning for middle and right mouse buttons
		var panningHandlerIsForcePanningEvent = graph.panningHandler.isForcePanningEvent;
		graph.panningHandler.isForcePanningEvent = function(me)
		{
			// Ctrl+left button is reported as right button in FF on Mac
			return panningHandlerIsForcePanningEvent.apply(this, arguments) ||
				spaceKeyPressed || (mxEvent.isMouseEvent(me.getEvent()) &&
				(this.usePopupTrigger || !mxEvent.isPopupTrigger(me.getEvent())) &&
				((!mxEvent.isControlDown(me.getEvent()) &&
				mxEvent.isRightMouseButton(me.getEvent())) ||
				mxEvent.isMiddleMouseButton(me.getEvent())));
		};
	
		// Ctrl/Cmd+Enter applies editing value except in Safari where Ctrl+Enter creates
		// a new line (while Enter creates a new paragraph and Shift+Enter stops)
		var cellEditorIsStopEditingEvent = graph.cellEditor.isStopEditingEvent;
		graph.cellEditor.isStopEditingEvent = function(evt)
		{
			return cellEditorIsStopEditingEvent.apply(this, arguments) ||
				(evt.keyCode == 13 && ((!mxClient.IS_SF && mxEvent.isControlDown(evt)) ||
				(mxClient.IS_MAC && mxEvent.isMetaDown(evt)) ||
				(mxClient.IS_SF && mxEvent.isShiftDown(evt))));
		};
				
		// Adds space+wheel for zoom
		var graphIsZoomWheelEvent = graph.isZoomWheelEvent;
		
		graph.isZoomWheelEvent = function()
		{
			return spaceKeyPressed || graphIsZoomWheelEvent.apply(this, arguments);
		};
		
		// Switches toolbar for text editing
		var textMode = false;
		var fontMenu = null;
		var sizeMenu = null;
		var nodes = null;
		
		var updateToolbar = mxUtils.bind(this, function()
		{
			if (this.toolbar != null && textMode != graph.cellEditor.isContentEditing())
			{
				var node = this.toolbar.container.firstChild;
				var newNodes = [];
				
				while (node != null)
				{
					var tmp = node.nextSibling;
					
					if (mxUtils.indexOf(this.toolbar.staticElements, node) < 0)
					{
						node.parentNode.removeChild(node);
						newNodes.push(node);
					}
					
					node = tmp;
				}
				
				// Saves references to special items
				var tmp1 = this.toolbar.fontMenu;
				var tmp2 = this.toolbar.sizeMenu;
				
				if (nodes == null)
				{
					this.toolbar.createTextToolbar();
				}
				else
				{
					for (var i = 0; i < nodes.length; i++)
					{
						this.toolbar.container.appendChild(nodes[i]);
					}
					
					// Restores references to special items
					this.toolbar.fontMenu = fontMenu;
					this.toolbar.sizeMenu = sizeMenu;
				}
				
				textMode = graph.cellEditor.isContentEditing();
				fontMenu = tmp1;
				sizeMenu = tmp2;
				nodes = newNodes;
			}
		});
	
		var ui = this;
		
		// Overrides cell editor to update toolbar
		var cellEditorStartEditing = graph.cellEditor.startEditing;
		graph.cellEditor.startEditing = function()
		{
			cellEditorStartEditing.apply(this, arguments);
			updateToolbar();
			
			if (graph.cellEditor.isContentEditing())
			{
				var updating = false;
				
				var updateCssHandler = function()
				{
					if (!updating)
					{
						updating = true;
					
						window.setTimeout(function()
						{
							var node = graph.getSelectedEditingElement();

							if (node != null)
							{
								var css = mxUtils.getCurrentStyle(node);
		
								if (css != null && ui.toolbar != null)
								{
									ui.toolbar.setFontName(Graph.stripQuotes(css.fontFamily));
									ui.toolbar.setFontSize(parseInt(css.fontSize));
								}
							}
							
							updating = false;
						}, 0);
					}
				};
				
				mxEvent.addListener(graph.cellEditor.textarea, 'input', updateCssHandler)
				mxEvent.addListener(graph.cellEditor.textarea, 'touchend', updateCssHandler);
				mxEvent.addListener(graph.cellEditor.textarea, 'mouseup', updateCssHandler);
				mxEvent.addListener(graph.cellEditor.textarea, 'keyup', updateCssHandler);
				updateCssHandler();
			}
		};
		
		// Updates toolbar and handles possible errors
		var cellEditorStopEditing = graph.cellEditor.stopEditing;
		graph.cellEditor.stopEditing = function(cell, trigger)
		{
			try
			{
				cellEditorStopEditing.apply(this, arguments);
				updateToolbar();
			}
			catch (e)
			{
				ui.handleError(e);
			}
		};
		
	    // Enables scrollbars and sets cursor style for the container
		graph.container.setAttribute('tabindex', '0');
	   	graph.container.style.cursor = 'default';

		// Workaround for page scroll if embedded via iframe
		if (window.self === window.top && graph.container.parentNode != null)
		{
			try
			{
				graph.container.focus();
			}
			catch (e)
			{
				// ignores error in old versions of IE
			}
		}
	
	   	// Keeps graph container focused on mouse down
	   	var graphFireMouseEvent = graph.fireMouseEvent;
	   	graph.fireMouseEvent = function(evtName, me, sender)
	   	{
	   		if (evtName == mxEvent.MOUSE_DOWN)
	   		{
	   			this.container.focus();
	   		}
	   		
	   		graphFireMouseEvent.apply(this, arguments);
	   	};
	
	   	// Configures automatic expand on mouseover
		graph.popupMenuHandler.autoExpand = true;
	
	    // Installs context menu
		if (this.menus != null)
		{
			graph.popupMenuHandler.factoryMethod = mxUtils.bind(this, function(menu, cell, evt)
			{
				this.menus.createPopupMenu(menu, cell, evt);
			});
		}
		
		// Hides context menu
		mxEvent.addGestureListeners(document, mxUtils.bind(this, function(evt)
		{
			graph.popupMenuHandler.hideMenu();
		}));
	
	    // Create handler for key events
		this.keyHandler = this.createKeyHandler(editor);
	    
		// Getter for key handler
		this.getKeyHandler = function()
		{
			return keyHandler;
		};

		graph.connectionHandler.addListener(mxEvent.CONNECT, function(sender, evt)
		{
			var cells = [evt.getProperty('cell')];
			
			if (evt.getProperty('terminalInserted'))
			{
				cells.push(evt.getProperty('terminal'));

				window.setTimeout(function()
				{
					if (ui.hoverIcons != null)
					{
						ui.hoverIcons.update(graph.view.getState(cells[cells.length - 1]));
					}
				}, 0);
			}
			
			insertHandler(cells);
		});

		this.addListener('styleChanged', mxUtils.bind(this, function(sender, evt)
		{
			// Checks if edges and/or vertices were modified
			var cells = evt.getProperty('cells');
			var vertex = false;
			var edge = false;
			
			if (cells.length > 0)
			{
				for (var i = 0; i < cells.length; i++)
				{
					vertex = graph.getModel().isVertex(cells[i]) || vertex;
					edge = graph.getModel().isEdge(cells[i]) || edge;
					
					if (edge && vertex)
					{
						break;
					}
				}
			}
			else
			{
				vertex = true;
				edge = true;
			}
			
			var keys = evt.getProperty('keys');
			var values = evt.getProperty('values');
	
			for (var i = 0; i < keys.length; i++)
			{
				var common = mxUtils.indexOf(valueStyles, keys[i]) >= 0;
				
				// Ignores transparent stroke colors
				if (keys[i] != 'strokeColor' || values[i] != null && values[i] != 'none')
				{
					// Special case: Edge style and shape
					if (mxUtils.indexOf(connectStyles, keys[i]) >= 0)
					{
						if (edge || mxUtils.indexOf(alwaysEdgeStyles, keys[i]) >= 0)
						{
							if (values[i] == null)
							{
								delete graph.currentEdgeStyle[keys[i]];
							}
							else
							{
								graph.currentEdgeStyle[keys[i]] = values[i];
							}
						}
						// Uses style for vertex if defined in styles
						else if (vertex && mxUtils.indexOf(styles, keys[i]) >= 0)
						{
							if (values[i] == null)
							{
								delete graph.currentVertexStyle[keys[i]];
							}
							else
							{
								graph.currentVertexStyle[keys[i]] = values[i];
							}
						}
					}
					else if (mxUtils.indexOf(styles, keys[i]) >= 0)
					{
						if (vertex || common)
						{
							if (values[i] == null)
							{
								delete graph.currentVertexStyle[keys[i]];
							}
							else
							{
								graph.currentVertexStyle[keys[i]] = values[i];
							}
						}
						
						if (edge || common || mxUtils.indexOf(alwaysEdgeStyles, keys[i]) >= 0)
						{
							if (values[i] == null)
							{
								delete graph.currentEdgeStyle[keys[i]];
							}
							else
							{
								graph.currentEdgeStyle[keys[i]] = values[i];
							}
						}
					}
				}
			}

			if (this.toolbar != null)
			{
				this.toolbar.setFontName(graph.currentVertexStyle['fontFamily'] || Menus.prototype.defaultFont);
				this.toolbar.setFontSize(graph.currentVertexStyle['fontSize'] || Menus.prototype.defaultFontSize);
				
				if (this.toolbar.edgeStyleMenu != null)
				{
					// Updates toolbar icon for edge style
					var edgeStyleDiv = this.toolbar.edgeStyleMenu.getElementsByTagName('div')[0];
	
					if (graph.currentEdgeStyle['edgeStyle'] == 'orthogonalEdgeStyle' && graph.currentEdgeStyle['curved'] == '1')
					{
						edgeStyleDiv.className = 'geSprite geSprite-curved';
					}
					else if (graph.currentEdgeStyle['edgeStyle'] == 'straight' || graph.currentEdgeStyle['edgeStyle'] == 'none' ||
							graph.currentEdgeStyle['edgeStyle'] == null)
					{
						edgeStyleDiv.className = 'geSprite geSprite-straight';
					}
					else if (graph.currentEdgeStyle['edgeStyle'] == 'entityRelationEdgeStyle')
					{
						edgeStyleDiv.className = 'geSprite geSprite-entity';
					}
					else if (graph.currentEdgeStyle['edgeStyle'] == 'elbowEdgeStyle')
					{
						edgeStyleDiv.className = 'geSprite geSprite-' + ((graph.currentEdgeStyle['elbow'] == 'vertical') ?
							'verticalelbow' : 'horizontalelbow');
					}
					else if (graph.currentEdgeStyle['edgeStyle'] == 'isometricEdgeStyle')
					{
						edgeStyleDiv.className = 'geSprite geSprite-' + ((graph.currentEdgeStyle['elbow'] == 'vertical') ?
							'verticalisometric' : 'horizontalisometric');
					}
					else
					{
						edgeStyleDiv.className = 'geSprite geSprite-orthogonal';
					}
				}
				
				if (this.toolbar.edgeShapeMenu != null)
				{
					// Updates icon for edge shape
					var edgeShapeDiv = this.toolbar.edgeShapeMenu.getElementsByTagName('div')[0];
					
					if (graph.currentEdgeStyle['shape'] == 'link')
					{
						edgeShapeDiv.className = 'geSprite geSprite-linkedge';
					}
					else if (graph.currentEdgeStyle['shape'] == 'flexArrow')
					{
						edgeShapeDiv.className = 'geSprite geSprite-arrow';
					}
					else if (graph.currentEdgeStyle['shape'] == 'arrow')
					{
						edgeShapeDiv.className = 'geSprite geSprite-simplearrow';
					}
					else
					{
						edgeShapeDiv.className = 'geSprite geSprite-connection';
					}
				}
				
				// Updates icon for optinal line start shape
				if (this.toolbar.lineStartMenu != null)
				{
					var lineStartDiv = this.toolbar.lineStartMenu.getElementsByTagName('div')[0];
					
					lineStartDiv.className = this.getCssClassForMarker('start',
							graph.currentEdgeStyle['shape'], graph.currentEdgeStyle[mxConstants.STYLE_STARTARROW],
							mxUtils.getValue(graph.currentEdgeStyle, 'startFill', '1'));
				}
	
				// Updates icon for optinal line end shape
				if (this.toolbar.lineEndMenu != null)
				{
					var lineEndDiv = this.toolbar.lineEndMenu.getElementsByTagName('div')[0];
					
					lineEndDiv.className = this.getCssClassForMarker('end',
							graph.currentEdgeStyle['shape'], graph.currentEdgeStyle[mxConstants.STYLE_ENDARROW],
							mxUtils.getValue(graph.currentEdgeStyle, 'endFill', '1'));
				}
			}
		}));
		
		// Update font size and font family labels
		if (this.toolbar != null)
		{
			var update = mxUtils.bind(this, function()
			{
				var ff = graph.currentVertexStyle['fontFamily'] || 'Helvetica';
				var fs = String(graph.currentVertexStyle['fontSize'] || '12');
			    	var state = graph.getView().getState(graph.getSelectionCell());
			    	
			    	if (state != null)
			    	{
			    		ff = state.style[mxConstants.STYLE_FONTFAMILY] || ff;
			    		fs = state.style[mxConstants.STYLE_FONTSIZE] || fs;
			    		
			    		if (ff.length > 10)
			    		{
			    			ff = ff.substring(0, 8) + '...';
			    		}
			    	}
			    	
			    	this.toolbar.setFontName(ff);
			    	this.toolbar.setFontSize(fs);
			});
			
		    graph.getSelectionModel().addListener(mxEvent.CHANGE, update);
		    graph.getModel().addListener(mxEvent.CHANGE, update);
		}
		
		// Makes sure the current layer is visible when cells are added
		graph.addListener(mxEvent.CELLS_ADDED, function(sender, evt)
		{
			var cells = evt.getProperty('cells');
			var parent = evt.getProperty('parent');
			
			if (parent != null && graph.getModel().isLayer(parent) &&
				!graph.isCellVisible(parent) && cells != null &&
				cells.length > 0)
			{
				graph.getModel().setVisible(parent, true);
			}
		});
		
		// Global handler to hide the current menu
		this.gestureHandler = mxUtils.bind(this, function(evt)
		{
			if (this.currentMenu != null && mxEvent.getSource(evt) != this.currentMenu.div)
			{
				this.hideCurrentMenu();
			}
		});
		
		mxEvent.addGestureListeners(document, this.gestureHandler);
	
		// Updates the editor UI after the window has been resized or the orientation changes
		// Timeout is workaround for old IE versions which have a delay for DOM client sizes.
		// Should not use delay > 0 to avoid handle multiple repaints during window resize
		this.resizeHandler = mxUtils.bind(this, function()
	   	{
	   		window.setTimeout(mxUtils.bind(this, function()
	   		{
	   			if (this.editor.graph != null)
	   			{
	   				this.refresh();
	   			}
	   		}), 0);
	   	});
		
	   	mxEvent.addListener(window, 'resize', this.resizeHandler);
	   	
	   	this.orientationChangeHandler = mxUtils.bind(this, function()
	   	{
	   		this.refresh();
	   	});
	   	
	   	mxEvent.addListener(window, 'orientationchange', this.orientationChangeHandler);
	   	
		// Workaround for bug on iOS see
		// http://stackoverflow.com/questions/19012135/ios-7-ipad-safari-landscape-innerheight-outerheight-layout-issue
		if (mxClient.IS_IOS && !window.navigator.standalone && typeof Menus !== 'undefined')
		{
			this.scrollHandler = mxUtils.bind(this, function()
		   	{
		   		window.scrollTo(0, 0);
		   	});
			
		   	mxEvent.addListener(window, 'scroll', this.scrollHandler);
		}
	
		/**
		 * Sets the initial scrollbar locations after a file was loaded.
		 */
		this.editor.addListener('resetGraphView', mxUtils.bind(this, function()
		{
			this.resetScrollbars();
		}));
		
		/**
		 * Repaints the grid.
		 */
		this.addListener('gridEnabledChanged', mxUtils.bind(this, function()
		{
			graph.view.validateBackground();
		}));
		
		this.addListener('backgroundColorChanged', mxUtils.bind(this, function()
		{
			graph.view.validateBackground();
		}));
	
		/**
		 * Repaints the grid.
		 */
		graph.addListener('gridSizeChanged', mxUtils.bind(this, function()
		{
			if (graph.isGridEnabled())
			{
				graph.view.validateBackground();
			}
		}));
		
	   	// Resets UI, updates action and menu states
	   	this.editor.resetGraph();
	}

	this.init();
	
	if (!graph.standalone)
	{
		this.open();
	}
};

/**
 * Global config that specifies if the compact UI elements should be used.
 */
 EditorUi.compactUi = true;

 /**
  * Static method for pasing PNG files.
  */
 EditorUi.parsePng = function(f, fn, error)
 {
	 var pos = 0;
	 
	 function fread(d, count)
	 {
		 var start = pos;
		 pos += count;
		 
		 return d.substring(start, pos);
	 };
	 
	 // Reads unsigned long 32 bit big endian
	 function _freadint(d)
	 {
		 var bytes = fread(d, 4);
		 
		 return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
			 (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
	 };
	 
	 // Checks signature
	 if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
	 {
		 if (error != null)
		 {
			 error();
		 }
		 
		 return;
	 }
	 
	 // Reads header chunk
	 fread(f,4);
	 
	 if (fread(f,4) != 'IHDR')
	 {
		 if (error != null)
		 {
			 error();
		 }
		 
		 return;
	 }
	 
	 fread(f, 17);
	 
	 do
	 {
		 var n = _freadint(f);
		 var type = fread(f,4);
		 
		 if (fn != null)
		 {
			 if (fn(pos - 8, type, n))
			 {
				 break;
			 }
		 }
		 
		 value = fread(f,n);
		 fread(f,4);
		 
		 if (type == 'IEND')
		 {
			 break;
		 }
	 }
	 while (n);
 };
 
// Extends mxEventSource
mxUtils.extend(EditorUi, mxEventSource);

/**
 * Specifies the size of the split bar.
 */
EditorUi.prototype.splitSize = (mxClient.IS_TOUCH || mxClient.IS_POINTER) ? 12 : 8;

/**
 * Specifies the height of the menubar. Default is 30.
 */
EditorUi.prototype.menubarHeight = 30;

/**
 * Specifies the width of the format panel should be enabled. Default is true.
 */
EditorUi.prototype.formatEnabled = true;

/**
 * Specifies the width of the format panel. Default is 240.
 */
EditorUi.prototype.formatWidth = 240;

/**
 * Specifies the height of the toolbar. Default is 38.
 */
EditorUi.prototype.toolbarHeight = 38;

/**
 * Specifies the height of the footer. Default is 28.
 */
EditorUi.prototype.footerHeight = 28;

/**
 * Specifies the height of the optional sidebarFooterContainer. Default is 34.
 */
EditorUi.prototype.sidebarFooterHeight = 34;

/**
 * Specifies the position of the horizontal split bar. Default is 240 or 118 for
 * screen widths <= 640px.
 */
EditorUi.prototype.hsplitPosition = (screen.width <= 640) ? 118 : ((urlParams['sidebar-entries'] != 'large') ? 212 : 240);

/**
 * Specifies if animations are allowed in <executeLayout>. Default is true.
 */
EditorUi.prototype.allowAnimation = true;

/**
 * Default is 2.
 */
EditorUi.prototype.lightboxMaxFitScale = 2;

/**
 * Default is 4.
 */
EditorUi.prototype.lightboxVerticalDivider = 4;

/**
 * Specifies if single click on horizontal split should collapse sidebar. Default is false.
 */
EditorUi.prototype.hsplitClickEnabled = false;

/**
 * Installs the listeners to update the action states.
 */
EditorUi.prototype.init = function()
{
	var graph = this.editor.graph;
	
	if (!graph.standalone)
	{
		if (urlParams['shape-picker'] != '0')
		{
			this.installShapePicker();
		}
		
		// Hides tooltips and connection points when scrolling
		mxEvent.addListener(graph.container, 'scroll', mxUtils.bind(this, function()
		{
			graph.tooltipHandler.hide();
			
			if (graph.connectionHandler != null && graph.connectionHandler.constraintHandler != null)
			{
				graph.connectionHandler.constraintHandler.reset();
			}
		}));
		
		// Hides tooltip on escape
		graph.addListener(mxEvent.ESCAPE, mxUtils.bind(this, function()
		{
			graph.tooltipHandler.hide();
			var rb = graph.getRubberband();
			
			if (rb != null)
			{
				rb.cancel();
			}
		}));
		
		mxEvent.addListener(graph.container, 'keydown', mxUtils.bind(this, function(evt)
		{
			this.onKeyDown(evt);
		}));
		
		mxEvent.addListener(graph.container, 'keypress', mxUtils.bind(this, function(evt)
		{
			this.onKeyPress(evt);
		}));
	
		// Updates action states
		this.addUndoListener();
		this.addBeforeUnloadListener();
		
		graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function()
		{
			this.updateActionStates();
		}));
		
		graph.getModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function()
		{
			this.updateActionStates();
		}));
		
		// Changes action states after change of default parent
		var graphSetDefaultParent = graph.setDefaultParent;
		var ui = this;
		
		this.editor.graph.setDefaultParent = function()
		{
			graphSetDefaultParent.apply(this, arguments);
			ui.updateActionStates();
		};
		
		// Hack to make editLink available in vertex handler
		graph.editLink = ui.actions.get('editLink').funct;
		
		this.updateActionStates();
		this.initClipboard();
		this.initCanvas();
		
		if (this.format != null)
		{
			this.format.init();
		}
	}
};

/**
 * Returns information about the current selection.
 */
EditorUi.prototype.clearSelectionState = function()
{
	this.selectionState = null;
};

/**
 * Returns information about the current selection.
 */
EditorUi.prototype.getSelectionState = function()
{
	if (this.selectionState == null)
	{
		this.selectionState = this.createSelectionState();
	}
	
	return this.selectionState;
};

/**
 * Returns information about the current selection.
 */
EditorUi.prototype.createSelectionState = function()
{
	var graph = this.editor.graph;
	var cells = graph.getSelectionCells();
	var result = this.initSelectionState();
	var initial = true;
	
	for (var i = 0; i < cells.length; i++)
	{
		var style = graph.getCurrentCellStyle(cells[i]);
	
		if (mxUtils.getValue(style, mxConstants.STYLE_EDITABLE, '1') != '0')
		{
			this.updateSelectionStateForCell(result, cells[i], cells, initial);
			initial = false;
		}
	}

	this.updateSelectionStateForTableCells(result);
	
	return result;
};

/**
 * Returns information about the current selection.
 */
EditorUi.prototype.initSelectionState = function()
{
	return {vertices: [], edges: [], cells: [], x: null, y: null, width: null, height: null,
		style: {}, containsImage: false, containsLabel: false, fill: true, glass: true,
		rounded: true, autoSize: false, image: true, shadow: true, lineJumps: true, resizable: true,
		table: false, cell: false, row: false, movable: true, rotatable: true, stroke: true,
		swimlane: false, unlocked: this.editor.graph.isEnabled(), connections: false};
};

/**
 * Adds information about current selected table cells range.
 */
EditorUi.prototype.updateSelectionStateForTableCells = function(result)
{
	if (result.cells.length > 1 && result.cell)
	{
		var cells = mxUtils.sortCells(result.cells);
		var model = this.editor.graph.model;
		var parent = model.getParent(cells[0]);
		var table = model.getParent(parent);
		var col = parent.getIndex(cells[0]);
		var row = table.getIndex(parent);
		var lastspan = null;
		var colspan = 1;
		var rowspan = 1;
		var index = 0;

		var nextRowCell = (row < table.getChildCount() - 1) ?
			model.getChildAt(model.getChildAt(
				table, row + 1), col) : null;
		
		while (index < cells.length - 1)
		{
			var next = cells[++index];
			
			if (nextRowCell != null && nextRowCell == next &&
				(lastspan == null || colspan == lastspan))
			{
				lastspan = colspan;
				colspan = 0;
				rowspan++;
				parent = model.getParent(nextRowCell);
				nextRowCell = (row + rowspan < table.getChildCount()) ?
					model.getChildAt(model.getChildAt(
						table, row + rowspan), col) : null;
			}
			
			var state = this.editor.graph.view.getState(next);

			if (next == model.getChildAt(parent, col + colspan) && state != null &&
				mxUtils.getValue(state.style, 'colspan', 1) == 1 &&
				mxUtils.getValue(state.style, 'rowspan', 1) == 1)
			{
				colspan++;
			}
			else
			{
				break;
			}
		}

		if (index == rowspan * colspan - 1)
		{
			result.mergeCell = cells[0];
			result.colspan = colspan;
			result.rowspan = rowspan;
		}
	}
};

/**
 * Returns information about the current selection.
 */
EditorUi.prototype.updateSelectionStateForCell = function(result, cell, cells, initial)
{
	var graph = this.editor.graph;
	result.cells.push(cell);
	
	if (graph.getModel().isVertex(cell))
	{
		result.connections = graph.model.getEdgeCount(cell) > 0;
		result.unlocked = result.unlocked && !graph.isCellLocked(cell);
		result.resizable = result.resizable && graph.isCellResizable(cell);
		result.rotatable = result.rotatable && graph.isCellRotatable(cell);
		result.movable = result.movable && graph.isCellMovable(cell) &&
			!graph.isTableRow(cell) && !graph.isTableCell(cell);
		result.swimlane = result.swimlane || graph.isSwimlane(cell);
		result.table = result.table || graph.isTable(cell);
		result.cell = result.cell || graph.isTableCell(cell);
		result.row = result.row || graph.isTableRow(cell);
		result.vertices.push(cell);
		var geo = graph.getCellGeometry(cell);
		
		if (geo != null)
		{
			if (geo.width > 0)
			{
				if (result.width == null)
				{
					result.width = geo.width;
				}
				else if (result.width != geo.width)
				{
					result.width = '';
				}
			}
			else
			{
				result.containsLabel = true;
			}
			
			if (geo.height > 0)
			{
				if (result.height == null)
				{
					result.height = geo.height;
				}
				else if (result.height != geo.height)
				{
					result.height = '';
				}
			}
			else
			{
				result.containsLabel = true;
			}
			
			if (!geo.relative || geo.offset != null)
			{
				var x = (geo.relative) ? geo.offset.x : geo.x;
				var y = (geo.relative) ? geo.offset.y : geo.y;
				
				if (result.x == null)
				{
					result.x = x;
				}
				else if (result.x != x)
				{
					result.x = '';
				}
				
				if (result.y == null)
				{
					result.y = y;
				}
				else if (result.y != y)
				{
					result.y = '';
				}
			}
		}
	}
	else if (graph.getModel().isEdge(cell))
	{
		result.edges.push(cell);
		result.connections = true;
		result.resizable = false;
		result.rotatable = false;
		result.movable = false;
	}

	var state = graph.view.getState(cell);
	
	if (state != null)
	{
		result.autoSize = result.autoSize || graph.isAutoSizeState(state);
		result.glass = result.glass && graph.isGlassState(state);
		result.rounded = result.rounded && graph.isRoundedState(state);
		result.lineJumps = result.lineJumps && graph.isLineJumpState(state);
		result.image = result.image && graph.isImageState(state);
		result.shadow = result.shadow && graph.isShadowState(state);
		result.fill = result.fill && graph.isFillState(state);
		result.stroke = result.stroke && graph.isStrokeState(state);
		
		var shape = mxUtils.getValue(state.style, mxConstants.STYLE_SHAPE, null);
		result.containsImage = result.containsImage || shape == 'image';
		graph.mergeStyle(state.style, result.style, initial);
	}
};

/**
 * Returns true if the given event should start editing. This implementation returns true.
 */
EditorUi.prototype.installShapePicker = function()
{
	var graph = this.editor.graph;
	var ui = this;

	// Uses this event to process mouseDown to check the selection state before it is changed
	graph.addListener(mxEvent.FIRE_MOUSE_EVENT, mxUtils.bind(this, function(sender, evt)
	{
		if (evt.getProperty('eventName') == 'mouseDown')
		{
			ui.hideShapePicker();
		}
	}));

	var hidePicker = mxUtils.bind(this, function()
	{
		ui.hideShapePicker(true);
	});
	
	graph.addListener('wheel', hidePicker);
	graph.addListener(mxEvent.ESCAPE, hidePicker);
	graph.view.addListener(mxEvent.SCALE, hidePicker);
	graph.view.addListener(mxEvent.SCALE_AND_TRANSLATE, hidePicker);
	graph.getSelectionModel().addListener(mxEvent.CHANGE, hidePicker);
	
	// Counts as popup menu
	var popupMenuHandlerIsMenuShowing = graph.popupMenuHandler.isMenuShowing;
	 
	graph.popupMenuHandler.isMenuShowing = function()
	{
		return popupMenuHandlerIsMenuShowing.apply(this, arguments) || ui.shapePicker != null;
	};
	
	// Adds dbl click dialog for inserting shapes
	var graphDblClick = graph.dblClick;
	
	graph.dblClick = function(evt, cell)
	{
		if (this.isEnabled())
		{
			if (cell == null && ui.sidebar != null && !mxEvent.isShiftDown(evt) &&
				!graph.isCellLocked(graph.getDefaultParent()))
			{
				var pt = mxUtils.convertPoint(this.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
				mxEvent.consume(evt);

				// Asynchronous to avoid direct insert after double tap
				window.setTimeout(mxUtils.bind(this, function()
				{
					// TODO thingsKit 隐藏双击图层插入图形
					// ui.showShapePicker(pt.x, pt.y);
				}), 30);
			}
			else
			{
				graphDblClick.apply(this, arguments);
			}
		}
	};

	if (this.hoverIcons != null)
	{
		this.hoverIcons.addListener('reset', hidePicker);
		var hoverIconsDrag = this.hoverIcons.drag;
		
		this.hoverIcons.drag = function()
		{
			ui.hideShapePicker();
			hoverIconsDrag.apply(this, arguments);
		};
		
		var hoverIconsExecute = this.hoverIcons.execute;
		
		this.hoverIcons.execute = function(state, dir, me)
		{
			var evt = me.getEvent();
			
			if (!this.graph.isCloneEvent(evt) && !mxEvent.isShiftDown(evt))
			{
				this.graph.connectVertex(state.cell, dir, this.graph.defaultEdgeLength, evt, null, null, mxUtils.bind(this, function(x, y, execute)
				{
					var temp = graph.getCompositeParent(state.cell);
					var geo = graph.getCellGeometry(temp);
					me.consume();
					
					while (temp != null && graph.model.isVertex(temp) && geo != null && geo.relative)
					{
						cell = temp;
						temp = graph.model.getParent(cell)
						geo = graph.getCellGeometry(temp);
					}
					
					// Asynchronous to avoid direct insert after double tap
					window.setTimeout(mxUtils.bind(this, function()
					{
						ui.showShapePicker(me.getGraphX(), me.getGraphY(), temp, mxUtils.bind(this, function(cell)
						{
							execute(cell);
							
							if (ui.hoverIcons != null)
							{
								ui.hoverIcons.update(graph.view.getState(cell));
							}
						}), dir);
					}), 30);
				}), mxUtils.bind(this, function(result)
				{
					this.graph.selectCellsForConnectVertex(result, evt, this);
				}));
			}
			else
			{
				hoverIconsExecute.apply(this, arguments);
			}
		};

		var thread = null;

		this.hoverIcons.addListener('focus', mxUtils.bind(this, function(sender, evt)
		{
			if (thread != null)
			{
				window.clearTimeout(thread);
			}

			thread = window.setTimeout(mxUtils.bind(this, function()
			{
				var arrow = evt.getProperty('arrow');
				var dir = evt.getProperty('direction');
				var mouseEvent = evt.getProperty('event');

				var rect = arrow.getBoundingClientRect();
				var offset = mxUtils.getOffset(graph.container);
				var x = graph.container.scrollLeft + rect.x - offset.x;
				var y = graph.container.scrollTop + rect.y - offset.y;

				var temp = graph.getCompositeParent((this.hoverIcons.currentState != null) ?
					this.hoverIcons.currentState.cell : null);
				var div = ui.showShapePicker(x, y, temp, mxUtils.bind(this, function(cell)
				{
					if (cell != null)
					{
						graph.connectVertex(temp, dir, graph.defaultEdgeLength, mouseEvent, true, true, function(x, y, execute)
						{
							execute(cell);
								
							if (ui.hoverIcons != null)
							{
								ui.hoverIcons.update(graph.view.getState(cell));
							}
						}, function(cells)
						{
							graph.selectCellsForConnectVertex(cells);
						}, mouseEvent, this.hoverIcons);
					}
				}), dir, true);

				this.centerShapePicker(div, rect, x, y, dir);
				mxUtils.setOpacity(div, 30);

				mxEvent.addListener(div, 'mouseenter', function()
				{
					mxUtils.setOpacity(div, 100);
				});

				mxEvent.addListener(div, 'mouseleave', function()
				{
					ui.hideShapePicker();
				});
			}), Editor.shapePickerHoverDelay);
		}));

		this.hoverIcons.addListener('blur', mxUtils.bind(this, function(sender, evt)
		{
			if (thread != null)
			{
				window.clearTimeout(thread);
			}
		}));
	}
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.centerShapePicker = function(div, rect, x, y, dir)
{
	if (dir == mxConstants.DIRECTION_EAST || dir == mxConstants.DIRECTION_WEST)
	{
		div.style.width = '40px';
	}

	var r2 = div.getBoundingClientRect();

	if (dir == mxConstants.DIRECTION_NORTH)
	{
		x -= r2.width / 2 - 10;
		y -= r2.height + 6;
	}
	else if (dir == mxConstants.DIRECTION_SOUTH)
	{
		x -= r2.width / 2 - 10;
		y += rect.height + 6;
	}
	else if (dir == mxConstants.DIRECTION_WEST)
	{
		x -= r2.width + 6;
		y -= r2.height / 2 - 10;
	}
	else if (dir == mxConstants.DIRECTION_EAST)
	{
		x += rect.width + 6;
		y -= r2.height / 2 - 10;
	}

	div.style.left = x + 'px';
	div.style.top = y + 'px';
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.showShapePicker = function(x, y, source, callback, direction, hovering)
{
	var div = this.createShapePicker(x, y, source, callback, direction, mxUtils.bind(this, function()
	{	
		this.hideShapePicker();
	}), this.getCellsForShapePicker(source, hovering), hovering);
	
	if (div != null)
	{
		if (this.hoverIcons != null && !hovering)
		{
			this.hoverIcons.reset();
		}
		
		var graph = this.editor.graph;
		graph.popupMenuHandler.hideMenu();
		graph.tooltipHandler.hideTooltip();
		this.hideCurrentMenu();
		this.hideShapePicker();
		
		this.shapePickerCallback = callback;
		this.shapePicker = div;
	}

	return div;
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.createShapePicker = function(x, y, source, callback, direction, afterClick, cells, hovering)
{
	var div = null;
	
	if (cells != null && cells.length > 0)
	{
		var ui = this;
		var graph = this.editor.graph;
		div = document.createElement('div');
		var sourceState = graph.view.getState(source);
		var style = (source != null && (sourceState == null ||
			!graph.isTransparentState(sourceState))) ?
			graph.copyStyle(source) : null;
		
		// Do not place entry under pointer for touch devices
		var w = (cells.length < 6) ? cells.length * 35 : 140;
		div.className = 'geToolbarContainer geSidebarContainer';
		div.style.cssText = 'position:absolute;left:' + x + 'px;top:' + y +
			'px;width:' + w + 'px;border-radius:10px;padding:4px;text-align:center;' +
			'box-shadow:0px 0px 3px 1px #d1d1d1;padding: 6px 0 8px 0;' +
			'z-index: ' + mxPopupMenu.prototype.zIndex + 1 + ';';

		if (!hovering)
		{
			mxUtils.setPrefixedStyle(div.style, 'transform', 'translate(-22px,-22px)');
		}
		
		if (graph.background != null && graph.background != mxConstants.NONE)
		{
			div.style.backgroundColor = graph.background;
		}
		
		graph.container.appendChild(div);
		
		var addCell = mxUtils.bind(this, function(cell)
		{
			// Wrapper needed to catch events
			var node = document.createElement('a');
			node.className = 'geItem';
			node.style.cssText = 'position:relative;display:inline-block;position:relative;' +
				'width:30px;height:30px;cursor:pointer;overflow:hidden;padding:3px 0 0 3px;';
			div.appendChild(node);
			
			if (style != null && urlParams['sketch'] != '1')
			{
				this.sidebar.graph.pasteStyle(style, [cell]);
			}
			else
			{
				ui.insertHandler([cell], cell.value != '' && urlParams['sketch'] != '1', this.sidebar.graph.model);
			}
			
			this.sidebar.createThumb([cell], 25, 25, node, null, true, false, cell.geometry.width, cell.geometry.height);

			mxEvent.addListener(node, 'click', function()
			{
				var clone = graph.cloneCell(cell);
				
				if (callback != null)
				{
					callback(clone);
				}
				else
				{
					clone.geometry.x = graph.snap(Math.round(x / graph.view.scale) -
						graph.view.translate.x - cell.geometry.width / 2);
					clone.geometry.y = graph.snap(Math.round(y / graph.view.scale) -
						graph.view.translate.y - cell.geometry.height / 2);
					
					graph.model.beginUpdate();
					try
					{
						graph.addCell(clone);
					}
					finally
					{
						graph.model.endUpdate();
					}
					
					graph.setSelectionCell(clone);
					graph.scrollCellToVisible(clone);
					graph.startEditingAtCell(clone);
					
					if (ui.hoverIcons != null)
					{
						ui.hoverIcons.update(graph.view.getState(clone));
					}
				}
				
				if (afterClick != null)
				{
					afterClick();
				}
			});
		});
		
		for (var i = 0; i < (hovering ? Math.min(cells.length, 4) : cells.length); i++)
		{
			addCell(cells[i]);
		}
		
		var b = graph.container.scrollTop + graph.container.offsetHeight;
		var dy = div.offsetTop + div.clientHeight - b;
		
		if (dy > 0)
		{
			div.style.top = Math.max(graph.container.scrollTop + 22, y - dy) + 'px';
		}
		
		var r = graph.container.scrollLeft + graph.container.offsetWidth;
		var dx = div.offsetLeft + div.clientWidth - r;
		
		if (dx > 0)
		{
			div.style.left = Math.max(graph.container.scrollLeft + 22, x - dx) + 'px';
		}
	}
	
	return div;
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.getCellsForShapePicker = function(cell, hovering)
{
	var createVertex = mxUtils.bind(this, function(style, w, h, value)
	{
		return this.editor.graph.createVertex(null, null, value || '', 0, 0, w || 120, h || 60, style, false);
	});
	
	return [(cell != null) ? this.editor.graph.cloneCell(cell) :
			createVertex('text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;', 40, 20, 'Text'),
		createVertex('whiteSpace=wrap;html=1;'),
		createVertex('ellipse;whiteSpace=wrap;html=1;'),
		createVertex('rhombus;whiteSpace=wrap;html=1;', 80, 80),
		createVertex('rounded=1;whiteSpace=wrap;html=1;'),
		createVertex('shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;fixedSize=1;'),
		createVertex('shape=trapezoid;perimeter=trapezoidPerimeter;whiteSpace=wrap;html=1;fixedSize=1;', 120, 60),
		createVertex('shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;', 120, 80),
		createVertex('shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;', 120, 80),
		createVertex('shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;'),
		createVertex('triangle;whiteSpace=wrap;html=1;', 60, 80),
		createVertex('shape=document;whiteSpace=wrap;html=1;boundedLbl=1;', 120, 80),
		createVertex('shape=tape;whiteSpace=wrap;html=1;', 120, 100),
		createVertex('ellipse;shape=cloud;whiteSpace=wrap;html=1;', 120, 80),
		createVertex('shape=singleArrow;whiteSpace=wrap;html=1;arrowWidth=0.4;arrowSize=0.4;', 80, 60),
		createVertex('shape=waypoint;sketch=0;size=6;pointerEvents=1;points=[];fillColor=none;resizable=0;rotatable=0;perimeter=centerPerimeter;snapToPoint=1;', 40, 40)];
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.hideShapePicker = function(cancel)
{
	if (this.shapePicker != null)
	{
		this.shapePicker.parentNode.removeChild(this.shapePicker);
		this.shapePicker = null;
				
		if (!cancel && this.shapePickerCallback != null)
		{
			this.shapePickerCallback();
		}
		
		this.shapePickerCallback = null;
	}
};

/**
 * Returns true if the given event should start editing. This implementation returns true.
 */
EditorUi.prototype.onKeyDown = function(evt)
{
	var graph = this.editor.graph;
	
	// Alt+tab for task switcher in Windows, ctrl+tab for tab control in Chrome
	if (evt.which == 9 && graph.isEnabled() && !mxEvent.isControlDown(evt))
	{
		if (graph.isEditing())
		{
			if (mxEvent.isAltDown(evt))
			{
				graph.stopEditing(false);
			}
			else
			{
				try
				{
					var nesting = graph.cellEditor.isContentEditing() && graph.cellEditor.isTextSelected();

					if (window.getSelection && graph.cellEditor.isContentEditing() &&
						!nesting && !mxClient.IS_IE && !mxClient.IS_IE11)
					{
						var selection = window.getSelection();
						var container = (selection.rangeCount > 0) ? selection.getRangeAt(0).commonAncestorContainer : null;
						nesting = container != null && (container.nodeName == 'LI' || (container.parentNode != null &&
							container.parentNode.nodeName == 'LI'));
					}

					if (nesting)
					{
						// (Shift+)tab indents/outdents with text selection or inside list elements
						document.execCommand(mxEvent.isShiftDown(evt) ? 'outdent' : 'indent', false, null);
					}
					// Shift+tab applies value with cursor
					else if (mxEvent.isShiftDown(evt))
					{
						graph.stopEditing(false);
					}
					else
					{
						// Inserts tab character
						graph.cellEditor.insertTab(!graph.cellEditor.isContentEditing() ? 4 : null);
					}
				}
				catch (e)
				{
					// ignore
				}
			}
		}
		else if (mxEvent.isAltDown(evt))
		{
			graph.selectParentCell();
		}
		else
		{
			graph.selectCell(!mxEvent.isShiftDown(evt));
		}
			
		mxEvent.consume(evt);
	}
};

/**
 * Returns true if the given event should start editing. This implementation returns true.
 */
EditorUi.prototype.onKeyPress = function(evt)
{
	var graph = this.editor.graph;
	
	// KNOWN: Focus does not work if label is empty in quirks mode
	if (this.isImmediateEditingEvent(evt) && !graph.isEditing() && !graph.isSelectionEmpty() && evt.which !== 0 &&
		evt.which !== 27 && !mxEvent.isAltDown(evt) && !mxEvent.isControlDown(evt) && !mxEvent.isMetaDown(evt))
	{
		graph.escape();
		graph.startEditing();

		// Workaround for FF where char is lost if cursor is placed before char
		if (mxClient.IS_FF)
		{
			var ce = graph.cellEditor;
			
			if (ce.textarea != null)
			{
				ce.textarea.innerHTML = String.fromCharCode(evt.which);
	
				// Moves cursor to end of textarea
				var range = document.createRange();
				range.selectNodeContents(ce.textarea);
				range.collapse(false);
				var sel = window.getSelection();
				sel.removeAllRanges();
				sel.addRange(range);
			}
		}
	}
};

/**
 * Returns true if the given event should start editing. This implementation returns true.
 */
EditorUi.prototype.isImmediateEditingEvent = function(evt)
{
	return true;
};

/**
 * Private helper method.
 */
EditorUi.prototype.getCssClassForMarker = function(prefix, shape, marker, fill)
{
	var result = '';

	if (shape == 'flexArrow')
	{
		result = (marker != null && marker != mxConstants.NONE) ?
			'geSprite geSprite-' + prefix + 'blocktrans' : 'geSprite geSprite-noarrow';
	}
	else
	{
		// SVG marker sprites
		if (marker == 'box' || marker == 'halfCircle')
		{
			result = 'geSprite geSvgSprite geSprite-' + marker + ((prefix == 'end') ? ' geFlipSprite' : '');
		}
		else if (marker == mxConstants.ARROW_CLASSIC)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'classic' : 'geSprite geSprite-' + prefix + 'classictrans';
		}
		else if (marker == mxConstants.ARROW_CLASSIC_THIN)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'classicthin' : 'geSprite geSprite-' + prefix + 'classicthintrans';
		}
		else if (marker == mxConstants.ARROW_OPEN)
		{
			result = 'geSprite geSprite-' + prefix + 'open';
		}
		else if (marker == mxConstants.ARROW_OPEN_THIN)
		{
			result = 'geSprite geSprite-' + prefix + 'openthin';
		}
		else if (marker == mxConstants.ARROW_BLOCK)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'block' : 'geSprite geSprite-' + prefix + 'blocktrans';
		}
		else if (marker == mxConstants.ARROW_BLOCK_THIN)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'blockthin' : 'geSprite geSprite-' + prefix + 'blockthintrans';
		}
		else if (marker == mxConstants.ARROW_OVAL)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'oval' : 'geSprite geSprite-' + prefix + 'ovaltrans';
		}
		else if (marker == mxConstants.ARROW_DIAMOND)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'diamond' : 'geSprite geSprite-' + prefix + 'diamondtrans';
		}
		else if (marker == mxConstants.ARROW_DIAMOND_THIN)
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'thindiamond' : 'geSprite geSprite-' + prefix + 'thindiamondtrans';
		}
		else if (marker == 'openAsync')
		{
			result = 'geSprite geSprite-' + prefix + 'openasync';
		}
		else if (marker == 'dash')
		{
			result = 'geSprite geSprite-' + prefix + 'dash';
		}
		else if (marker == 'cross')
		{
			result = 'geSprite geSprite-' + prefix + 'cross';
		}
		else if (marker == 'async')
		{
			result = (fill == '1') ? 'geSprite geSprite-' + prefix + 'async' : 'geSprite geSprite-' + prefix + 'asynctrans';
		}
		else if (marker == 'circle' || marker == 'circlePlus')
		{
			result = (fill == '1' || marker == 'circle') ? 'geSprite geSprite-' + prefix + 'circle' : 'geSprite geSprite-' + prefix + 'circleplus';
		}
		else if (marker == 'ERone')
		{
			result = 'geSprite geSprite-' + prefix + 'erone';
		}
		else if (marker == 'ERmandOne')
		{
			result = 'geSprite geSprite-' + prefix + 'eronetoone';
		}
		else if (marker == 'ERmany')
		{
			result = 'geSprite geSprite-' + prefix + 'ermany';
		}
		else if (marker == 'ERoneToMany')
		{
			result = 'geSprite geSprite-' + prefix + 'eronetomany';
		}
		else if (marker == 'ERzeroToOne')
		{
			result = 'geSprite geSprite-' + prefix + 'eroneopt';
		}
		else if (marker == 'ERzeroToMany')
		{
			result = 'geSprite geSprite-' + prefix + 'ermanyopt';
		}
		else
		{
			result = 'geSprite geSprite-noarrow';
		}
	}

	return result;
};

/**
 * Overridden in Menus.js
 */
EditorUi.prototype.createMenus = function()
{
	return null;
};

/**
 * Hook for allowing selection and context menu for certain events.
 */
EditorUi.prototype.updatePasteActionStates = function()
{
	var graph = this.editor.graph;
	var paste = this.actions.get('paste');
	var pasteHere = this.actions.get('pasteHere');
	
	paste.setEnabled(this.editor.graph.cellEditor.isContentEditing() ||
		(((!mxClient.IS_FF && navigator.clipboard != null) || !mxClipboard.isEmpty()) &&
		graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent())));
	pasteHere.setEnabled(paste.isEnabled());
};

/**
 * Hook for allowing selection and context menu for certain events.
 */
EditorUi.prototype.initClipboard = function()
{
	var ui = this;

	var mxClipboardCut = mxClipboard.cut;
	mxClipboard.cut = function(graph)
	{
		if (graph.cellEditor.isContentEditing())
		{
			document.execCommand('cut', false, null);
		}
		else
		{
			mxClipboardCut.apply(this, arguments);
		}
		
		ui.updatePasteActionStates();
	};
	
	var mxClipboardCopy = mxClipboard.copy;
	mxClipboard.copy = function(graph)
	{
		var result = null;
		
		if (graph.cellEditor.isContentEditing())
		{
			document.execCommand('copy', false, null);
		}
		else
		{
			result = result || graph.getSelectionCells();
			result = graph.getExportableCells(graph.model.getTopmostCells(result));
			
			var cloneMap = new Object();
			var lookup = graph.createCellLookup(result);
			var clones = graph.cloneCells(result, null, cloneMap);
			
			// Uses temporary model to force new IDs to be assigned
			// to avoid having to carry over the mapping from object
			// ID to cell ID to the paste operation
			var model = new mxGraphModel();
			var parent = model.getChildAt(model.getRoot(), 0);
			
			for (var i = 0; i < clones.length; i++)
			{
				model.add(parent, clones[i]);
				
				// Checks for orphaned relative children and makes absolute				
				var state = graph.view.getState(result[i]);
				
				if (state != null)
				{
					var geo = graph.getCellGeometry(clones[i]);
				
					if (geo != null && geo.relative && !model.isEdge(result[i]) &&
						lookup[mxObjectIdentity.get(model.getParent(result[i]))] == null)
					{
						geo.offset = null;
						geo.relative = false;
						geo.x = state.x / state.view.scale - state.view.translate.x;
						geo.y = state.y / state.view.scale - state.view.translate.y;
					}
				}
			}
			
			graph.updateCustomLinks(graph.createCellMapping(cloneMap, lookup), clones);

			mxClipboard.insertCount = 1;
			mxClipboard.setCells(clones);
		}
		
		ui.updatePasteActionStates();
		
		return result;
	};

	var mxClipboardPaste = mxClipboard.paste;
	mxClipboard.paste = function(graph)
	{
		var result = null;
		
		if (graph.cellEditor.isContentEditing())
		{
			document.execCommand('paste', false, null);
		}
		else
		{
			result = mxClipboardPaste.apply(this, arguments);
		}
		
		ui.updatePasteActionStates();
		
		return result;
	};

	// Overrides cell editor to update paste action state
	var cellEditorStartEditing = this.editor.graph.cellEditor.startEditing;
	
	this.editor.graph.cellEditor.startEditing = function()
	{
		cellEditorStartEditing.apply(this, arguments);
		ui.updatePasteActionStates();
	};
	
	var cellEditorStopEditing = this.editor.graph.cellEditor.stopEditing;
	
	this.editor.graph.cellEditor.stopEditing = function(cell, trigger)
	{
		cellEditorStopEditing.apply(this, arguments);
		ui.updatePasteActionStates();
	};
	
	this.updatePasteActionStates();
};

/**
 * Delay between zoom steps when not using preview.
 */
EditorUi.prototype.lazyZoomDelay = 20;

/**
 * Delay before update of DOM when using preview.
 */
EditorUi.prototype.wheelZoomDelay = 400;

/**
 * Delay before update of DOM when using preview.
 */
EditorUi.prototype.buttonZoomDelay = 600;

/**
 * Initializes the infinite canvas.
 */
EditorUi.prototype.initCanvas = function()
{
	// Initial page layout view, scrollBuffer and timer-based scrolling
	var graph = this.editor.graph;
	graph.timerAutoScroll = true;

	/**
	 * Returns the padding for pages in page view with scrollbars.
	 */
	graph.getPagePadding = function()
	{
		return new mxPoint(Math.max(0, Math.round((graph.container.offsetWidth - 34) / graph.view.scale)),
				Math.max(0, Math.round((graph.container.offsetHeight - 34) / graph.view.scale)));
	};

	// Fits the number of background pages to the graph
	graph.view.getBackgroundPageBounds = function()
	{
		var layout = this.graph.getPageLayout();
		var page = this.graph.getPageSize();
		
		// TODO thingsKit 固定页面尺寸 超出边界后隐藏
		return new mxRectangle(this.scale * (this.translate.x),
		this.scale * (this.translate.y),
		this.scale * page.width,
		this.scale * page.height)
		// return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
		// 		this.scale * (this.translate.y + layout.y * page.height),
		// 		this.scale * layout.width * page.width,
		// 		this.scale * layout.height * page.height);
	};

	graph.getPreferredPageSize = function(bounds, width, height)
	{
		var pages = this.getPageLayout();
		var size = this.getPageSize();
		
		return new mxRectangle(0, 0, pages.width * size.width, pages.height * size.height);
	};
	
	// Scales pages/graph to fit available size
	var resize = null;
	var ui = this;
	
	if (this.editor.isChromelessView())
	{
        resize = mxUtils.bind(this, function(autoscale, maxScale, cx, cy)
        {
            if (graph.container != null && !graph.isViewer())
            {
                cx = (cx != null) ? cx : 0;
                cy = (cy != null) ? cy : 0;
                
                var bds = (graph.pageVisible) ? graph.view.getBackgroundPageBounds() : graph.getGraphBounds();
                var scroll = mxUtils.hasScrollbars(graph.container);
                var tr = graph.view.translate;
                var s = graph.view.scale;
                
                // Normalizes the bounds
                var b = mxRectangle.fromRectangle(bds);
                b.x = b.x / s - tr.x;
                b.y = b.y / s - tr.y;
                b.width /= s;
                b.height /= s;
                
                var st = graph.container.scrollTop;
                var sl = graph.container.scrollLeft;
                var sb = (document.documentMode >= 8) ? 20 : 14;
                
                if (document.documentMode == 8 || document.documentMode == 9)
                {
                    sb += 3;
                }
                
                var cw = graph.container.offsetWidth - sb;
                var ch = graph.container.offsetHeight - sb;
                
                var ns = (autoscale) ? Math.max(0.3, Math.min(maxScale || 1, cw / b.width)) : s;
                var dx = ((cw - ns * b.width) / 2) / ns;
                var dy = (this.lightboxVerticalDivider == 0) ? 0 : ((ch - ns * b.height) / this.lightboxVerticalDivider) / ns;
                
                if (scroll)
                {
                    dx = Math.max(dx, 0);
                    dy = Math.max(dy, 0);
                }

                if (scroll || bds.width < cw || bds.height < ch)
                {
                    graph.view.scaleAndTranslate(ns, Math.floor(dx - b.x), Math.floor(dy - b.y));
                    graph.container.scrollTop = st * ns / s;
                    graph.container.scrollLeft = sl * ns / s;
                }
                else if (cx != 0 || cy != 0)
                {
                    var t = graph.view.translate;
                    graph.view.setTranslate(Math.floor(t.x + cx / s), Math.floor(t.y + cy / s));
                }
								// HACK thingsKit 设置视图起点为0, 0
								graph.view.setTranslate(0, 0)
            }
        });
		
		// Hack to make function available to subclassers
		this.chromelessResize = resize;

		// Hook for subclassers for override
		this.chromelessWindowResize = mxUtils.bind(this, function()
	   	{
			this.chromelessResize(false);
	   	});

		// Removable resize listener
		var autoscaleResize = mxUtils.bind(this, function()
	   	{
			this.chromelessWindowResize(false);
	   	});
		
	   	mxEvent.addListener(window, 'resize', autoscaleResize);
	   	
	   	this.destroyFunctions.push(function()
	   	{
	   		mxEvent.removeListener(window, 'resize', autoscaleResize);
	   	});
	   	
		this.editor.addListener('resetGraphView', mxUtils.bind(this, function()
		{
			this.chromelessResize(true);
		}));

		this.actions.get('zoomIn').funct = mxUtils.bind(this, function(evt)
		{
			graph.zoomIn();
			this.chromelessResize(false);
		});
		this.actions.get('zoomOut').funct = mxUtils.bind(this, function(evt)
		{
			graph.zoomOut();
			this.chromelessResize(false);
		});
		
		// Creates toolbar for viewer - do not use CSS here
		// as this may be used in a viewer that has no CSS
		if (urlParams['toolbar'] != '0')
		{
			var toolbarConfig = JSON.parse(decodeURIComponent(urlParams['toolbar-config'] || '{}'));
			
			this.chromelessToolbar = document.createElement('div');
			this.chromelessToolbar.style.position = 'fixed';
			this.chromelessToolbar.style.overflow = 'hidden';
			this.chromelessToolbar.style.boxSizing = 'border-box';
			this.chromelessToolbar.style.whiteSpace = 'nowrap';
			this.chromelessToolbar.style.padding = '10px 10px 8px 10px';
			this.chromelessToolbar.style.left = (graph.isViewer()) ? '0' : '50%';

			if (!mxClient.IS_IE && !mxClient.IS_IE11)
			{
				this.chromelessToolbar.style.backgroundColor = '#000000';
			}
			else
			{
				this.chromelessToolbar.style.backgroundColor = '#ffffff';
				this.chromelessToolbar.style.border = '3px solid black';
			}
			
			mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'borderRadius', '16px');
			mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'transition', 'opacity 600ms ease-in-out');
			
			var updateChromelessToolbarPosition = mxUtils.bind(this, function()
			{
				var css = mxUtils.getCurrentStyle(graph.container);
				
				if (graph.isViewer())
				{
					this.chromelessToolbar.style.top = '0';
				}
				else
				{
				 	this.chromelessToolbar.style.bottom = ((css != null) ? parseInt(css['margin-bottom'] || 0) : 0) +
				 		((this.tabContainer != null) ? (20 + parseInt(this.tabContainer.style.height)) : 20) + 'px';
				} 
			});
			
			this.editor.addListener('resetGraphView', updateChromelessToolbarPosition);
			updateChromelessToolbarPosition();
			
			var btnCount = 0;
	
			var addButton = mxUtils.bind(this, function(fn, imgSrc, tip)
			{
				btnCount++;
				
				var a = document.createElement('span');
				a.style.paddingLeft = '8px';
				a.style.paddingRight = '8px';
				a.style.cursor = 'pointer';
				mxEvent.addListener(a, 'click', fn);
				
				if (tip != null)
				{
					a.setAttribute('title', tip);
				}
				
				var img = document.createElement('img');
				img.setAttribute('border', '0');
				img.setAttribute('src', imgSrc);
				img.style.width = '36px';
				img.style.filter = 'invert(100%)';
				
				a.appendChild(img);
				this.chromelessToolbar.appendChild(a);
				
				return a;
			});
			
			if (toolbarConfig.backBtn != null)
			{
				addButton(mxUtils.bind(this, function(evt)
				{
					window.location.href = toolbarConfig.backBtn.url;
					mxEvent.consume(evt);
				}), Editor.backImage, mxResources.get('back', null, 'Back'));
			}
			
			if (this.isPagesEnabled())
			{
				var prevButton = addButton(mxUtils.bind(this, function(evt)
				{
					this.actions.get('previousPage').funct();
					mxEvent.consume(evt);
				}), Editor.previousImage, mxResources.get('previousPage'));
				
				var pageInfo = document.createElement('div');
				pageInfo.style.fontFamily = Editor.defaultHtmlFont;
				pageInfo.style.display = 'inline-block';
				pageInfo.style.verticalAlign = 'top';
				pageInfo.style.fontWeight = 'bold';
				pageInfo.style.marginTop = '8px';
				pageInfo.style.fontSize = '14px';

				if (!mxClient.IS_IE && !mxClient.IS_IE11)
				{
					pageInfo.style.color = '#ffffff';
				}
				else
				{
					pageInfo.style.color = '#000000';
				}

				this.chromelessToolbar.appendChild(pageInfo);
				
				var nextButton = addButton(mxUtils.bind(this, function(evt)
				{
					this.actions.get('nextPage').funct();
					mxEvent.consume(evt);
				}), Editor.nextImage, mxResources.get('nextPage'));
				
				var updatePageInfo = mxUtils.bind(this, function()
				{
					if (this.pages != null && this.pages.length > 1 && this.currentPage != null)
					{
						pageInfo.innerHTML = '';
						mxUtils.write(pageInfo, (mxUtils.indexOf(this.pages, this.currentPage) + 1) + ' / ' + this.pages.length);
					}
				});
				
				prevButton.style.paddingLeft = '0px';
				prevButton.style.paddingRight = '4px';
				nextButton.style.paddingLeft = '4px';
				nextButton.style.paddingRight = '0px';
				
				var updatePageButtons = mxUtils.bind(this, function()
				{
					if (this.pages != null && this.pages.length > 1 && this.currentPage != null)
					{
						nextButton.style.display = '';
						prevButton.style.display = '';
						pageInfo.style.display = 'inline-block';
					}
					else
					{
						nextButton.style.display = 'none';
						prevButton.style.display = 'none';
						pageInfo.style.display = 'none';
					}
					
					updatePageInfo();
				});
				
				this.editor.addListener('resetGraphView', updatePageButtons);
				this.editor.addListener('pageSelected', updatePageInfo);
			}
		
			addButton(mxUtils.bind(this, function(evt)
			{
				this.actions.get('zoomOut').funct();
				mxEvent.consume(evt);
			}), Editor.zoomOutImage, mxResources.get('zoomOut') + ' (Alt+Mousewheel)');
			
			addButton(mxUtils.bind(this, function(evt)
			{
				this.actions.get('zoomIn').funct();
				mxEvent.consume(evt);
			}), Editor.zoomInImage, mxResources.get('zoomIn') + ' (Alt+Mousewheel)');
			
			// TODO thingsKit 隐藏自适应按钮
			addButton(mxUtils.bind(this, function(evt)
			{
				if (graph.isLightboxView())
				{
					if (graph.view.scale == 1)
					{
						this.lightboxFit();
					}
					else
					{
						graph.zoomTo(1);
					}
					
					this.chromelessResize(false);
				}
				else
				{
					this.chromelessResize(true);
				}
				
				mxEvent.consume(evt);
			}), Editor.zoomFitImage, mxResources.get('fit'));
	
			// Changes toolbar opacity on hover
			var fadeThread = null;
			var fadeThread2 = null;
			
			var fadeOut = mxUtils.bind(this, function(delay)
			{
				if (fadeThread != null)
				{
					window.clearTimeout(fadeThread);
					fadeThread = null;
				}
				
				if (fadeThread2 != null)
				{
					window.clearTimeout(fadeThread2);
					fadeThread2 = null;
				}
				
				fadeThread = window.setTimeout(mxUtils.bind(this, function()
				{
				 	mxUtils.setOpacity(this.chromelessToolbar, 0);
					fadeThread = null;
				 	
					fadeThread2 = window.setTimeout(mxUtils.bind(this, function()
					{
						this.chromelessToolbar.style.display = 'none';
						fadeThread2 = null;
					}), 600);
				}), delay || 200);
			});
			
			var fadeIn = mxUtils.bind(this, function(opacity)
			{
				if (fadeThread != null)
				{
					window.clearTimeout(fadeThread);
					fadeThread = null;
				}
				
				if (fadeThread2 != null)
				{
					window.clearTimeout(fadeThread2);
					fadeThread2 = null;
				}
				
				this.chromelessToolbar.style.display = '';
				mxUtils.setOpacity(this.chromelessToolbar, opacity || 30);
			});
	
			if (urlParams['layers'] == '1')
			{
				this.layersDialog = null;
				
				var layersButton = addButton(mxUtils.bind(this, function(evt)
				{
					if (this.layersDialog != null)
					{
						this.layersDialog.parentNode.removeChild(this.layersDialog);
						this.layersDialog = null;
					}
					else
					{
						this.layersDialog = graph.createLayersDialog(null, true);
						
						mxEvent.addListener(this.layersDialog, 'mouseleave', mxUtils.bind(this, function()
						{
							this.layersDialog.parentNode.removeChild(this.layersDialog);
							this.layersDialog = null;
						}));
						
						var r = layersButton.getBoundingClientRect();
						
						mxUtils.setPrefixedStyle(this.layersDialog.style, 'borderRadius', '5px');
						this.layersDialog.style.position = 'fixed';
						this.layersDialog.style.fontFamily = Editor.defaultHtmlFont;
						this.layersDialog.style.width = '160px';
						this.layersDialog.style.padding = '4px 2px 4px 2px';
						this.layersDialog.style.left = r.left + 'px';
						this.layersDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
							this.chromelessToolbar.offsetHeight + 4 + 'px';

						if (!mxClient.IS_IE && !mxClient.IS_IE11)
						{
							this.layersDialog.style.backgroundColor = '#000000';
							this.layersDialog.style.color = '#ffffff';
							mxUtils.setOpacity(this.layersDialog, 80);
						}
						else
						{
							this.layersDialog.style.backgroundColor = '#ffffff';
							this.layersDialog.style.border = '2px solid black';
							this.layersDialog.style.color = '#000000';
						}

						// Puts the dialog on top of the container z-index
						var style = mxUtils.getCurrentStyle(this.editor.graph.container);
						this.layersDialog.style.zIndex = style.zIndex;
						
						document.body.appendChild(this.layersDialog);
						this.editor.fireEvent(new mxEventObject('layersDialogShown'));
					}
					
					mxEvent.consume(evt);
				}), Editor.layersImage, mxResources.get('layers'));
				
				// Shows/hides layers button depending on content
				var model = graph.getModel();
	
				model.addListener(mxEvent.CHANGE, function()
				{
					layersButton.style.display = (model.getChildCount(model.root) > 1) ? '' : 'none';
				});
			}
	
			if (urlParams['openInSameWin'] != '1' || navigator.standalone)
			{
				this.addChromelessToolbarItems(addButton);
			}
	
			if (this.editor.editButtonLink != null || this.editor.editButtonFunc != null)
			{
				addButton(mxUtils.bind(this, function(evt)
				{
					if (this.editor.editButtonFunc != null) 
					{
						this.editor.editButtonFunc();
					} 
					else if (this.editor.editButtonLink == '_blank')
					{
						this.editor.editAsNew(this.getEditBlankXml());
					}
					else
					{
						graph.openLink(this.editor.editButtonLink, 'editWindow');
					}
					
					mxEvent.consume(evt);
				}), Editor.editImage, mxResources.get('edit'));
			}
			
			if (this.lightboxToolbarActions != null)
			{
				for (var i = 0; i < this.lightboxToolbarActions.length; i++)
				{
					var lbAction = this.lightboxToolbarActions[i];
					lbAction.elem = addButton(lbAction.fn, lbAction.icon, lbAction.tooltip);
				}
			}

			if (toolbarConfig.refreshBtn != null)
			{
				addButton(mxUtils.bind(this, function(evt)
				{
					if (toolbarConfig.refreshBtn.url)
					{
						window.location.href = toolbarConfig.refreshBtn.url;
					}
					else
					{
						window.location.reload();
					}
					
					mxEvent.consume(evt);
				}), Editor.refreshImage, mxResources.get('refresh', null, 'Refresh'));
			}

			if (toolbarConfig.fullscreenBtn != null && window.self !== window.top)
			{
				addButton(mxUtils.bind(this, function(evt)
				{
					if (toolbarConfig.fullscreenBtn.url)
					{
						graph.openLink(toolbarConfig.fullscreenBtn.url);
					}
					else
					{
						graph.openLink(window.location.href);
					}
					
					mxEvent.consume(evt);
				}), Editor.fullscreenImage, mxResources.get('openInNewWindow', null, 'Open in New Window'));
			}
			
			if ((toolbarConfig.closeBtn && window.self === window.top) ||
				(graph.lightbox && (urlParams['close'] == '1' || this.container != document.body)))
			{
				addButton(mxUtils.bind(this, function(evt)
				{
					if (urlParams['close'] == '1' || toolbarConfig.closeBtn)
					{
						window.close();
					}
					else
					{
						this.destroy();
						mxEvent.consume(evt);
					}
				}), Editor.closeImage, mxResources.get('close') + ' (Escape)');
			}
	
			// Initial state invisible
			this.chromelessToolbar.style.display = 'none';
			
			if (!graph.isViewer())
			{
				mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'transform', 'translate(-50%,0)');
			}
			
			graph.container.appendChild(this.chromelessToolbar);
			
			mxEvent.addListener(graph.container, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', mxUtils.bind(this, function(evt)
			{
				if (!mxEvent.isTouchEvent(evt))
				{
					if (!mxEvent.isShiftDown(evt))
					{
						fadeIn(30);
					}
					
					fadeOut();
				}
			}));
			
			mxEvent.addListener(this.chromelessToolbar, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', function(evt)
			{
				mxEvent.consume(evt);
			});
			
			mxEvent.addListener(this.chromelessToolbar, 'mouseenter', mxUtils.bind(this, function(evt)
			{
				graph.tooltipHandler.resetTimer();
				graph.tooltipHandler.hideTooltip();

				if (!mxEvent.isShiftDown(evt))
				{
					fadeIn(100);
				}
				else
				{
					fadeOut();
				}
			}));

			mxEvent.addListener(this.chromelessToolbar, 'mousemove',  mxUtils.bind(this, function(evt)
			{
				if (!mxEvent.isShiftDown(evt))
				{
					fadeIn(100);
				}
				else
				{
					fadeOut();
				}
				
				mxEvent.consume(evt);
			}));

			mxEvent.addListener(this.chromelessToolbar, 'mouseleave',  mxUtils.bind(this, function(evt)
			{
				if (!mxEvent.isTouchEvent(evt))
				{
					fadeIn(30);
				}
			}));

			// Shows/hides toolbar for touch devices
			var tol = graph.getTolerance();

			graph.addMouseListener(
			{
			    startX: 0,
			    startY: 0,
			    scrollLeft: 0,
			    scrollTop: 0,
			    mouseDown: function(sender, me)
			    {
			    	this.startX = me.getGraphX();
			    	this.startY = me.getGraphY();
				    this.scrollLeft = graph.container.scrollLeft;
				    this.scrollTop = graph.container.scrollTop;
			    },
			    mouseMove: function(sender, me) {},
			    mouseUp: function(sender, me)
			    {
			    	if (mxEvent.isTouchEvent(me.getEvent()))
			    	{
				    	if ((Math.abs(this.scrollLeft - graph.container.scrollLeft) < tol &&
				    		Math.abs(this.scrollTop - graph.container.scrollTop) < tol) &&
				    		(Math.abs(this.startX - me.getGraphX()) < tol &&
				    		Math.abs(this.startY - me.getGraphY()) < tol))
				    	{
				    		if (parseFloat(ui.chromelessToolbar.style.opacity || 0) > 0)
				    		{
				    			fadeOut();
				    		}
				    		else
				    		{
				    			fadeIn(30);
				    		}
						}
			    	}
			    }
			});
		} // end if toolbar

		// Installs handling of highlight and handling links to relative links and anchors
		if (!this.editor.editable)
		{
			this.addChromelessClickHandler();
		}
	}
	else if (this.editor.extendCanvas)
	{
		/**
		 * Guesses autoTranslate to avoid another repaint (see below).
		 * Works if only the scale of the graph changes or if pages
		 * are visible and the visible pages do not change.
		 */
		var graphViewValidate = graph.view.validate;
		graph.view.validate = function()
		{
			if (this.graph.container != null && mxUtils.hasScrollbars(this.graph.container))
			{
				var pad = this.graph.getPagePadding();
				var size = this.graph.getPageSize();
				
				// Updating scrollbars here causes flickering in quirks and is not needed
				// if zoom method is always used to set the current scale on the graph.
				var tx = this.translate.x;
				var ty = this.translate.y;
				this.translate.x = pad.x - (this.x0 || 0) * size.width;
				this.translate.y = pad.y - (this.y0 || 0) * size.height;
			}
			
			graphViewValidate.apply(this, arguments);
		};
		
		if (!graph.isViewer())
		{
			var graphSizeDidChange = graph.sizeDidChange;
			
			graph.sizeDidChange = function()
			{
				if (this.container != null && mxUtils.hasScrollbars(this.container))
				{
					var pages = this.getPageLayout();
					var pad = this.getPagePadding();
					var size = this.getPageSize();
					
					// Updates the minimum graph size
					var minw = Math.ceil(2 * pad.x + pages.width * size.width);
					var minh = Math.ceil(2 * pad.y + pages.height * size.height);
					
					var min = graph.minimumGraphSize;
					
					// LATER: Fix flicker of scrollbar size in IE quirks mode
					// after delayed call in window.resize event handler
					if (min == null || min.width != minw || min.height != minh)
					{
						graph.minimumGraphSize = new mxRectangle(0, 0, minw, minh);
					}
					
					// Updates auto-translate to include padding and graph size
					var dx = pad.x - pages.x * size.width;
					var dy = pad.y - pages.y * size.height;
					
					if (!this.autoTranslate && (this.view.translate.x != dx || this.view.translate.y != dy))
					{
						this.autoTranslate = true;
						this.view.x0 = pages.x;
						this.view.y0 = pages.y;
	
						// NOTE: THIS INVOKES THIS METHOD AGAIN. UNFORTUNATELY THERE IS NO WAY AROUND THIS SINCE THE
						// BOUNDS ARE KNOWN AFTER THE VALIDATION AND SETTING THE TRANSLATE TRIGGERS A REVALIDATION.
						// SHOULD MOVE TRANSLATE/SCALE TO VIEW.
						var tx = graph.view.translate.x;
						var ty = graph.view.translate.y;
						graph.view.setTranslate(dx, dy);
						
						// LATER: Fix rounding errors for small zoom
						graph.container.scrollLeft += Math.round((dx - tx) * graph.view.scale);
						graph.container.scrollTop += Math.round((dy - ty) * graph.view.scale);
						
						this.autoTranslate = false;
						
						return;
					}
	
					graphSizeDidChange.apply(this, arguments);
				}
				else
				{
					// Fires event but does not invoke superclass
					this.fireEvent(new mxEventObject(mxEvent.SIZE, 'bounds', this.getGraphBounds()));
				}
			};
		}
	}
	
	// Accumulates the zoom factor while the rendering is taking place
	// so that not the complete sequence of zoom steps must be painted
	var bgGroup = graph.view.getBackgroundPane();
	var mainGroup = graph.view.getDrawPane();
	graph.cumulativeZoomFactor = 1;
	var updateZoomTimeout = null;
	var cursorPosition = null;
	var scrollPosition = null;
	var forcedZoom = null;
	var filter = null;
	
	var scheduleZoom = function(delay)
	{
		if (updateZoomTimeout != null)
		{
			window.clearTimeout(updateZoomTimeout);
		}

		if (delay >= 0)
		{
			window.setTimeout(function()
			{
				if (!graph.isMouseDown || forcedZoom)
				{
					updateZoomTimeout = window.setTimeout(mxUtils.bind(this, function()
					{
						if (graph.isFastZoomEnabled())
						{
							// Transforms background page
							if (graph.view.backgroundPageShape != null && graph.view.backgroundPageShape.node != null)
							{
								mxUtils.setPrefixedStyle(graph.view.backgroundPageShape.node.style, 'transform-origin', null);
								mxUtils.setPrefixedStyle(graph.view.backgroundPageShape.node.style, 'transform', null);
							}
							
							// Transforms graph and background image
							mainGroup.style.transformOrigin = '';
							bgGroup.style.transformOrigin = '';

							// Workaround for no reset of transform in Safari
							if (mxClient.IS_SF)
							{
								mainGroup.style.transform = 'scale(1)';
								bgGroup.style.transform = 'scale(1)';
								
								window.setTimeout(function()
								{
									mainGroup.style.transform = '';
									bgGroup.style.transform = '';
								}, 0)
							}
							else
							{
								mainGroup.style.transform = '';
								bgGroup.style.transform = '';
							}
							
							// Shows interactive elements
							graph.view.getDecoratorPane().style.opacity = '';
							graph.view.getOverlayPane().style.opacity = '';
						}
						
						var sp = new mxPoint(graph.container.scrollLeft, graph.container.scrollTop);
						var offset = mxUtils.getOffset(graph.container);
						var prev = graph.view.scale;
						var dx = 0;
						var dy = 0;
						
						if (cursorPosition != null)
						{
							dx = graph.container.offsetWidth / 2 - cursorPosition.x + offset.x;
							dy = graph.container.offsetHeight / 2 - cursorPosition.y + offset.y;
						}

						graph.zoom(graph.cumulativeZoomFactor, null,
							graph.isFastZoomEnabled() ? 20 : null);
						var s = graph.view.scale;
						
						if (s != prev)
						{
							if (scrollPosition != null)
							{
								dx += sp.x - scrollPosition.x;
								dy += sp.y - scrollPosition.y;
							}
							
							if (resize != null)
							{
								ui.chromelessResize(false, null, dx * (graph.cumulativeZoomFactor - 1),
									dy * (graph.cumulativeZoomFactor - 1));
							}
							
							if (mxUtils.hasScrollbars(graph.container) && (dx != 0 || dy != 0))
							{
								graph.container.scrollLeft -= dx * (graph.cumulativeZoomFactor - 1);
								graph.container.scrollTop -= dy * (graph.cumulativeZoomFactor - 1);
							}
						}
						
						if (filter != null)
						{
							mainGroup.setAttribute('filter', filter);
						}
						
						graph.cumulativeZoomFactor = 1;
						updateZoomTimeout = null;
						scrollPosition = null;
						cursorPosition = null;
						forcedZoom = null;
						filter = null;
					}), (delay != null) ? delay : ((graph.isFastZoomEnabled()) ? ui.wheelZoomDelay : ui.lazyZoomDelay));
				}
			}, 0);
		}
	};
	
	graph.lazyZoom = function(zoomIn, ignoreCursorPosition, delay, factor)
	{
		factor = (factor != null) ? factor : this.zoomFactor;

		// TODO: Fix ignored cursor position if scrollbars are disabled
		ignoreCursorPosition = ignoreCursorPosition || !graph.scrollbars;
		
		if (ignoreCursorPosition)
		{
			cursorPosition = new mxPoint(
				graph.container.offsetLeft + graph.container.clientWidth / 2,
				graph.container.offsetTop + graph.container.clientHeight / 2);
		}
		
		// Switches to 5% zoom steps below 15%
		if (zoomIn)
		{
			if (this.view.scale * this.cumulativeZoomFactor <= 0.15)
			{
				this.cumulativeZoomFactor *= (this.view.scale + 0.05) / this.view.scale;
			}
			else
			{
				this.cumulativeZoomFactor *= factor;
				this.cumulativeZoomFactor = Math.round(this.view.scale * this.cumulativeZoomFactor * 100) / 100 / this.view.scale;
			}
		}
		else
		{
			if (this.view.scale * this.cumulativeZoomFactor <= 0.15)
			{
				this.cumulativeZoomFactor *= (this.view.scale - 0.05) / this.view.scale;
			}
			else
			{
				this.cumulativeZoomFactor /= factor;
				this.cumulativeZoomFactor = Math.round(this.view.scale * this.cumulativeZoomFactor * 100) / 100 / this.view.scale;
			}
		}

		this.cumulativeZoomFactor = Math.max(0.05, Math.min(this.view.scale * this.cumulativeZoomFactor, 160)) / this.view.scale;

		if (graph.isFastZoomEnabled())
		{
			if (filter == null && mainGroup.getAttribute('filter') != '')
			{
				filter = mainGroup.getAttribute('filter');
				mainGroup.removeAttribute('filter');
			}

			scrollPosition = new mxPoint(graph.container.scrollLeft, graph.container.scrollTop);
			
			var cx = (ignoreCursorPosition || cursorPosition == null) ?
				graph.container.scrollLeft + graph.container.clientWidth / 2 :
				cursorPosition.x + graph.container.scrollLeft - graph.container.offsetLeft;
			var cy = (ignoreCursorPosition || cursorPosition == null) ?
				graph.container.scrollTop + graph.container.clientHeight / 2 :
				cursorPosition.y + graph.container.scrollTop - graph.container.offsetTop;
			mainGroup.style.transformOrigin = cx + 'px ' + cy + 'px';
			mainGroup.style.transform = 'scale(' + this.cumulativeZoomFactor + ')';
			bgGroup.style.transformOrigin = cx + 'px ' + cy + 'px';
			bgGroup.style.transform = 'scale(' + this.cumulativeZoomFactor + ')';
			
			if (graph.view.backgroundPageShape != null && graph.view.backgroundPageShape.node != null)
			{
				var page = graph.view.backgroundPageShape.node;
				
				mxUtils.setPrefixedStyle(page.style, 'transform-origin',
					((ignoreCursorPosition || cursorPosition == null) ?
						((graph.container.clientWidth / 2 + graph.container.scrollLeft -
						page.offsetLeft) + 'px') : ((cursorPosition.x + graph.container.scrollLeft -
						page.offsetLeft - graph.container.offsetLeft) + 'px')) + ' ' +
					((ignoreCursorPosition || cursorPosition == null) ?
						((graph.container.clientHeight / 2 + graph.container.scrollTop -
						page.offsetTop) + 'px') : ((cursorPosition.y + graph.container.scrollTop -
						page.offsetTop - graph.container.offsetTop) + 'px')));
				mxUtils.setPrefixedStyle(page.style, 'transform',
					'scale(' + this.cumulativeZoomFactor + ')');
			}

			graph.view.getDecoratorPane().style.opacity = '0';
			graph.view.getOverlayPane().style.opacity = '0';
			
			if (ui.hoverIcons != null)
			{
				ui.hoverIcons.reset();
			}
		}
		
		scheduleZoom(graph.isFastZoomEnabled() ? delay : 0);
	};
	
	// Holds back repaint until after mouse gestures
	mxEvent.addGestureListeners(graph.container, function(evt)
	{
		if (updateZoomTimeout != null)
		{
			window.clearTimeout(updateZoomTimeout);
		}
	}, null, function(evt)
	{
		if (graph.cumulativeZoomFactor != 1)
		{
			scheduleZoom(0);
		}
	});
	
	// Holds back repaint until scroll ends
	mxEvent.addListener(graph.container, 'scroll', function(evt)
	{
		if (updateZoomTimeout != null && !graph.isMouseDown && graph.cumulativeZoomFactor != 1)
		{
			scheduleZoom(0);
		}
	});
	
	mxEvent.addMouseWheelListener(mxUtils.bind(this, function(evt, up, force, cx, cy)
	{
		graph.fireEvent(new mxEventObject('wheel'));

		if (this.dialogs == null || this.dialogs.length == 0)
		{
			// Scrolls with scrollbars turned off
			if (!graph.scrollbars && !force && graph.isScrollWheelEvent(evt))
            {
                var t = graph.view.getTranslate();
                var step = 40 / graph.view.scale;
                
                if (!mxEvent.isShiftDown(evt))
                {
                    graph.view.setTranslate(t.x, t.y + ((up) ? step : -step));
                }
                else
                {
                    graph.view.setTranslate(t.x + ((up) ? -step : step), t.y);
                }
            }
			else if (force || graph.isZoomWheelEvent(evt))
			{
				var source = mxEvent.getSource(evt);

				while (source != null)
				{
					if (source == graph.container)
					{
						graph.tooltipHandler.hideTooltip();
						cursorPosition = (cx != null && cy!= null) ? new mxPoint(cx, cy) :
							new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
						forcedZoom = force;
						var factor = graph.zoomFactor;
						var delay = null;

						// Slower zoom for pinch gesture on trackpad with max delta to
						// filter out mouse wheel events in Brave browser for Windows 
						if (evt.ctrlKey && evt.deltaY != null && Math.abs(evt.deltaY) < 40 &&
							Math.round(evt.deltaY) != evt.deltaY)
						{
							factor = 1 + (Math.abs(evt.deltaY) / 20) * (factor - 1);
						}
						// Slower zoom for pinch gesture on touch screens
						else if (evt.movementY != null && evt.type == 'pointermove')
						{
							factor = 1 + (Math.max(1, Math.abs(evt.movementY)) / 20) * (factor - 1);
							delay = -1;
						}
						
						graph.lazyZoom(up, null, delay, factor);
						mxEvent.consume(evt);
				
						return false;
					}
					
					source = source.parentNode;
				}
			}
		}
	}), graph.container);
	
	// Uses fast zoom for pinch gestures on iOS
	graph.panningHandler.zoomGraph = function(evt)
	{
		graph.cumulativeZoomFactor = evt.scale;
		graph.lazyZoom(evt.scale > 0, true);
		mxEvent.consume(evt);
	};
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.addChromelessToolbarItems = function(addButton)
{
	// TODO thingsKit 隐藏预览打印按钮
	// addButton(mxUtils.bind(this, function(evt)
	// {
	// 	this.actions.get('print').funct();
	// 	mxEvent.consume(evt);
	// }), Editor.printImage, mxResources.get('print'));	
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.isPagesEnabled = function()
{
	return this.editor.editable || urlParams['hide-pages'] != '1';
};

/**
 * Creates a temporary graph instance for rendering off-screen content.
 */
EditorUi.prototype.createTemporaryGraph = function(stylesheet)
{
	return Graph.createOffscreenGraph(stylesheet);
};

/**
 * 
 */
EditorUi.prototype.addChromelessClickHandler = function()
{
	var hl = urlParams['highlight'];
	
	// Adds leading # for highlight color code
	if (hl != null && hl.length > 0)
	{
		hl = '#' + hl;
	}

	this.editor.graph.addClickHandler(hl);
};

/**
 * 
 */
EditorUi.prototype.toggleFormatPanel = function(visible)
{
	visible = (visible != null) ? visible : this.formatWidth == 0;
	
	if (this.format != null)
	{
		this.formatWidth = (visible) ? 240 : 0;
		this.formatContainer.style.display = (visible) ? '' : 'none';
		this.refresh();
		this.format.refresh();
		this.fireEvent(new mxEventObject('formatWidthChanged'));
	}
};

/**
 * Adds support for placeholders in labels.
 */
EditorUi.prototype.lightboxFit = function(maxHeight)
{
	if (this.isDiagramEmpty())
	{
		this.editor.graph.view.setScale(1);
	}
	else
	{
		var p = urlParams['border'];
		var border = 60;
		
		if (p != null)
		{
			border = parseInt(p);
		}
		
		// LATER: Use initial graph bounds to avoid rounding errors
		// this.editor.graph.maxFitScale = this.lightboxMaxFitScale;
		// this.editor.graph.fit(border, null, null, null, null, null, maxHeight);
		// this.editor.graph.maxFitScale = null;
		// // TODO thingsKit lightbox 默认缩放为1 
		// console.log(this.editor.graph.view)
		// this.editor.graph.view.setScale(1);
		/// TODO thingsKit 设置内容最大化
		var margin = 2;
		var max = 3;
		var graph = this.editor.graph
		var pageFormat = graph.pageFormat
		var bounds = graph.getGraphBounds();
		var cw = graph.container.clientWidth - margin; 
		var ch = graph.container.clientHeight - margin;
		try {
			if (graph.container.clientHeight <= 0 && graph.container.clientWidth <= 0 && parent) {
				var iframeContainerList = parent.document.querySelectorAll('.iframe-content') || []
				var parentNode = Array.from(iframeContainerList).find(item => item.querySelector('iframe').contentDocument === document)
				if(!parentNode) return
				var width = parentNode.style.width
				var height = parentNode.style.height
				cw = Number(width.replace('px', '')) 
				ch = Number(height.replace('px', '')) 
			}
		}	catch (error) {
			throw error
		}
		var w = pageFormat.width
		// var w = pageFormat.width / graph.view.scale;
		var h = pageFormat.height;
		// var h = pageFormat.height / graph.view.scale;
		var s = Math.min(max, Math.min(cw / w, ch / h));
		s = s < 0 ? 1 : s 
		graph.view.scaleAndTranslate(s,
			(margin + cw - w * s) / (2 * s) - bounds.x / graph.view.scale,
			(margin + ch - h * s) / (2 * s) - bounds.y / graph.view.scale);
	}
};

/**
 * Translates this point by the given vector.
 * 
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
EditorUi.prototype.isDiagramEmpty = function()
{
	var model = this.editor.graph.getModel();
	
	return model.getChildCount(model.root) == 1 && model.getChildCount(model.getChildAt(model.root, 0)) == 0;
};

/**
 * Hook for allowing selection and context menu for certain events.
 */
EditorUi.prototype.isSelectionAllowed = function(evt)
{
	return mxEvent.getSource(evt).nodeName == 'SELECT' || (mxEvent.getSource(evt).nodeName == 'INPUT' &&
		mxUtils.isAncestorNode(this.formatContainer, mxEvent.getSource(evt)));
};

/**
 * Installs dialog if browser window is closed without saving
 * This must be disabled during save and image export.
 */
EditorUi.prototype.addBeforeUnloadListener = function()
{
	// Installs dialog if browser window is closed without saving
	// This must be disabled during save and image export
	window.onbeforeunload = mxUtils.bind(this, function()
	{
		if (!this.editor.isChromelessView())
		{
			return this.onBeforeUnload();
		}
	});
};

/**
 * Sets the onbeforeunload for the application
 */
EditorUi.prototype.onBeforeUnload = function()
{
	if (this.editor.modified)
	{
		return mxResources.get('allChangesLost');
	}
};

/**
 * Opens the current diagram via the window.opener if one exists.
 */
EditorUi.prototype.open = function()
{
	// Cross-domain window access is not allowed in FF, so if we
	// were opened from another domain then this will fail.
	try
	{
		if (window.opener != null && window.opener.openFile != null)
		{
			window.opener.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
			{
				try
				{
					var doc = mxUtils.parseXml(xml); 
					this.editor.setGraphXml(doc.documentElement);
					this.editor.setModified(false);
					this.editor.undoManager.clear();
					
					if (filename != null)
					{
						this.editor.setFilename(filename);
						this.updateDocumentTitle();
					}
					
					return;
				}
				catch (e)
				{
					mxUtils.alert(mxResources.get('invalidOrMissingFile') + ': ' + e.message);
				}
			}));
		}
	}
	catch(e)
	{
		// ignore
	}
	
	// Fires as the last step if no file was loaded
	this.editor.graph.view.validate();
	
	// Required only in special cases where an initial file is opened
	// and the minimumGraphSize changes and CSS must be updated.
	this.editor.graph.sizeDidChange();
	this.editor.fireEvent(new mxEventObject('resetGraphView'));
};

/**
 * Shows the given popup menu.
 */
EditorUi.prototype.showPopupMenu = function(fn, x, y, evt)
{
	this.editor.graph.popupMenuHandler.hideMenu();
	
	var menu = new mxPopupMenu(fn);
	menu.div.className += ' geMenubarMenu';
	menu.smartSeparators = true;
	menu.showDisabled = true;
	menu.autoExpand = true;
	
	// Disables autoexpand and destroys menu when hidden
	menu.hideMenu = mxUtils.bind(this, function()
	{
		mxPopupMenu.prototype.hideMenu.apply(menu, arguments);
		menu.destroy();
	});

	menu.popup(x, y, null, evt);
	
	// Allows hiding by clicking on document
	this.setCurrentMenu(menu);	
};

/**
 * Sets the current menu and element.
 */
EditorUi.prototype.setCurrentMenu = function(menu, elt)
{
	this.currentMenuElt = elt;
	this.currentMenu = menu;
};

/**
 * Resets the current menu and element.
 */
EditorUi.prototype.resetCurrentMenu = function()
{
	this.currentMenuElt = null;
	this.currentMenu = null;
};

/**
 * Hides and destroys the current menu.
 */
EditorUi.prototype.hideCurrentMenu = function()
{
	if (this.currentMenu != null)
	{
		this.currentMenu.hideMenu();
		this.resetCurrentMenu();
	}
};

/**
 * Updates the document title.
 */
EditorUi.prototype.updateDocumentTitle = function()
{
	var title = this.editor.getOrCreateFilename();
	
	if (this.editor.appName != null)
	{
		// TODO thingskit delete '-'
		// title += ' - ' + this.editor.appName;
	}
	
	document.title = title;
};

/**
 * Updates the document title.
 */
EditorUi.prototype.createHoverIcons = function()
{
	return new HoverIcons(this.editor.graph);
};

/**
 * Returns the URL for a copy of this editor with no state.
 */
EditorUi.prototype.redo = function()
{
	try
	{
		var graph = this.editor.graph;
		
		if (graph.isEditing())
		{
			document.execCommand('redo', false, null);
		}
		else
		{
			this.editor.undoManager.redo();
		}
	}
	catch (e)
	{
		// ignore all errors
	}
};

/**
 * Returns the URL for a copy of this editor with no state.
 */
EditorUi.prototype.undo = function()
{
	try
	{
		var graph = this.editor.graph;
	
		if (graph.isEditing())
		{
			// Stops editing and executes undo on graph if native undo
			// does not affect current editing value
			var value = graph.cellEditor.textarea.innerHTML;
			document.execCommand('undo', false, null);
	
			if (value == graph.cellEditor.textarea.innerHTML)
			{
				graph.stopEditing(true);
				this.editor.undoManager.undo();
			}
		}
		else
		{
			this.editor.undoManager.undo();
		}
	}
	catch (e)
	{
		// ignore all errors
	}
};

/**
 * Returns the URL for a copy of this editor with no state.
 */
EditorUi.prototype.canRedo = function()
{
	return this.editor.graph.isEditing() || this.editor.undoManager.canRedo();
};

/**
 * Returns the URL for a copy of this editor with no state.
 */
EditorUi.prototype.canUndo = function()
{
	return this.editor.graph.isEditing() || this.editor.undoManager.canUndo();
};

/**
 * 
 */
EditorUi.prototype.getEditBlankXml = function()
{
	return mxUtils.getXml(this.editor.getGraphXml());
};

/**
 * Returns the URL for a copy of this editor with no state.
 */
EditorUi.prototype.getUrl = function(pathname)
{
	var href = (pathname != null) ? pathname : window.location.pathname;
	var parms = (href.indexOf('?') > 0) ? 1 : 0;
	
	// Removes template URL parameter for new blank diagram
	for (var key in urlParams)
	{
		if (parms == 0)
		{
			href += '?';
		}
		else
		{
			href += '&';
		}
	
		href += key + '=' + urlParams[key];
		parms++;
	}
	
	return href;
};

/**
 * Specifies if the graph has scrollbars.
 */
EditorUi.prototype.setScrollbars = function(value)
{
	var graph = this.editor.graph;
	var prev = graph.container.style.overflow;
	graph.scrollbars = value;
	this.editor.updateGraphComponents();

	if (prev != graph.container.style.overflow)
	{
		graph.container.scrollTop = 0;
		graph.container.scrollLeft = 0;
		graph.view.scaleAndTranslate(1, 0, 0);
		this.resetScrollbars();
	}
	
	this.fireEvent(new mxEventObject('scrollbarsChanged'));
};

/**
 * Returns true if the graph has scrollbars.
 */
EditorUi.prototype.hasScrollbars = function()
{
	return this.editor.graph.scrollbars;
};

/**
 * Resets the state of the scrollbars.
 */
EditorUi.prototype.resetScrollbars = function()
{
	var graph = this.editor.graph;
	
	if (!this.editor.extendCanvas)
	{
		graph.container.scrollTop = 0;
		graph.container.scrollLeft = 0;
	
		if (!mxUtils.hasScrollbars(graph.container))
		{
			graph.view.setTranslate(0, 0);
		}
	}
	else if (!this.editor.isChromelessView())
	{
		if (mxUtils.hasScrollbars(graph.container))
		{
			if (graph.pageVisible)
			{
				var pad = graph.getPagePadding();
				graph.container.scrollTop = Math.floor(pad.y - this.editor.initialTopSpacing) - 1;
				graph.container.scrollLeft = Math.floor(Math.min(pad.x,
					(graph.container.scrollWidth - graph.container.clientWidth) / 2)) - 1;

				// Scrolls graph to visible area
				var bounds = graph.getGraphBounds();
				
				if (bounds.width > 0 && bounds.height > 0)
				{
					if (bounds.x > graph.container.scrollLeft + graph.container.clientWidth * 0.9)
					{
						graph.container.scrollLeft = Math.min(bounds.x + bounds.width - graph.container.clientWidth, bounds.x - 10);
					}
					
					if (bounds.y > graph.container.scrollTop + graph.container.clientHeight * 0.9)
					{
						graph.container.scrollTop = Math.min(bounds.y + bounds.height - graph.container.clientHeight, bounds.y - 10);
					}
				}
			}
			else
			{
				var bounds = graph.getGraphBounds();
				var width = Math.max(bounds.width, graph.scrollTileSize.width * graph.view.scale);
				var height = Math.max(bounds.height, graph.scrollTileSize.height * graph.view.scale);
				graph.container.scrollTop = Math.floor(Math.max(0, bounds.y - Math.max(20, (graph.container.clientHeight - height) / 4)));
				graph.container.scrollLeft = Math.floor(Math.max(0, bounds.x - Math.max(0, (graph.container.clientWidth - width) / 2)));
			}
		}
		else
		{
			var b = mxRectangle.fromRectangle((graph.pageVisible) ? graph.view.getBackgroundPageBounds() : graph.getGraphBounds())
			var tr = graph.view.translate;
			var s = graph.view.scale;
            b.x = b.x / s - tr.x;
            b.y = b.y / s - tr.y;
            b.width /= s;
            b.height /= s;
            
            var dy = (graph.pageVisible) ? 0 : Math.max(0, (graph.container.clientHeight - b.height) / 4); 
            
			graph.view.setTranslate(Math.floor(Math.max(0,
				(graph.container.clientWidth - b.width) / 2) - b.x + 2),
				Math.floor(dy - b.y + 1));
		}
	}
};

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setPageVisible = function(value)
{
	var graph = this.editor.graph;
	var hasScrollbars = mxUtils.hasScrollbars(graph.container);
	var tx = 0;
	var ty = 0;
	
	if (hasScrollbars)
	{
		tx = graph.view.translate.x * graph.view.scale - graph.container.scrollLeft;
		ty = graph.view.translate.y * graph.view.scale - graph.container.scrollTop;
	}
	
	graph.pageVisible = value;
	graph.pageBreaksVisible = value; 
	graph.preferPageSize = value;
	graph.view.validateBackground();

	// Workaround for possible handle offset
	if (hasScrollbars)
	{
		var cells = graph.getSelectionCells();
		graph.clearSelection();
		graph.setSelectionCells(cells);
	}
	
	// Calls updatePageBreaks
	graph.sizeDidChange();
	
	if (hasScrollbars)
	{
		graph.container.scrollLeft = graph.view.translate.x * graph.view.scale - tx;
		graph.container.scrollTop = graph.view.translate.y * graph.view.scale - ty;
	}
	
	graph.defaultPageVisible = value;
	this.fireEvent(new mxEventObject('pageViewChanged'));
};

/**
 * Class: ChangeGridColor
 *
 * Undoable change to grid color.
 */
function ChangeGridColor(ui, color)
{
	this.ui = ui;
	this.color = color;
};

/**
 * Executes selection of a new page.
 */
ChangeGridColor.prototype.execute = function()
{
	var temp = this.ui.editor.graph.view.gridColor;
	this.ui.setGridColor(this.color);
	this.color = temp;
};

// Registers codec for ChangePageSetup
(function()
{
	var codec = new mxObjectCodec(new ChangeGridColor(), ['ui']);

	mxCodecRegistry.register(codec);
})();

/**
 * Change types
 */
function ChangePageSetup(ui, color, image, format, pageScale)
{
	this.ui = ui;
	this.color = color;
	this.previousColor = color;
	this.image = image;
	this.previousImage = image;
	this.format = format;
	this.previousFormat = format;
	this.pageScale = pageScale;
	this.previousPageScale = pageScale;
	
	// Needed since null are valid values for color and image
	this.ignoreColor = false;
	this.ignoreImage = false;
}

/**
 * Implementation of the undoable page rename.
 */
ChangePageSetup.prototype.execute = function()
{
	var graph = this.ui.editor.graph;
	
	if (!this.ignoreColor)
	{
		this.color = this.previousColor;
		var tmp = graph.background;
		this.ui.setBackgroundColor(this.previousColor);
		this.previousColor = tmp;
	}
	
	if (!this.ignoreImage)
	{
		this.image = this.previousImage;
		var tmp = graph.backgroundImage;
		var img = this.previousImage;

		if (img != null && img.src != null && img.src.substring(0, 13) == 'data:page/id,')
		{
			img = this.ui.createImageForPageLink(img.src, this.ui.currentPage);
		}

		this.ui.setBackgroundImage(img);
		this.previousImage = tmp;
	}
	
	if (this.previousFormat != null)
	{
		this.format = this.previousFormat;
		var tmp = graph.pageFormat;
		
		if (this.previousFormat.width != tmp.width ||
			this.previousFormat.height != tmp.height)
		{
			this.ui.setPageFormat(this.previousFormat);
			this.previousFormat = tmp;
		}
	}

    if (this.foldingEnabled != null && this.foldingEnabled != this.ui.editor.graph.foldingEnabled)
    {
    	this.ui.setFoldingEnabled(this.foldingEnabled);
        this.foldingEnabled = !this.foldingEnabled;
    }

    if (this.previousPageScale != null)
    {
	    var currentPageScale = this.ui.editor.graph.pageScale;
	    
	    if (this.previousPageScale != currentPageScale)
	    {
	    	this.ui.setPageScale(this.previousPageScale);
	        this.previousPageScale = currentPageScale;
	    }
    }
};

// Registers codec for ChangePageSetup
(function()
{
	var codec = new mxObjectCodec(new ChangePageSetup(),  ['ui', 'previousColor', 'previousImage', 'previousFormat', 'previousPageScale']);

	codec.afterDecode = function(dec, node, obj)
	{
		obj.previousColor = obj.color;
		obj.previousImage = obj.image;
		obj.previousFormat = obj.format;
		obj.previousPageScale = obj.pageScale;

        if (obj.foldingEnabled != null)
        {
        	obj.foldingEnabled = !obj.foldingEnabled;
        }
       
		return obj;
	};
	
	mxCodecRegistry.register(codec);
})();

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setBackgroundColor = function(value)
{
	this.editor.graph.background = value;
	this.editor.graph.view.validateBackground();

	this.fireEvent(new mxEventObject('backgroundColorChanged'));
};

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setFoldingEnabled = function(value)
{
	this.editor.graph.foldingEnabled = value;
	this.editor.graph.view.revalidate();
	
	this.fireEvent(new mxEventObject('foldingEnabledChanged'));
};

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setPageFormat = function(value, ignorePageVisible)
{
	ignorePageVisible = (ignorePageVisible != null) ? ignorePageVisible : urlParams['sketch'] == '1';
	this.editor.graph.pageFormat = value;
	
	if (!ignorePageVisible)
	{
		if (!this.editor.graph.pageVisible)
		{
			this.actions.get('pageView').funct();
		}
		else
		{
			this.editor.graph.view.validateBackground();
			this.editor.graph.sizeDidChange();
		}
	}

	this.fireEvent(new mxEventObject('pageFormatChanged'));
};

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setPageScale = function(value)
{
	this.editor.graph.pageScale = value;
	
	if (!this.editor.graph.pageVisible)
	{
		this.actions.get('pageView').funct();
	}
	else
	{
		this.editor.graph.view.validateBackground();
		this.editor.graph.sizeDidChange();
	}

	this.fireEvent(new mxEventObject('pageScaleChanged'));
};

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setGridColor = function(value)
{
	this.editor.graph.view.gridColor = value;
	this.editor.graph.view.validateBackground();
	this.fireEvent(new mxEventObject('gridColorChanged'));
};

/**
 * Updates the states of the given undo/redo items.
 */
EditorUi.prototype.addUndoListener = function()
{
	var undo = this.actions.get('undo');
	var redo = this.actions.get('redo');
	
	var undoMgr = this.editor.undoManager;
	
    var undoListener = mxUtils.bind(this, function()
    {
    	undo.setEnabled(this.canUndo());
    	redo.setEnabled(this.canRedo());
    });

    undoMgr.addListener(mxEvent.ADD, undoListener);
    undoMgr.addListener(mxEvent.UNDO, undoListener);
    undoMgr.addListener(mxEvent.REDO, undoListener);
    undoMgr.addListener(mxEvent.CLEAR, undoListener);
	
	// Overrides cell editor to update action states
	var cellEditorStartEditing = this.editor.graph.cellEditor.startEditing;
	
	this.editor.graph.cellEditor.startEditing = function()
	{
		cellEditorStartEditing.apply(this, arguments);
		undoListener();
	};
	
	var cellEditorStopEditing = this.editor.graph.cellEditor.stopEditing;
	
	this.editor.graph.cellEditor.stopEditing = function(cell, trigger)
	{
		cellEditorStopEditing.apply(this, arguments);
		undoListener();
	};
	
	// Updates the button states once
    undoListener();
};

/**
* Updates the states of the given toolbar items based on the selection.
*/
EditorUi.prototype.updateActionStates = function()
{
	var graph = this.editor.graph;
	var ss = this.getSelectionState();
    var unlocked = graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent());

	// Updates action states
	var actions = ['cut', 'copy', 'bold', 'italic', 'underline', 'delete', 'duplicate',
	               'editStyle', 'editTooltip', 'editLink', 'backgroundColor', 'borderColor',
	               'edit', 'toFront', 'toBack', 'solid', 'dashed', 'pasteSize',
	               'dotted', 'fillColor', 'gradientColor', 'shadow', 'fontColor',
	               'formattedText', 'rounded', 'toggleRounded', 'strokeColor',
				   'sharp', 'snapToGrid'];
	
	for (var i = 0; i < actions.length; i++)
	{
		this.actions.get(actions[i]).setEnabled(ss.cells.length > 0);
	}

	this.actions.get('grid').setEnabled(!this.editor.chromeless || this.editor.editable);
	this.actions.get('pasteSize').setEnabled(this.copiedSize != null && ss.vertices.length > 0);
	this.actions.get('pasteData').setEnabled(this.copiedValue != null && ss.cells.length > 0);
	this.actions.get('setAsDefaultStyle').setEnabled(graph.getSelectionCount() == 1);
	this.actions.get('lockUnlock').setEnabled(!graph.isSelectionEmpty());
	this.actions.get('bringForward').setEnabled(ss.cells.length == 1);
	this.actions.get('sendBackward').setEnabled(ss.cells.length == 1);
	this.actions.get('rotation').setEnabled(ss.vertices.length == 1);
	this.actions.get('wordWrap').setEnabled(ss.vertices.length == 1);
	this.actions.get('autosize').setEnabled(ss.vertices.length == 1);
	this.actions.get('copySize').setEnabled(ss.vertices.length == 1);
	this.actions.get('clearWaypoints').setEnabled(ss.connections);
	this.actions.get('curved').setEnabled(ss.edges.length > 0);
	this.actions.get('turn').setEnabled(ss.cells.length > 0);
	this.actions.get('group').setEnabled(!ss.row && !ss.cell &&
		(ss.cells.length > 1 || (ss.vertices.length == 1 &&
		graph.model.getChildCount(ss.cells[0]) == 0 &&
		!graph.isContainer(ss.vertices[0]))));
	this.actions.get('ungroup').setEnabled(!ss.row && !ss.cell && !ss.table &&
		ss.vertices.length > 0 && (graph.isContainer(ss.vertices[0]) ||
		graph.getModel().getChildCount(ss.vertices[0]) > 0));
   	this.actions.get('removeFromGroup').setEnabled(ss.cells.length == 1 &&
   		graph.getModel().isVertex(graph.getModel().getParent(ss.cells[0])));
	this.actions.get('collapsible').setEnabled(ss.vertices.length == 1 &&
		(graph.model.getChildCount(ss.vertices[0]) > 0 ||
		graph.isContainer(ss.vertices[0])));
		this.actions.get('exitGroup').setEnabled(graph.view.currentRoot != null);
	this.actions.get('home').setEnabled(graph.view.currentRoot != null);
	this.actions.get('enterGroup').setEnabled(ss.cells.length == 1 &&
		graph.isValidRoot(ss.cells[0]));
	this.actions.get('editLink').setEnabled(ss.cells.length == 1);
	this.actions.get('openLink').setEnabled(ss.cells.length == 1 &&
		graph.getLinkForCell(ss.cells[0]) != null);
	this.actions.get('guides').setEnabled(graph.isEnabled());
    this.actions.get('selectVertices').setEnabled(unlocked);
    this.actions.get('selectEdges').setEnabled(unlocked);
    this.actions.get('selectAll').setEnabled(unlocked);
    this.actions.get('selectNone').setEnabled(unlocked);

	var foldable = ss.vertices.length == 1 &&
		graph.isCellFoldable(ss.vertices[0]);
	this.actions.get('expand').setEnabled(foldable);
	this.actions.get('collapse').setEnabled(foldable);

	// Updates menu states
    this.menus.get('navigation').setEnabled(ss.cells.length > 0 ||
		graph.view.currentRoot != null);
    this.menus.get('layout').setEnabled(unlocked);
    this.menus.get('insert').setEnabled(unlocked);
    this.menus.get('direction').setEnabled(ss.unlocked &&
		ss.vertices.length == 1);
    this.menus.get('distribute').setEnabled(ss.unlocked &&
		ss.vertices.length > 1);
    this.menus.get('align').setEnabled(ss.unlocked &&
		ss.cells.length > 0);

    this.updatePasteActionStates();
};

EditorUi.prototype.zeroOffset = new mxPoint(0, 0);

EditorUi.prototype.getDiagramContainerOffset = function()
{
	return this.zeroOffset;
};

/**
 * Refreshes the viewport.
 */
EditorUi.prototype.refresh = function(sizeDidChange)
{
	sizeDidChange = (sizeDidChange != null) ? sizeDidChange : true;
	
	var w = this.container.clientWidth;
	var h = this.container.clientHeight;

	if (this.container == document.body)
	{
		w = document.body.clientWidth || document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	}
	
	// Workaround for bug on iOS see
	// http://stackoverflow.com/questions/19012135/ios-7-ipad-safari-landscape-innerheight-outerheight-layout-issue
	// FIXME: Fix if footer visible
	var off = 0;

	if (mxClient.IS_IOS && !window.navigator.standalone && typeof Menus !== 'undefined')
	{
		if (window.innerHeight != document.documentElement.clientHeight)
		{
			off = document.documentElement.clientHeight - window.innerHeight;
			window.scrollTo(0, 0);
		}
	}
	
	var effHsplitPosition = Math.max(0, Math.min(this.hsplitPosition, w - this.splitSize - 20));
	var tmp = 0;
	
	if (this.menubar != null)
	{
		this.menubarContainer.style.height = this.menubarHeight + 'px';
		tmp += this.menubarHeight;
	}
	
	if (this.toolbar != null)
	{
		this.toolbarContainer.style.top = this.menubarHeight + 'px';
		this.toolbarContainer.style.height = this.toolbarHeight + 'px';
		tmp += this.toolbarHeight;
	}
	
	if (tmp > 0)
	{
		tmp += 1;
	}
	
	var sidebarFooterHeight = 0;
	
	if (this.sidebarFooterContainer != null)
	{
		var bottom = this.footerHeight + off;
		sidebarFooterHeight = Math.max(0, Math.min(h - tmp - bottom, this.sidebarFooterHeight));
		this.sidebarFooterContainer.style.width = effHsplitPosition + 'px';
		this.sidebarFooterContainer.style.height = sidebarFooterHeight + 'px';
		this.sidebarFooterContainer.style.bottom = bottom + 'px';
	}
	
	var fw = (this.format != null) ? this.formatWidth : 0;
	this.sidebarContainer.style.top = tmp + 'px';
	this.sidebarContainer.style.width = effHsplitPosition + 'px';
	this.formatContainer.style.top = tmp + 'px';
	this.formatContainer.style.width = fw + 'px';
	this.formatContainer.style.display = (this.format != null) ? '' : 'none';
	
	var diagContOffset = this.getDiagramContainerOffset();
	var contLeft = (this.hsplit.parentNode != null) ? (effHsplitPosition + this.splitSize) : 0;
	this.footerContainer.style.height = this.footerHeight + 'px';
	this.hsplit.style.top = this.sidebarContainer.style.top;
	this.hsplit.style.bottom = (this.footerHeight + off) + 'px';
	this.hsplit.style.left = effHsplitPosition + 'px';
	this.footerContainer.style.display = (this.footerHeight == 0) ? 'none' : '';
	
	if (this.tabContainer != null)
	{
		this.tabContainer.style.left = contLeft + 'px';
	}

	if (this.footerHeight > 0)
	{
		this.footerContainer.style.bottom = off + 'px';
	}
	
	var th = 0;
	
	if (this.tabContainer != null)
	{
		this.tabContainer.style.bottom = (this.footerHeight + off) + 'px';
		this.tabContainer.style.right = this.diagramContainer.style.right;
		th = this.tabContainer.clientHeight;
	}
	
	this.sidebarContainer.style.bottom = (this.footerHeight + sidebarFooterHeight + off) + 'px';
	this.formatContainer.style.bottom = (this.footerHeight + off) + 'px';

	if (urlParams['embedInline'] != '1')
	{
		this.diagramContainer.style.left =  (contLeft + diagContOffset.x) + 'px';
		this.diagramContainer.style.top = (tmp + diagContOffset.y) + 'px';
		this.diagramContainer.style.right = fw + 'px';
		this.diagramContainer.style.bottom = (this.footerHeight + off + th) + 'px';
	}

	if (sizeDidChange)
	{
		this.editor.graph.sizeDidChange();
	}
};

/**
 * Creates the required containers.
 */
EditorUi.prototype.createTabContainer = function()
{
	return null;
};

/**
 * Creates the required containers.
 */
EditorUi.prototype.createDivs = function()
{
	this.menubarContainer = this.createDiv('geMenubarContainer');
	this.toolbarContainer = this.createDiv('geToolbarContainer');
	this.sidebarContainer = this.createDiv('geSidebarContainer');
	this.formatContainer = this.createDiv('geSidebarContainer geFormatContainer');
	this.diagramContainer = this.createDiv('geDiagramContainer');
	this.footerContainer = this.createDiv('geFooterContainer');
	this.hsplit = this.createDiv('geHsplit');
	this.hsplit.setAttribute('title', mxResources.get('collapseExpand'));

	// Sets static style for containers
	this.menubarContainer.style.top = '0px';
	this.menubarContainer.style.left = '0px';
	this.menubarContainer.style.right = '0px';
	this.toolbarContainer.style.left = '0px';
	this.toolbarContainer.style.right = '0px';
	this.sidebarContainer.style.left = '0px';
	this.formatContainer.style.right = '0px';
	this.formatContainer.style.zIndex = '1';
	this.diagramContainer.style.right = ((this.format != null) ? this.formatWidth : 0) + 'px';
	this.footerContainer.style.left = '0px';
	this.footerContainer.style.right = '0px';
	this.footerContainer.style.bottom = '0px';
	this.footerContainer.style.zIndex = mxPopupMenu.prototype.zIndex - 3;
	this.hsplit.style.width = this.splitSize + 'px';
	this.sidebarFooterContainer = this.createSidebarFooterContainer();
	
	if (this.sidebarFooterContainer)
	{
		this.sidebarFooterContainer.style.left = '0px';
	}
	
	if (!this.editor.chromeless)
	{
		this.tabContainer = this.createTabContainer();
	}
	else
	{
		this.diagramContainer.style.border = 'none';
	}
};

/**
 * Hook for sidebar footer container. This implementation returns null.
 */
EditorUi.prototype.createSidebarFooterContainer = function()
{
	return null;
};

/**
 * Creates the required containers.
 */
EditorUi.prototype.createUi = function()
{
	// Creates menubar
	this.menubar = (this.editor.chromeless) ? null : this.menus.createMenubar(this.createDiv('geMenubar'));
	
	if (this.menubar != null)
	{
		this.menubarContainer.appendChild(this.menubar.container);
	}
	
	// Adds status bar in menubar
	if (this.menubar != null)
	{
		this.statusContainer = this.createStatusContainer();

		// Connects the status bar to the editor status
		this.editor.addListener('statusChanged', mxUtils.bind(this, function()
		{
			this.setStatusText(this.editor.getStatus());
		}));

		this.setStatusText(this.editor.getStatus());
		//不添加保存按钮,在菜单栏
		//this.menubar.container.appendChild(this.statusContainer);

		// Inserts into DOM
		this.container.appendChild(this.menubarContainer);
	}

	// Creates the sidebar
	this.sidebar = (this.editor.chromeless) ? null : this.createSidebar(this.sidebarContainer);
	
	if (this.sidebar != null)
	{
		this.container.appendChild(this.sidebarContainer);
	}
	
	// Creates the format sidebar
	this.format = (this.editor.chromeless || !this.formatEnabled) ? null : this.createFormat(this.formatContainer);
	
	if (this.format != null)
	{
		this.container.appendChild(this.formatContainer);
	}
	
	// Creates the footer
	var footer = (this.editor.chromeless) ? null : this.createFooter();
	
	if (footer != null)
	{
		this.footerContainer.appendChild(footer);
		this.container.appendChild(this.footerContainer);
	}

	if (this.sidebar != null && this.sidebarFooterContainer)
	{
		this.container.appendChild(this.sidebarFooterContainer);		
	}

	this.container.appendChild(this.diagramContainer);

	if (this.container != null && this.tabContainer != null)
	{
		this.container.appendChild(this.tabContainer);
	}

	// Creates toolbar
	this.toolbar = (this.editor.chromeless) ? null : this.createToolbar(this.createDiv('geToolbar'));
	
	if (this.toolbar != null)
	{
		//添加保存开始
		this.statusContainer = this.createStatusContainer();

		// Connects the status bar to the editor status
		this.editor.addListener('statusChanged', mxUtils.bind(this, function()
		{
			this.setStatusText(this.editor.getStatus());
		}));

		this.setStatusText(this.editor.getStatus());
		this.toolbar.container.appendChild(this.statusContainer);
		//添加保存结束


		this.toolbarContainer.appendChild(this.toolbar.container);
		this.container.appendChild(this.toolbarContainer);
	}

	// HSplit
	if (this.sidebar != null)
	{
		this.container.appendChild(this.hsplit);
		
		this.addSplitHandler(this.hsplit, true, 0, mxUtils.bind(this, function(value)
		{
			this.hsplitPosition = value;
			this.refresh();
		}));
	}
};

/**
 * Creates a new toolbar for the given container.
 */
EditorUi.prototype.createStatusContainer = function()
{
	var container = document.createElement('a');
	container.className = 'geItem geStatus';

	return container;
};

/**
 * Creates a new toolbar for the given container.
 */
EditorUi.prototype.setStatusText = function(value)
{
	this.statusContainer.innerHTML = value;
};

/**
 * Creates a new toolbar for the given container.
 */
EditorUi.prototype.createToolbar = function(container)
{
	return new Toolbar(this, container);
};

/**
 * Creates a new sidebar for the given container.
 */
EditorUi.prototype.createSidebar = function(container)
{
	return new Sidebar(this, container);
};

/**
 * Creates a new sidebar for the given container.
 */
EditorUi.prototype.createFormat = function(container)
{
	return new Format(this, container);
};

/**
 * Creates and returns a new footer.
 */
EditorUi.prototype.createFooter = function()
{
	return this.createDiv('geFooter');
};

/**
 * Creates the actual toolbar for the toolbar container.
 */
EditorUi.prototype.createDiv = function(classname)
{
	var elt = document.createElement('div');
	elt.className = classname;
	
	return elt;
};

/**
 * Updates the states of the given undo/redo items.
 */
EditorUi.prototype.addSplitHandler = function(elt, horizontal, dx, onChange)
{
	var start = null;
	var initial = null;
	var ignoreClick = true;
	var last = null;

	// Disables built-in pan and zoom in IE10 and later
	if (mxClient.IS_POINTER)
	{
		elt.style.touchAction = 'none';
	}
	
	var getValue = mxUtils.bind(this, function()
	{
		var result = parseInt(((horizontal) ? elt.style.left : elt.style.bottom));
	
		// Takes into account hidden footer
		if (!horizontal)
		{
			result = result + dx - this.footerHeight;
		}
		
		return result;
	});

	function moveHandler(evt)
	{
		if (start != null)
		{
			var pt = new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
			onChange(Math.max(0, initial + ((horizontal) ? (pt.x - start.x) : (start.y - pt.y)) - dx));
			mxEvent.consume(evt);
			
			if (initial != getValue())
			{
				ignoreClick = true;
				last = null;
			}
		}
	};
	
	function dropHandler(evt)
	{
		moveHandler(evt);
		initial = null;
		start = null;
	};
	
	mxEvent.addGestureListeners(elt, function(evt)
	{
		start = new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
		initial = getValue();
		ignoreClick = false;
		mxEvent.consume(evt);
	});
	
	mxEvent.addListener(elt, 'click', mxUtils.bind(this, function(evt)
	{
		if (!ignoreClick && this.hsplitClickEnabled)
		{
			var next = (last != null) ? last - dx : 0;
			last = getValue();
			onChange(next);
			mxEvent.consume(evt);
		}
	}));

	mxEvent.addGestureListeners(document, null, moveHandler, dropHandler);
	
	this.destroyFunctions.push(function()
	{
		mxEvent.removeGestureListeners(document, null, moveHandler, dropHandler);
	});	
};

/**
 * Translates this point by the given vector.
 * 
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
EditorUi.prototype.handleError = function(resp, title, fn, invokeFnOnClose, notFoundMessage)
{
	var e = (resp != null && resp.error != null) ? resp.error : resp;

	if (e != null || title != null)
	{
		var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
		var btn = mxResources.get('ok');
		title = (title != null) ? title : mxResources.get('error');
		
		if (e != null && e.message != null)
		{
			msg = mxUtils.htmlEntities(e.message);
		}

		this.showError(title, msg, btn, fn, null, null, null, null, null,
			null, null, null, (invokeFnOnClose) ? fn : null);
	}
	else if (fn != null)
	{
		fn();
	}
};

/**
 * Translates this point by the given vector.
 * 
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
EditorUi.prototype.showError = function(title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h, hide, onClose)
{
	var dlg = new ErrorDialog(this, title, msg, btn || mxResources.get('ok'),
		fn, retry, btn2, fn2, hide, btn3, fn3);
	var lines = Math.ceil((msg != null) ? msg.length / 50 : 1);
	this.showDialog(dlg.container, w || 340, h || (100 + lines * 20), true, false, onClose);
	dlg.init();
};

/**
 * Displays a print dialog.
 */
EditorUi.prototype.showDialog = function(elt, w, h, modal, closable, onClose, noScroll, transparent, onResize, ignoreBgClick)
{
	this.editor.graph.tooltipHandler.resetTimer();
	this.editor.graph.tooltipHandler.hideTooltip();
	
	if (this.dialogs == null)
	{
		this.dialogs = [];
	}
	
	this.dialog = new Dialog(this, elt, w, h, modal, closable, onClose, noScroll, transparent, onResize, ignoreBgClick);
	this.dialogs.push(this.dialog);
};

/**
 * Displays a print dialog.
 */
EditorUi.prototype.hideDialog = function(cancel, isEsc, matchContainer)
{
	if (this.dialogs != null && this.dialogs.length > 0)
	{
		if (matchContainer != null && matchContainer != this.dialog.container.firstChild)
		{
			return;
		}
		
		var dlg = this.dialogs.pop();
		
		if (dlg.close(cancel, isEsc) == false) 
		{
			//add the dialog back if dialog closing is cancelled
			this.dialogs.push(dlg);
			return;
		}
		
		this.dialog = (this.dialogs.length > 0) ? this.dialogs[this.dialogs.length - 1] : null;
		this.editor.fireEvent(new mxEventObject('hideDialog'));
		
		if (this.dialog == null && this.editor.graph.container.style.visibility != 'hidden')
		{
			window.setTimeout(mxUtils.bind(this, function()
			{
				if (this.editor.graph.isEditing() && this.editor.graph.cellEditor.textarea != null)
				{
					this.editor.graph.cellEditor.textarea.focus();
				}
				else
				{
					mxUtils.clearSelection();
					this.editor.graph.container.focus();
				}
			}), 0);
		}
	}
};

/**
 * Handles ctrl+enter keystroke to clone cells.
 */
EditorUi.prototype.ctrlEnter = function()
{
	var graph = this.editor.graph;

	if (graph.isEnabled())
	{
		try
		{
			var cells = graph.getSelectionCells();
		    var lookup = new mxDictionary();
		    var newCells = [];

		    for (var i = 0; i < cells.length; i++)
		    {
		    	// Clones table rows instead of cells
		    	var cell = (graph.isTableCell(cells[i])) ? graph.model.getParent(cells[i]) : cells[i];
		    	
		    	if (cell != null && !lookup.get(cell))
		    	{
		    		lookup.put(cell, true);
		            newCells.push(cell);
		        }
		    }
		    
			graph.setSelectionCells(graph.duplicateCells(newCells, false));
		}
		catch (e)
		{
			this.handleError(e);
		}
	}
};

/**
 * Display a color dialog.
 */
EditorUi.prototype.pickColor = function(color, apply)
{
	var graph = this.editor.graph;
	var selState = graph.cellEditor.saveSelection();
	var h = 230 + ((Math.ceil(ColorDialog.prototype.presetColors.length / 12) +
		Math.ceil(ColorDialog.prototype.defaultColors.length / 12)) * 17);
	
	var dlg = new ColorDialog(this, mxUtils.rgba2hex(color) || 'none', function(color)
	{
		graph.cellEditor.restoreSelection(selState);
		apply(color);
	}, function()
	{
		graph.cellEditor.restoreSelection(selState);
	});
	
	this.showDialog(dlg.container, 230, h, true, false);
	dlg.init();
};

/**
 * Adds the label menu items to the given menu and parent.
 */
EditorUi.prototype.openFile = function()
{
	// Closes dialog after open
	window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
	{
		this.hideDialog(cancel);
	}));

	// Removes openFile if dialog is closed
	this.showDialog(new OpenDialog(this).container, (Editor.useLocalStorage) ? 640 : 320,
			(Editor.useLocalStorage) ? 480 : 220, true, true, function()
	{
		window.openFile = null;
	});
};

/**
 * Extracs the graph model from the given HTML data from a data transfer event.
 */
EditorUi.prototype.extractGraphModelFromHtml = function(data)
{
	var result = null;
	
	try
	{
    	var idx = data.indexOf('&lt;mxGraphModel ');
    	
    	if (idx >= 0)
    	{
    		var idx2 = data.lastIndexOf('&lt;/mxGraphModel&gt;');
    		
    		if (idx2 > idx)
    		{
    			result = data.substring(idx, idx2 + 21).replace(/&gt;/g, '>').
    				replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
    		}
    	}
	}
	catch (e)
	{
		// ignore
	}
	
	return result;
};

/**
 * Opens the given files in the editor.
 */
EditorUi.prototype.readGraphModelFromClipboard = function(fn)
{
	this.readGraphModelFromClipboardWithType(mxUtils.bind(this, function(xml)
	{
		if (xml != null)
		{
			fn(xml);
		}
		else
		{
			this.readGraphModelFromClipboardWithType(mxUtils.bind(this, function(xml)
			{
				if (xml != null)
				{
					var tmp = decodeURIComponent(xml);
							
					if (this.isCompatibleString(tmp))
					{
						xml = tmp;
					}
				}
				
				fn(xml);
			}), 'text');
		}
	}), 'html');
};

/**
 * Opens the given files in the editor.
 */
EditorUi.prototype.readGraphModelFromClipboardWithType = function(fn, type)
{
	navigator.clipboard.read().then(mxUtils.bind(this, function(data)
	{
		if (data != null && data.length > 0 && type == 'html' &&
			mxUtils.indexOf(data[0].types, 'text/html') >= 0)
		{
			data[0].getType('text/html').then(mxUtils.bind(this, function(blob)
			{
				blob.text().then(mxUtils.bind(this, function(value)
				{
					try
					{
						var elt = this.parseHtmlData(value);
						var asHtml = elt.getAttribute('data-type') != 'text/plain';
						
						// KNOWN: Paste from IE11 to other browsers on Windows
						// seems to paste the contents of index.html
						var xml = (asHtml) ? elt.innerHTML :
							mxUtils.trim((elt.innerText == null) ?
							mxUtils.getTextContent(elt) : elt.innerText);
		
						// Workaround for junk after XML in VM
						try
						{
							var idx = xml.lastIndexOf('%3E');
							
							if (idx >= 0 && idx < xml.length - 3)
							{
								xml = xml.substring(0, idx + 3);
							}
						}
						catch (e)
						{
							// ignore
						}
						
						// Checks for embedded XML content
						try
						{
							var spans = elt.getElementsByTagName('span');
							var tmp = (spans != null && spans.length > 0) ? 
								mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
								decodeURIComponent(xml);
									
							if (this.isCompatibleString(tmp))
							{
								xml = tmp;
							}
						}
						catch (e)
						{
							// ignore
						}
					}
					catch (e)
					{
						// ignore
					}
					
					fn(this.isCompatibleString(xml) ? xml : null);
				}))['catch'](function(data)
				{
					fn(null);
				});
			}))['catch'](function(data)
			{
				fn(null);
			});
		}
		else if (data != null && data.length > 0 && type == 'text' &&
				mxUtils.indexOf(data[0].types, 'text/plain') >= 0)
		{
			data[0].getType('text/plain').then(function(blob)
			{
				blob.text().then(function(value)
				{
					fn(value);
				})['catch'](function()
				{
					fn(null);
				});
			})['catch'](function()
			{
				fn(null);
			});
		}
		else
		{
			fn(null);
		}
	}))['catch'](function(data)
	{
		fn(null);
	});
};

/**
 * Parses the given HTML data and returns a DIV.
 */
EditorUi.prototype.parseHtmlData = function(data)
{
	var elt = null;
	
	if (data != null && data.length > 0)
	{
		var hasMeta = data.substring(0, 6) == '<meta ';
		elt = document.createElement('div');
		elt.innerHTML = ((hasMeta) ? '<meta charset="utf-8">' : '') +
			this.editor.graph.sanitizeHtml(data);
		asHtml = true;
		
		// Workaround for innerText not ignoring style elements in Chrome
		var styles = elt.getElementsByTagName('style');
		
		if (styles != null)
		{
			while (styles.length > 0)
			{
				styles[0].parentNode.removeChild(styles[0]);
			}
		}
		
		// Special case of link pasting from Chrome
		if (elt.firstChild != null && elt.firstChild.nodeType == mxConstants.NODETYPE_ELEMENT &&
			elt.firstChild.nextSibling != null && elt.firstChild.nextSibling.nodeType == mxConstants.NODETYPE_ELEMENT &&
			elt.firstChild.nodeName == 'META' && elt.firstChild.nextSibling.nodeName == 'A' &&
			elt.firstChild.nextSibling.nextSibling == null)
		{
			var temp = (elt.firstChild.nextSibling.innerText == null) ?
				mxUtils.getTextContent(elt.firstChild.nextSibling) :
				elt.firstChild.nextSibling.innerText;
		
			if (temp == elt.firstChild.nextSibling.getAttribute('href'))
			{
				mxUtils.setTextContent(elt, temp);
				asHtml = false;
			}
		}

		// Extracts single image source address with meta tag in markup
		var img = (hasMeta && elt.firstChild != null) ? elt.firstChild.nextSibling : elt.firstChild;

		if (img != null && img.nextSibling == null &&
			img.nodeType == mxConstants.NODETYPE_ELEMENT &&
			img.nodeName == 'IMG')
		{
			var temp = img.getAttribute('src');
			
			if (temp != null)
			{
				if (Editor.isPngDataUrl(temp))
				{
					var xml = Editor.extractGraphModelFromPng(temp);
					
					if (xml != null && xml.length > 0)
					{
						temp = xml;
					}
				}

				mxUtils.setTextContent(elt, temp);
				asHtml = false;
			}
		}
		else
		{
			// Extracts embedded XML or image source address from single PNG image
			var images = elt.getElementsByTagName('img');

			if (images.length == 1)
			{
				var img = images[0];
				var temp = img.getAttribute('src');
				
				if (temp != null && img.parentNode == elt && elt.children.length == 1)
				{
					if (Editor.isPngDataUrl(temp))
					{
						var xml = Editor.extractGraphModelFromPng(temp);
						
						if (xml != null && xml.length > 0)
						{
							temp = xml;
						}
					}
					
					mxUtils.setTextContent(elt, temp);
					asHtml = false;
				}
			}
		}
		
		if (asHtml)
		{
			Graph.removePasteFormatting(elt);
		}
	}
	
	if (!asHtml)
	{
		elt.setAttribute('data-type', 'text/plain');
	}

	return elt;
};

/**
 * Opens the given files in the editor.
 */
EditorUi.prototype.extractGraphModelFromEvent = function(evt)
{
	var result = null;
	var data = null;
	
	if (evt != null)
	{
		var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
		
		if (provider != null)
		{
			if (document.documentMode == 10 || document.documentMode == 11)
			{
				data = provider.getData('Text');
			}
			else
			{
				data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
			
				if (mxUtils.indexOf(provider.types, 'text/plain' && (data == null || data.length == 0)))
				{
					data = provider.getData('text/plain');
				}
			}

			if (data != null)
			{
				data = Graph.zapGremlins(mxUtils.trim(data));
				
				// Tries parsing as HTML document with embedded XML
				var xml =  this.extractGraphModelFromHtml(data);
				
				if (xml != null)
				{
					data = xml;
				}
			}		
		}
	}
	
	if (data != null && this.isCompatibleString(data))
	{
		result = data;
	}
	
	return result;
};

/**
 * Hook for subclassers to return true if event data is a supported format.
 * This implementation always returns false.
 */
EditorUi.prototype.isCompatibleString = function(data)
{
	return false;
};

/**
 * Adds the label menu items to the given menu and parent.
 */
EditorUi.prototype.saveFile = function(forceDialog)
{
	if (!forceDialog && this.editor.filename != null)
	{
		this.save(this.editor.getOrCreateFilename());
	}
	else
	{
		var dlg = new FilenameDialog(this, this.editor.getOrCreateFilename(), mxResources.get('save'), mxUtils.bind(this, function(name)
		{
			this.save(name);
		}), null, mxUtils.bind(this, function(name)
		{
			if (name != null && name.length > 0)
			{
				return true;
			}
			
			mxUtils.confirm(mxResources.get('invalidName'));
			
			return false;
		}));
		this.showDialog(dlg.container, 300, 100, true, true);
		dlg.init();
	}
};

/**
 * Saves the current graph under the given filename.
 */
EditorUi.prototype.save = function(name)
{
	if (name != null)
	{
		if (this.editor.graph.isEditing())
		{
			this.editor.graph.stopEditing();
		}
		
		var xml = mxUtils.getXml(this.editor.getGraphXml());
		
		try
		{
			if (Editor.useLocalStorage)
			{
				if (localStorage.getItem(name) != null &&
					!mxUtils.confirm(mxResources.get('replaceIt', [name])))
				{
					return;
				}

				localStorage.setItem(name, xml);
				this.editor.setStatus(mxUtils.htmlEntities(mxResources.get('saved')) + ' ' + new Date());
			}
			else
			{
				if (xml.length < MAX_REQUEST_SIZE)
				{
					new mxXmlRequest(SAVE_URL, 'filename=' + encodeURIComponent(name) +
						'&xml=' + encodeURIComponent(xml)).simulate(document, '_blank');
				}
				else
				{
					mxUtils.alert(mxResources.get('drawingTooLarge'));
					mxUtils.popup(xml);
					
					return;
				}
			}

			this.editor.setModified(false);
			this.editor.setFilename(name);
			this.updateDocumentTitle();
		}
		catch (e)
		{
			this.editor.setStatus(mxUtils.htmlEntities(mxResources.get('errorSavingFile')));
		}
	}
};

/**
 * Executes the given layout.
 */
EditorUi.prototype.executeLayout = function(exec, animate, post)
{
	var graph = this.editor.graph;

	if (graph.isEnabled())
	{
		graph.getModel().beginUpdate();
		try
		{
			exec();
		}
		catch (e)
		{
			throw e;
		}
		finally
		{
			// Animates the changes in the graph model except
			// for Camino, where animation is too slow
			if (this.allowAnimation && animate && (navigator.userAgent == null ||
				navigator.userAgent.indexOf('Camino') < 0))
			{
				// New API for animating graph layout results asynchronously
				var morph = new mxMorphing(graph);
				morph.addListener(mxEvent.DONE, mxUtils.bind(this, function()
				{
					graph.getModel().endUpdate();
					
					if (post != null)
					{
						post();
					}
				}));
				
				morph.startAnimation();
			}
			else
			{
				graph.getModel().endUpdate();
				
				if (post != null)
				{
					post();
				}
			}
		}
	}
};

/**
 * Hides the current menu.
 */
EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting)
{
	var cellEditor = this.editor.graph.cellEditor;
	var selState = cellEditor.saveSelection();
	var newValue = mxUtils.prompt(title, value);
	cellEditor.restoreSelection(selState);
	
	if (newValue != null && newValue.length > 0)
	{
		var img = new Image();
		
		img.onload = function()
		{
			fn(newValue, img.width, img.height);
		};
		img.onerror = function()
		{
			fn(null);
			mxUtils.alert(mxResources.get('fileNotFound'));
		};
		
		img.src = newValue;
	}
	else
	{
		fn(null);
	}
};

/**
 * Hides the current menu.
 */
EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
{
	var dlg = new LinkDialog(this, value, btnLabel, fn);
	this.showDialog(dlg.container, 420, 90, true, true);
	dlg.init();
};

/**
 * Hides the current menu.
 */
EditorUi.prototype.showDataDialog = function(cell)
{
	if (cell != null)
	{
		var dlg = new EditDataDialog(this, cell);
		this.showDialog(dlg.container, 480, 420, true, false, null, false);
		dlg.init();
	}
};

/**
 * Hides the current menu.
 */
EditorUi.prototype.showBackgroundImageDialog = function(apply, img)
{
	apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
	{
		var change = new ChangePageSetup(this, null, image);
		change.ignoreColor = true;
		
		this.editor.graph.model.execute(change);
	});
	
	var newValue = mxUtils.prompt(mxResources.get('backgroundImage'), (img != null) ? img.src : '');
	
	if (newValue != null && newValue.length > 0)
	{
		var img = new Image();
		
		img.onload = function()
		{
			apply(new mxImage(newValue, img.width, img.height), false);
		};
		img.onerror = function()
		{
			apply(null, true);
			mxUtils.alert(mxResources.get('fileNotFound'));
		};
		
		img.src = newValue;
	}
	else
	{
		apply(null);
	}
};

/**
 * Loads the stylesheet for this graph.
 */
EditorUi.prototype.setBackgroundImage = function(image)
{
	this.editor.graph.setBackgroundImage(image);
	this.editor.graph.view.validateBackgroundImage();

	this.fireEvent(new mxEventObject('backgroundImageChanged'));
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
EditorUi.prototype.confirm = function(msg, okFn, cancelFn)
{
	if (mxUtils.confirm(msg))
	{
		if (okFn != null)
		{
			okFn();
		}
	}
	else if (cancelFn != null)
	{
		cancelFn();
	}
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
EditorUi.prototype.createOutline = function(wnd)
{
	var outline = new mxOutline(this.editor.graph);

	mxEvent.addListener(window, 'resize', function()
	{
		outline.update(false);
	});
	
	return outline;
};

// Alt+Shift+Keycode mapping to action
EditorUi.prototype.altShiftActions = {67: 'clearWaypoints', // Alt+Shift+C
  65: 'connectionArrows', // Alt+Shift+A
  76: 'editLink', // Alt+Shift+L
  80: 'connectionPoints', // Alt+Shift+P
  84: 'editTooltip', // Alt+Shift+T
  86: 'pasteSize', // Alt+Shift+V
  88: 'copySize', // Alt+Shift+X
  66: 'copyData', // Alt+Shift+B
  69: 'pasteData' // Alt+Shift+E
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
EditorUi.prototype.createKeyHandler = function(editor)
{
	var editorUi = this;
	var graph = this.editor.graph;
	var keyHandler = new mxKeyHandler(graph);

	var isEventIgnored = keyHandler.isEventIgnored;
	keyHandler.isEventIgnored = function(evt)
	{
		// Handles undo/redo/ctrl+./,/u via action and allows ctrl+b/i
		// only if editing value is HTML (except for FF and Safari)
		return !(mxEvent.isShiftDown(evt) && evt.keyCode == 9) &&
			((!this.isControlDown(evt) || mxEvent.isShiftDown(evt) ||
			(evt.keyCode != 90 && evt.keyCode != 89 && evt.keyCode != 188 &&
			evt.keyCode != 190 && evt.keyCode != 85)) && ((evt.keyCode != 66 && evt.keyCode != 73) ||
			!this.isControlDown(evt) ||  (this.graph.cellEditor.isContentEditing() &&
			!mxClient.IS_FF && !mxClient.IS_SF)) && isEventIgnored.apply(this, arguments));
	};
	
	// Ignores graph enabled state but not chromeless state
	keyHandler.isEnabledForEvent = function(evt)
	{
		return (!mxEvent.isConsumed(evt) && this.isGraphEvent(evt) && this.isEnabled() &&
			(editorUi.dialogs == null || editorUi.dialogs.length == 0));
	};
	
	// Routes command-key to control-key on Mac
	keyHandler.isControlDown = function(evt)
	{
		return mxEvent.isControlDown(evt) || (mxClient.IS_MAC && evt.metaKey);
	};

	var thread = null;
	
	// Helper function to move cells with the cursor keys
	function nudge(keyCode, stepSize, resize)
	{
		if (!graph.isSelectionEmpty() && graph.isEnabled())
		{
			stepSize = (stepSize != null) ? stepSize : 1;

			if (resize)
			{
				// Resizes all selected vertices
				graph.getModel().beginUpdate();
				try
				{
					var cells = graph.getSelectionCells();
					
					for (var i = 0; i < cells.length; i++)
					{
						if (graph.getModel().isVertex(cells[i]) && graph.isCellResizable(cells[i]))
						{
							var geo = graph.getCellGeometry(cells[i]);
							
							if (geo != null)
							{
								geo = geo.clone();
								
								if (keyCode == 37)
								{
									geo.width = Math.max(0, geo.width - stepSize);
								}
								else if (keyCode == 38)
								{
									geo.height = Math.max(0, geo.height - stepSize);
								}
								else if (keyCode == 39)
								{
									geo.width += stepSize;
								}
								else if (keyCode == 40)
								{
									geo.height += stepSize;
								}
								
								graph.getModel().setGeometry(cells[i], geo);
							}
						}
					}
				}
				finally
				{
					graph.getModel().endUpdate();
				}
			}
			else
			{
				// Moves vertices up/down in a stack layout
				var cell = graph.getSelectionCell();
				var parent = graph.model.getParent(cell);
				var scale = graph.getView().scale;
				var layout = null;

				if (graph.getSelectionCount() == 1 && graph.model.isVertex(cell) &&
					graph.layoutManager != null && !graph.isCellLocked(cell))
				{
					layout = graph.layoutManager.getLayout(parent);
				}
				
				if (layout != null && layout.constructor == mxStackLayout)
				{
					var index = parent.getIndex(cell);
					
					if (keyCode == 37 || keyCode == 38)
					{
						graph.model.add(parent, cell, Math.max(0, index - 1));
					}
					else if (keyCode == 39 ||keyCode == 40)
					{
						graph.model.add(parent, cell, Math.min(graph.model.getChildCount(parent), index + 1));
					}
				}
				else
				{
					var handler = graph.graphHandler;

					if (handler != null)
					{
						if (handler.first == null)
						{
							handler.start(graph.getSelectionCell(),
								0, 0, graph.getSelectionCells());
						}

						if (handler.first != null)
						{
							var dx = 0;
							var dy = 0;
							
							if (keyCode == 37)
							{
								dx = -stepSize;
							}
							else if (keyCode == 38)
							{
								dy = -stepSize;
							}
							else if (keyCode == 39)
							{
								dx = stepSize;
							}
							else if (keyCode == 40)
							{
								dy = stepSize;
							}

							handler.currentDx += dx * scale;
							handler.currentDy += dy * scale;
							handler.checkPreview();
							handler.updatePreview();
						}

						// Groups move steps in undoable change
						if (thread != null)
						{
							window.clearTimeout(thread);
						}
						
						thread = window.setTimeout(function()
						{
							if (handler.first != null)
							{
								var dx = handler.roundLength(handler.currentDx / scale);
								var dy = handler.roundLength(handler.currentDy / scale);
								handler.moveCells(handler.cells, dx, dy);
								handler.reset();
							}
						}, 400);
					}
				}
			}
		}
	};
	
	// Overridden to handle special alt+shift+cursor keyboard shortcuts
	var directions = {37: mxConstants.DIRECTION_WEST, 38: mxConstants.DIRECTION_NORTH,
			39: mxConstants.DIRECTION_EAST, 40: mxConstants.DIRECTION_SOUTH};
	
	var keyHandlerGetFunction = keyHandler.getFunction;

	mxKeyHandler.prototype.getFunction = function(evt)
	{
		if (graph.isEnabled())
		{
			// TODO: Add alt modified state in core API, here are some specific cases
			if (mxEvent.isShiftDown(evt) && mxEvent.isAltDown(evt))
			{
				var action = editorUi.actions.get(editorUi.altShiftActions[evt.keyCode]);

				if (action != null)
				{
					return action.funct;
				}
			}
			
			if (directions[evt.keyCode] != null && !graph.isSelectionEmpty())
			{
				// On macOS, Control+Cursor is used by Expose so allow for Alt+Control to resize
				if (!this.isControlDown(evt) && mxEvent.isShiftDown(evt) && mxEvent.isAltDown(evt))
				{
					if (graph.model.isVertex(graph.getSelectionCell()))
					{
						return function()
						{
							var cells = graph.connectVertex(graph.getSelectionCell(), directions[evt.keyCode],
								graph.defaultEdgeLength, evt, true);
			
							if (cells != null && cells.length > 0)
							{
								if (cells.length == 1 && graph.model.isEdge(cells[0]))
								{
									graph.setSelectionCell(graph.model.getTerminal(cells[0], false));
								}
								else
								{
									graph.setSelectionCell(cells[cells.length - 1]);
								}

								graph.scrollCellToVisible(graph.getSelectionCell());
								
								if (editorUi.hoverIcons != null)
								{
									editorUi.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
								}
							}
						};
					}
				}
				else
				{
					// Avoids consuming event if no vertex is selected by returning null below
					// Cursor keys move and resize (ctrl) cells
					if (this.isControlDown(evt))
					{
						return function()
						{
							nudge(evt.keyCode, (mxEvent.isShiftDown(evt)) ? graph.gridSize : null, true);
						};
					}
					else
					{
						return function()
						{
							nudge(evt.keyCode, (mxEvent.isShiftDown(evt)) ? graph.gridSize : null);
						};
					}
				}
			}
		}

		return keyHandlerGetFunction.apply(this, arguments);
	};

	// Binds keystrokes to actions
	keyHandler.bindAction = mxUtils.bind(this, function(code, control, key, shift)
	{
		var action = this.actions.get(key);
		
		if (action != null)
		{
			var f = function()
			{
				if (action.isEnabled())
				{
					action.funct();
				}
			};
    		
			if (control)
			{
				if (shift)
				{
					keyHandler.bindControlShiftKey(code, f);
				}
				else
				{
					keyHandler.bindControlKey(code, f);
				}
			}
			else
			{
				if (shift)
				{
					keyHandler.bindShiftKey(code, f);
				}
				else
				{
					keyHandler.bindKey(code, f);
				}
			}
		}
	});

	var ui = this;
	var keyHandlerEscape = keyHandler.escape;
	keyHandler.escape = function(evt)
	{
		keyHandlerEscape.apply(this, arguments);
	};

	// Ignores enter keystroke. Remove this line if you want the
	// enter keystroke to stop editing. N, W, T are reserved.
	keyHandler.enter = function() {};
	
	keyHandler.bindControlShiftKey(36, function() { graph.exitGroup(); }); // Ctrl+Shift+Home
	keyHandler.bindControlShiftKey(35, function() { graph.enterGroup(); }); // Ctrl+Shift+End
	keyHandler.bindShiftKey(36, function() { graph.home(); }); // Ctrl+Shift+Home
	keyHandler.bindKey(35, function() { graph.refresh(); }); // End
	keyHandler.bindAction(107, true, 'zoomIn'); // Ctrl+Plus
	keyHandler.bindAction(109, true, 'zoomOut'); // Ctrl+Minus
	keyHandler.bindAction(80, true, 'print'); // Ctrl+P
	keyHandler.bindAction(79, true, 'outline', true); // Ctrl+Shift+O

	if (!this.editor.chromeless || this.editor.editable)
	{
		keyHandler.bindControlKey(36, function() { if (graph.isEnabled()) { graph.foldCells(true); }}); // Ctrl+Home
		keyHandler.bindControlKey(35, function() { if (graph.isEnabled()) { graph.foldCells(false); }}); // Ctrl+End
		keyHandler.bindControlKey(13, function() { ui.ctrlEnter(); }); // Ctrl+Enter
		keyHandler.bindAction(8, false, 'delete'); // Backspace
		keyHandler.bindAction(8, true, 'deleteAll'); // Ctrl+Backspace
		keyHandler.bindAction(8, false, 'deleteLabels', true); // Shift+Backspace
		keyHandler.bindAction(46, false, 'delete'); // Delete
		keyHandler.bindAction(46, true, 'deleteAll'); // Ctrl+Delete
		keyHandler.bindAction(46, false, 'deleteLabels', true); // Shift+Delete
		keyHandler.bindAction(36, false, 'resetView'); // Home
		keyHandler.bindAction(72, true, 'fitWindow', true); // Ctrl+Shift+H
		keyHandler.bindAction(74, true, 'fitPage'); // Ctrl+J
		keyHandler.bindAction(74, true, 'fitTwoPages', true); // Ctrl+Shift+J
		keyHandler.bindAction(48, true, 'customZoom'); // Ctrl+0
		keyHandler.bindAction(82, true, 'turn'); // Ctrl+R
		keyHandler.bindAction(82, true, 'clearDefaultStyle', true); // Ctrl+Shift+R
		keyHandler.bindAction(83, true, 'save'); // Ctrl+S
		keyHandler.bindAction(83, true, 'saveAs', true); // Ctrl+Shift+S
		keyHandler.bindAction(65, true, 'selectAll'); // Ctrl+A
		keyHandler.bindAction(65, true, 'selectNone', true); // Ctrl+A
		keyHandler.bindAction(73, true, 'selectVertices', true); // Ctrl+Shift+I
		keyHandler.bindAction(69, true, 'selectEdges', true); // Ctrl+Shift+E
		keyHandler.bindAction(69, true, 'editStyle'); // Ctrl+E
		keyHandler.bindAction(66, true, 'bold'); // Ctrl+B
		keyHandler.bindAction(66, true, 'toBack', true); // Ctrl+Shift+B
		keyHandler.bindAction(70, true, 'toFront', true); // Ctrl+Shift+F
		keyHandler.bindAction(68, true, 'duplicate'); // Ctrl+D
		keyHandler.bindAction(68, true, 'setAsDefaultStyle', true); // Ctrl+Shift+D   
		keyHandler.bindAction(90, true, 'undo'); // Ctrl+Z
		keyHandler.bindAction(89, true, 'autosize', true); // Ctrl+Shift+Y
		keyHandler.bindAction(88, true, 'cut'); // Ctrl+X
		keyHandler.bindAction(67, true, 'copy'); // Ctrl+C
		keyHandler.bindAction(86, true, 'paste'); // Ctrl+V
		keyHandler.bindAction(71, true, 'group'); // Ctrl+G
		keyHandler.bindAction(77, true, 'editData'); // Ctrl+M
		keyHandler.bindAction(71, true, 'grid', true); // Ctrl+Shift+G
		keyHandler.bindAction(73, true, 'italic'); // Ctrl+I
		keyHandler.bindAction(76, true, 'lockUnlock'); // Ctrl+L
		keyHandler.bindAction(76, true, 'layers', true); // Ctrl+Shift+L
		keyHandler.bindAction(80, true, 'formatPanel', true); // Ctrl+Shift+P
		keyHandler.bindAction(85, true, 'underline'); // Ctrl+U
		keyHandler.bindAction(85, true, 'ungroup', true); // Ctrl+Shift+U
		keyHandler.bindAction(190, true, 'superscript'); // Ctrl+.
		keyHandler.bindAction(188, true, 'subscript'); // Ctrl+,
		keyHandler.bindAction(13, false, 'keyPressEnter'); // Enter
		keyHandler.bindKey(113, function() { if (graph.isEnabled()) { graph.startEditingAtCell(); }}); // F2
	}
	
	if (!mxClient.IS_WIN)
	{
		keyHandler.bindAction(90, true, 'redo', true); // Ctrl+Shift+Z
	}
	else
	{
		keyHandler.bindAction(89, true, 'redo'); // Ctrl+Y
	}
	
	return keyHandler;
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
EditorUi.prototype.destroy = function()
{
	var graph = this.editor.graph;

	if (graph != null && this.selectionStateListener != null)
	{
		graph.getSelectionModel().removeListener(mxEvent.CHANGE, this.selectionStateListener);
		graph.getModel().removeListener(mxEvent.CHANGE, this.selectionStateListener);
		graph.removeListener(mxEvent.EDITING_STARTED, this.selectionStateListener);
		graph.removeListener(mxEvent.EDITING_STOPPED, this.selectionStateListener);
		graph.getView().removeListener('unitChanged', this.selectionStateListener);
		this.selectionStateListener = null;
	}
	
	if (this.editor != null)
	{
		this.editor.destroy();
		this.editor = null;
	}
	
	if (this.menubar != null)
	{
		this.menubar.destroy();
		this.menubar = null;
	}
	
	if (this.toolbar != null)
	{
		this.toolbar.destroy();
		this.toolbar = null;
	}
	
	if (this.sidebar != null)
	{
		this.sidebar.destroy();
		this.sidebar = null;
	}
	
	if (this.keyHandler != null)
	{
		this.keyHandler.destroy();
		this.keyHandler = null;
	}
	
	if (this.keydownHandler != null)
	{
		mxEvent.removeListener(document, 'keydown', this.keydownHandler);
		this.keydownHandler = null;
	}
		
	if (this.keyupHandler != null)
	{
		mxEvent.removeListener(document, 'keyup', this.keyupHandler);
		this.keyupHandler = null;
	}
	
	if (this.resizeHandler != null)
	{
		mxEvent.removeListener(window, 'resize', this.resizeHandler);
		this.resizeHandler = null;
	}
	
	if (this.gestureHandler != null)
	{
		mxEvent.removeGestureListeners(document, this.gestureHandler);
		this.gestureHandler = null;
	}
	
	if (this.orientationChangeHandler != null)
	{
		mxEvent.removeListener(window, 'orientationchange', this.orientationChangeHandler);
		this.orientationChangeHandler = null;
	}
	
	if (this.scrollHandler != null)
	{
		mxEvent.removeListener(window, 'scroll', this.scrollHandler);
		this.scrollHandler = null;
	}

	if (this.destroyFunctions != null)
	{
		for (var i = 0; i < this.destroyFunctions.length; i++)
		{
			this.destroyFunctions[i]();
		}
		
		this.destroyFunctions = null;
	}
	
	var c = [this.menubarContainer, this.toolbarContainer, this.sidebarContainer,
	         this.formatContainer, this.diagramContainer, this.footerContainer,
	         this.chromelessToolbar, this.hsplit, this.sidebarFooterContainer,
	         this.layersDialog];
	
	for (var i = 0; i < c.length; i++)
	{
		if (c[i] != null && c[i].parentNode != null)
		{
			c[i].parentNode.removeChild(c[i]);
		}
	}
};