OSPE_VisuPanel.java 115 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
package osp.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import nom.tam.fits.FitsException;
import jsky.catalog.gui.CatalogNavigator;
import jsky.coords.DMS;
import jsky.coords.HMS;
import jsky.coords.WorldCoords;
import jsky.graphics.CanvasFigure;
import jsky.image.graphics.DivaImageGraphics;
import jsky.image.gui.ImageColorbar;
import jsky.image.gui.ImageCoordinateConverter;
import jsky.image.gui.ImageDisplayMenuBar;
import jsky.image.gui.ImagePanner;
import jsky.image.gui.ImageZoom;
import jsky.util.gui.ExampleFileFilter;
import osp.Detector;
import osp.FieldOfView;
import osp.Image;
import osp.InstrumentParameters;
import osp.Mask;
import osp.MaskHistoryEntry;
import osp.SkyObject;
import osp.Slit;
import osp.Writer;
import osp.utils.CustomJDialog;
import osp.utils.FileUtil;
import osp.utils.SearchWindow;
import osp.utils.TableurModel;
import osp.utils.TableurPanel;

/**
 * Right panel of MainFrame. Use to visualize image, choosing the reference
 * objects, positioning the mask and evaluating the slits positions.
 * 
 */

public class OSPE_VisuPanel extends JPanel implements Observer,
		VisuPanelNavigatorInterface, OSPE_VisuPanelInterface {
	private static final long serialVersionUID = 1L;

	private StatusInterface statusInterface;
	private JLabel projectLabel;
	private JPanel selectionSlitPanel;
	private ImagePanner imagePanner;
	private ImageZoom imageZoom;
	private JButton jButtonUnUn;
	private JButton jButtonZoomPlus;
	private JButton jButtonZoomMoins;
	public JComboBox<String> slitCombo;
	private JButton jButtonMoveZoom;
	public JSlider slide_position;
	public JSlider slide_aperture;
	private OSPE_SlitPropPanel slitPropertiesPanel;
	private JPanel imagePanel;
	private OSPE_NavigatorImageDisplay navigatorImageDisplay;
	private DivaImageGraphics divaImageGraphics;
	private OSPE_ImageCutLevelsDialog imCutDialog;

	private OSPE_ImageColorsDialog imColorsDialog;
	private ImageColorbar imColorBar;
	private JLabel jLabelDisplay;
	public JLabel jLabelFovSize;
	public JButton searchButton;
	public JButton validateButton;
	public JButton writeButton;
	public JProgressBar jpgb;
	
	protected FieldOfView fov;
	private JSpinner spinZoom;
	private OspeControl ospeControl;
	private TableurModel tablMod;
	
	private JPopupMenu mouseObjectPopupMenu;
	private JPopupMenu mouseGeneralPopupMenu;
	private Point2D.Double originPointer = new Point2D.Double();
	// def ds mouseMove - remonte ici pour garder la position de la souris en screen coord
	private Point2D.Double pointerPosDble = new Point2D.Double();
	// screen position of the mouse 
	private Point2D.Double mousePosition = new Point2D.Double();	
	private MouseEvent evtMouse;
		
	/** Image characteristics	 */
	private Image currentImage;
	/** Image center in (screen/canvas)? coord  */
	private Point2D.Double centerImage = new Point2D.Double();
	private int selectImage;
	private String newImageName=null;
	private String newImageCatalog="Local File";
	/** Image needed parameters for display */
	private double imResol;
	private double imWidth;
	private double imHeight;
	private float imScale;
	private Point2D.Double imCenter;
	
	/** Mask characteristics 	 */
	private Mask currentMask;
	private double originAngle;
	/** display needed parameters */
	private Point2D.Double maskDisplayCenter = new Point2D.Double();
	private Point2D.Double maskDisplayLeftCorner = new Point2D.Double();
	public boolean isMaskDisplayed = false;	
	
	/** Picking Objects*/
	public OSPE_PickObjectFrame pickObjFrame;
	private boolean isPickObjFrame;
	int objectId = -1;

	/** Windows Size of search for the near object in ??. */
	private static final int N_WIN = 20;
	protected ImageCoordinateConverter icc;
	private CanvasFigure canevasD = null;
	private CanvasFigure[] canevasH = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasMH = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasMB = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasB = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasHS = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasMHS = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasMBS = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure[] canevasBS = new CanvasFigure[Mask._NBRSLITS_];
	private CanvasFigure canevasT1 = null;
	private CanvasFigure canevasT2 = null;
	private CanvasFigure canevasT3 = null;
	private CanvasFigure canevasT4 = null;
	private CanvasFigure canvasTo1 = null;
	private CanvasFigure canvasTo2 = null;
	private CanvasFigure canevasM = null;
	private CanvasFigure[] canevasSpectre = new CanvasFigure[Mask._NBRSLITS_];
	
	private AffineTransform at = new AffineTransform();
	private AffineTransform at2 = new AffineTransform();
	
	public boolean isFromSlitComboBox = false;
	private CanvasFigure canvasObject;
	private List<CanvasFigure> listCanvasObjects1;
	private List<CanvasFigure> listCanvasObjects2;
	private List<CanvasFigure> listCanvasObjects3;
	private List<CanvasFigure> listCanvasObjects4;
	private CanvasFigure canvasBary;

	public float lWidth=1;
	 private SkyObject objChoosen;
	 private int idObjChoosen=-1;
	 private int idLastObjChoosen=-1;
	 
	Color[] colorTab={Color.RED, Color.ORANGE, Color.PINK, Color.MAGENTA, Color.LIGHT_GRAY};
	int nbColor=0;
	Color objColor=colorTab[nbColor];
	
	
	final Color red = Color.RED;
	final Color green = Color.GREEN;
	final Color greenTrans = new Color(0, 255, 0, 100);
	final Color blue = new Color(58, 163, 197);
	final Color blueTrans = new Color(58, 163, 197, 100);
	final Color trans = new Color(0, 0, 255, 0);
	final Color yellow = Color.YELLOW;
	final Color salmon = new Color(255, 128, 128);
	final int SMALL_DISPLAY_WIDTH = 80;
	
	private Writer theWriter;

	private JPanel smallDisplayPanel;

	private TableurPanel tableurPanel;
	private int colTab =0;
	private int lineTab = 0;

	private AccessMenuInterface accessMenuInterface;
	
	/**
	 * Constructor of the OSPE_VisuPanel, the visualization panel.
	 * 
	 * @param p
	 *            : Main frame Define the interface construction and the
	 *            functionalities
	 * @param fov 
	 * @param theWriter 
	 * @param tableurPanel 
	 */
	public OSPE_VisuPanel(StatusInterface statusInterface, AccessMenuInterface accessMenuInterface, 
			FieldOfView fov, Writer theWriter, TableurPanel tableurPanel) {
		super(new BorderLayout());
		this.statusInterface = statusInterface;
		this.accessMenuInterface = accessMenuInterface;
		this.fov = fov;
		this.theWriter = theWriter;
		this.tableurPanel = tableurPanel;
		
		this.divaImageGraphics = new DivaImageGraphics(getNavigatorImageDisplay());
		this.icc = new ImageCoordinateConverter(getNavigatorImageDisplay());
		
		this.isPickObjFrame = false;
		
		add(getProjectLabel(), BorderLayout.NORTH);
		add(getSelectionSlitPanel(), BorderLayout.WEST);
		add(getImagePanel(), BorderLayout.CENTER);
		
		buildMouseObjectPopupMenu();
		buildMouseGeneralPopupMenu();
		
		fov.addObserver(this);
		
		selectImage = -1;
		listCanvasObjects1 = new ArrayList<CanvasFigure>();
		listCanvasObjects2 = new ArrayList<CanvasFigure>();
		listCanvasObjects3 = new ArrayList<CanvasFigure>();
		listCanvasObjects4 = new ArrayList<CanvasFigure>();
	}

	/**
	 * 
	 */
	protected OSPE_ImageCutLevelsDialog getImageCutDialog() {
		if (imCutDialog == null){
			this.imCutDialog = new OSPE_ImageCutLevelsDialog(getNavigatorImageDisplay());
		}
		return imCutDialog;
	}

	/**
	 * 
	 */
	public OSPE_ImageColorsDialog getImageColorsDialog() {
		if (imColorsDialog == null){
			imColorsDialog = new OSPE_ImageColorsDialog(getNavigatorImageDisplay());
		}
		return imColorsDialog;
	}
	
	public void setControl(OspeControl ospeControl){
		this.ospeControl = ospeControl;
	}
	
	public void setWriter(Writer wi){
		this.theWriter = wi;
	}

	private JPanel getImagePanel() {
		if (imagePanel == null) {
			// add the panel for image manipulation (right)
			imagePanel = new JPanel(new BorderLayout());

			// Panel for the display (inside de imagePanel)
			JPanel displayPanel = new JPanel(new BorderLayout());
			displayPanel.setBorder(BorderFactory.createEtchedBorder());
			displayPanel.add(getNavigatorImageDisplay(), BorderLayout.CENTER);
			displayPanel.add(getImageColorBar(), BorderLayout.EAST);

			// add the different informations for the image
			JPanel jPanelLabels = new JPanel(new BorderLayout());
			displayPanel.add(jPanelLabels, BorderLayout.SOUTH);

			jPanelLabels.add(getDisplayLabel(), BorderLayout.WEST);
			jPanelLabels.add(getFovSizeLabel(), BorderLayout.EAST);
			imagePanel.add(displayPanel, BorderLayout.CENTER);

			// Definition of the used buttons to :
			JPanel buttonsAutomsPanel = new JPanel(new FlowLayout());
			buttonsAutomsPanel.add(getSearchButton());
			buttonsAutomsPanel.add(getValidateButton());
			buttonsAutomsPanel.add(getGenerateButton());
			imagePanel.add(buttonsAutomsPanel, BorderLayout.SOUTH);
		}
		return imagePanel;
	}

	//
	/**
	 * Size of what is seen in the win visu.
	 * 
	 * @return
	 */
	private JLabel getFovSizeLabel() {
		if (jLabelFovSize == null) {
			jLabelFovSize = new JLabel("Fov size : x-y");
		}
		return jLabelFovSize;
	}

	/**
	 * // Pointer world coordinates in image.
	 * 
	 * @return
	 */
	private JLabel getDisplayLabel() {
		if (jLabelDisplay == null) {
			jLabelDisplay = new JLabel("RA - DEC");
		}
		return jLabelDisplay;
	}

	/**
	 * To calculate the optimized mask
	 */
	private JButton getSearchButton() {
		if (searchButton == null) 
		{
			searchButton = new JButton("Search");
			searchButton.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					if (fov.getNbObjectsOfCurrentImage() <= 0) {
						new CustomJDialog("You need to add objects first.", CustomJDialog._ERROR_,
								CustomJDialog._CLOSE_BUTTON_, OSPE_VisuPanel.this);
						return;
					}
					final Point2D.Double pt=new Point2D.Double(0,0);
					
					if ((isMaskDisplayed) && (currentMask!= null)) 
						pt.setLocation(currentMask.getCenter());
						//pt.setLocation(maskDisplayCenter);
					
				   else
					   pt.setLocation(currentImage.getCenter());
				
				
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							new SearchWindow(OSPE_VisuPanel.this,pt);
						}
					});
				}
			});
			searchButton.setEnabled(false);
		}
		return searchButton;
	}

	/**
	 * To validate the current mask
	 */
	private JButton getValidateButton() {
		if (validateButton == null) {
			validateButton = new JButton("Validate");
			validateButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					onValidateButtonAction();
				}
			});
			validateButton.setEnabled(false);
		}
		return validateButton;
	}
	
	/**
	 * 
	 */
	private void onValidateButtonAction() {
		final Mask currentMask = fov.getCurrentMaskOfCurrentImage();
		boolean isCurrentMaskValidate = currentMask.validated;
		CustomJDialog dialog;
		if (!isCurrentMaskValidate) 
		{
			// test if there are enougth reference objects to define the mask position.
			if (testRefObjects()) 
			{
				// If there are enough reference objects
				currentMask.validated = true;
				currentMask.update();
				dialog = new CustomJDialog("The mask is validated. Do you want to write it ?",
						CustomJDialog._QUESTION_, CustomJDialog._YESNOCANCEL_BUTTON_, OSPE_VisuPanel.this);
				if (dialog.getValue() == JOptionPane.YES_OPTION) 
				{
					onWriteButtonAction();
				}
				validateButton.setText("Unvalidate");
			} 
			else 
			{
				dialog = new CustomJDialog("You don't have enough reference objects for the mask validation.",
						CustomJDialog._ERROR_, CustomJDialog._CLOSE_BUTTON_, OSPE_VisuPanel.this);
			}
		}
		else 
		{
			dialog = new CustomJDialog("You are going to cancel the mask validation.",
					CustomJDialog._WARNING_, CustomJDialog._YESNOCANCEL_BUTTON_, OSPE_VisuPanel.this);
			if (dialog.getValue() == JOptionPane.YES_OPTION) 
			{
				currentMask.validated = false;
				currentMask.update();
				validateButton.setText("Validate");
			}
		}
	}

	/**
	 * To generate the xml file with all the mask informations.
	 */
	private JButton getGenerateButton() {
		if (writeButton == null) 
		{
			writeButton = new JButton("Write");
			writeButton.addActionListener(new ActionListener() 
			{
				@Override
				public void actionPerformed(ActionEvent e)
				{
					onWriteButtonAction();
				}
			});
			writeButton.setEnabled(false);
		}
		return writeButton;
	}
	
	/**
	 * 
	 */
	private void onWriteButtonAction() {
		boolean noError=false;
		JFileChooser fileChooser = new JFileChooser(fov.getPath());
		final Mask currentMask = fov.getCurrentMaskOfCurrentImage();
		if (currentMask.getRefObjectsList().size()== 0)
		{				
			if (! testRefObjects())
			{
				new CustomJDialog(
					"You don't have enough reference objects to save the mask.",
					CustomJDialog._ERROR_, CustomJDialog._CLOSE_BUTTON_, OSPE_VisuPanel.this);
				return;
			}
		}
		currentMask.setM_uuid();
		fileChooser.setDialogTitle("Save Mask Configuration File");
		ExampleFileFilter filter = new ExampleFileFilter();
		filter.addExtension("xml");
		fileChooser.setFileFilter(filter);
		String fileMask="";
		int returnVal = fileChooser.showDialog(OSPE_VisuPanel.this, "Save as");
		if (returnVal == JFileChooser.APPROVE_OPTION) 
		{
			File file = fileChooser.getSelectedFile();
			if (file != null) 
			{
				fileMask=file.getAbsolutePath();
				int lgF=fileMask.length();
								
				String fileName = file.getName();
				int length = fileName.length();
				
				  if ((length>4) && ((fileName.substring(length - 4, length)).equals(".xml")))
				  {
					 fileMask=fileMask.substring(0,lgF - 4);
					theWriter.writeMask(currentMask, file.getAbsolutePath());
				  }
				 else
				 {
					theWriter.writeMask(currentMask,file.getAbsolutePath() + ".xml");
				 }
			}
			String [][] slitsArray =  ospeControl.getSlitsdetector(currentMask);

			double angleOffset=InstrumentParameters._OFFSET_IPA;
			
			noError = theWriter.writeMaskConfiguration(fileMask, currentMask);
			noError = theWriter.writeSlitsLocation(fileMask, slitsArray, currentMask, angleOffset);

		}
		
	} // End on_write_button

	/**
	 * Add a color bar on the right side
	 */
	private ImageColorbar getImageColorBar() {
		if (imColorBar == null) 
		{
			imColorBar = new ImageColorbar(navigatorImageDisplay);
			imColorBar.setOrient(SwingConstants.VERTICAL);
			imColorBar.setPreferredSize(new Dimension(20, 450));
			imColorBar.setBorder(BorderFactory.createEtchedBorder());
			imColorBar.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					imColorBar.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
				}
				@Override
				public void mouseReleased(MouseEvent e) {
					imColorBar.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
				}
				@Override
				public void mouseClicked(MouseEvent e) {
					if (e.getClickCount() >= 2)
						navigatorImageDisplay.editColors();
				}
			});
		}
		return imColorBar;
	}

	/**
	 * 
	 */
	private JLabel getProjectLabel() {
		if (projectLabel == null) {
			projectLabel = new JLabel("No selected image - No selected mask");
			projectLabel.setBorder(BorderFactory.createLineBorder(Color.black));
			projectLabel.setHorizontalAlignment(SwingConstants.CENTER);
			projectLabel.setHorizontalTextPosition(SwingConstants.CENTER);
		}
		return projectLabel;
	}

	/**
	 * Build the slits characteristics panel with the zooming function
	 */
	private JPanel getSelectionSlitPanel() {
		if (selectionSlitPanel == null) {
			selectionSlitPanel = new JPanel();
			selectionSlitPanel.setLayout(new BorderLayout());

			JPanel upSlitPanel = new JPanel();
			upSlitPanel.setLayout(new BoxLayout(upSlitPanel, BoxLayout.Y_AXIS));
			smallDisplayPanel = new JPanel(new FlowLayout());
			smallDisplayPanel.add(getImagePanner());
			smallDisplayPanel.add(getZoom());
			upSlitPanel.add(smallDisplayPanel);

			JPanel buttonsZoomPanel = new JPanel(new FlowLayout());
			buttonsZoomPanel.add(getUnUnButton());
			buttonsZoomPanel.add(getZoomPlusButton());
			buttonsZoomPanel.add(getZoomMoinsButton());
			upSlitPanel.add(buttonsZoomPanel);

			JPanel selectSlitPanel = new JPanel(new FlowLayout());
			selectSlitPanel.add(getSlitComboBox());
		//	selectSlitPanel.add(getMoveZoomButton());
		//	selectSlitPanel.add(getZoomSpin());
			upSlitPanel.add(selectSlitPanel);

			JPanel labelsPanel = new JPanel(new GridLayout(0, 2));
			labelsPanel.add(new JLabel("Position (arcsec)"));
			labelsPanel.add(new JLabel("Width (arcsec)"));
			upSlitPanel.add(labelsPanel);
			selectionSlitPanel.add(upSlitPanel, BorderLayout.NORTH);

			JPanel slitsSlidePanel = new JPanel(new GridLayout(0, 2));
			slitsSlidePanel.add(getPositionSlide());
			slitsSlidePanel.add(getApertureSlide());
			selectionSlitPanel.add(slitsSlidePanel, BorderLayout.CENTER);
			selectionSlitPanel.add(getSlitPropertiesPanel(), BorderLayout.SOUTH);
		}
		return selectionSlitPanel;
	}
	
	/**
	 * Set the slit sky coordinates.
	 * @param currentMask
	 * @param i : slit id
	 * @param X : X coord of slit start in canvas coord
	 * @param Y : Y coord of slit start in canvas coord
	 */
	private void setSlitSkyCoord(Mask currentMask, int i, double X, double Y) {
		Point2D.Double mPoint = new Point2D.Double(X,Y);
		// set the new slit's coordinates
		//icc.ImageToCanvasCoords(mPoint, false);
		WorldCoords wc = getWorldCoords(mPoint.getX(), mPoint.getY());
//System.out.println("visu:setSlitGal- 541  "+ i+" "+wc.getRA().toString()+" : "+wc.getDec().toString());
		currentMask.getSlit(i).setSkyPosition(wc.getRA(), wc.getDec());
	}

	
	
	private OSPE_SlitPropPanel getSlitPropertiesPanel() {
		if (slitPropertiesPanel == null) {
			slitPropertiesPanel = new OSPE_SlitPropPanel(this, fov, statusInterface);
			slitPropertiesPanel.getJComponent(OSPE_SlitPropPanel.posit).setEnabled(false);
			slitPropertiesPanel.getJComponent(OSPE_SlitPropPanel.aperture).setEnabled(false);
		}
		return slitPropertiesPanel;
	}

	private JSlider getApertureSlide() {
		if (slide_aperture == null) {
			slide_aperture = new JSlider(SwingConstants.VERTICAL);
			slide_aperture.addChangeListener(new ChangeListener() {
				@Override
				public void stateChanged(ChangeEvent e) {
					JSlider source = (JSlider)e.getSource();
//System.out.println("Visu 542 getApSlid flag "+	isFromSlitComboBox);			
					if (!isFromSlitComboBox) 
					{
						Slit currentSlit = fov.getCurrentImage().getCurrentMask().getCurrentSlit();
						double apeOri = currentSlit.getAperture();
				
//System.out.print("Visu 544 getApSlid "+apeOri+" Source val : "+source.getValue());
						if (!slide_aperture.getValueIsAdjusting()) {
//System.out.print("  - adjust Aper:  Source val : "+source.getValue());							
							adjustSlitAperture(slide_aperture.getValue(), currentSlit, apeOri);
						}
						fov.getCurrentImage().getCurrentMask().draggingSlides = slide_aperture
								.getValueIsAdjusting();
						// currentSlit.update();
						fov.getCurrentImage().getCurrentMask().update();
					}
//System.out.println(" A ");
				}
			});
			slide_aperture.setMajorTickSpacing(5);
			slide_aperture.setPaintTicks(true);
			slide_aperture.setEnabled(false);
		}
		return slide_aperture;
	}

	/**
	 * 
	 */
	private JSlider getPositionSlide() {
		if (slide_position == null) {
			slide_position = new JSlider(SwingConstants.VERTICAL);
			slide_position.addChangeListener(new ChangeListener() {
				@Override
				public void stateChanged(ChangeEvent e) {
					JSlider source = (JSlider)e.getSource();
					
//System.out.println("Visu 542 getPosSlid flag"+isFromSlitComboBox);	
					if (!isFromSlitComboBox) 
					{
						Slit currentSlit = fov.getCurrentImage().getCurrentMask().getCurrentSlit();
						double posOri = currentSlit.getPosition();
//System.out.print("Visu 544 getPosSlid Source val : "+ source.getValue() +" "+slide_position.getValue());
						//if (!slide_position.getValueIsAdjusting()) {
						if (!source.getValueIsAdjusting()) 
						{
//System.out.print(" - adjust Pos: ");																
						//adjustSlitPosition(slide_position.getValue(), currentSlit, posOri);
							adjustSlitPosition(source.getValue(), currentSlit, posOri);
						}
						//fov.getCurrentImage().getCurrentMask().draggingSlides = slide_position.getValueIsAdjusting();
						fov.getCurrentImage().getCurrentMask().draggingSlides = source.getValueIsAdjusting();
						currentSlit.update();
						fov.getCurrentImage().getCurrentMask().update();
					}
//System.out.println(" Out of listener P ");		
				}
			});
			slide_position.setMajorTickSpacing(20);
			slide_position.setPaintTicks(true);
			slide_position.setEnabled(false);
		}
		return slide_position;
	}

	/**
	 * @return
	 */
	private JSpinner getZoomSpin() {
		if (spinZoom == null) {
			spinZoom = new JSpinner(new SpinnerNumberModel(10, 1, 20, 1));
		}
		return spinZoom;
	}

	/**
	 * @return
	 */
	private JButton getMoveZoomButton() {
		if (jButtonMoveZoom == null) {
			jButtonMoveZoom = new JButton();

			jButtonMoveZoom.setText("Go &   Zoom x");
			jButtonMoveZoom.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					//moveToSlit(slitCombo.getSelectedIndex());
					zoomSet(Float.valueOf(getZoomSpin().getValue().toString()).floatValue());
				}
			});
			jButtonMoveZoom.setEnabled(false);
		}
		return jButtonMoveZoom;
	}

	/**
	 * 
	 */
	private JComboBox<String> getSlitComboBox() {
		if (slitCombo == null) {
			slitCombo = new JComboBox<String>();
			for (int i = 0; i < Mask._NBRSLITS_; i++) {
				String texte = new String();
				texte = "Slit " + (i+1);
				slitCombo.addItem(texte);
			}
			slitCombo.setEnabled(false);
			slitCombo.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
//System.out.print("Visu 645 - slitCombo Action listener flag true");						
					isFromSlitComboBox = true;

					if (slitCombo.getSelectedIndex() < 0)
						return;
					final Mask currentMask = fov.getCurrentImage().getCurrentMask();
					final Slit currentSlit = currentMask.getCurrentSlit();
					currentSlit.deleteObservers();
					currentMask.setCurrentSlit(slitCombo.getSelectedIndex());
					currentSlit.addObserver(OSPE_VisuPanel.this);
				
					slide_position.setValue((int) currentSlit.getPosition());
					slide_aperture.setValue((int) currentSlit.getAperture());
					currentSlit.update();
					isFromSlitComboBox = false;
//System.out.println("  Visu 660 - slitCombo Action listener flag false");						
				}
			});
		}
		return slitCombo;
	}

	/**
	 * 
	 */
	private JButton getZoomMoinsButton() {
		if (jButtonZoomMoins == null) {
			jButtonZoomMoins = new JButton();
			jButtonZoomMoins.setText("-");
			jButtonZoomMoins.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					zoomOut();
				}
			});
			jButtonZoomMoins.setEnabled(false);
		}

		return jButtonZoomMoins;
	}

	/**
	 * 
	 */
	private JButton getZoomPlusButton() {
		if (jButtonZoomPlus == null) {
			jButtonZoomPlus = new JButton();
			jButtonZoomPlus.setText("+");
			jButtonZoomPlus.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					zoomIn();
				}
			});
			jButtonZoomPlus.setEnabled(false);
		}
		return jButtonZoomPlus;
	}

	/**
	 * 
	 */
	private JButton getUnUnButton() {
		if (jButtonUnUn == null) {
			jButtonUnUn = new JButton();
			jButtonUnUn.setText("1:1");
			jButtonUnUn.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					if (fov.getCurrentImage().getSelectedMask() >= 0) {
						fov.getCurrentImage().getCurrentMask().init2Display();
					}
					zoomSet(1.0F);
				}
			});
			jButtonUnUn.setEnabled(false);
		}

		return jButtonUnUn;
	}

	/**
	 * 
	 */
	private ImagePanner getImagePanner() {
		if (imagePanner == null) {
			imagePanner = new ImagePanner(navigatorImageDisplay, SMALL_DISPLAY_WIDTH, SMALL_DISPLAY_WIDTH);
			imagePanner.setBorder(new LineBorder(navigatorImageDisplay.getBackground(), 1));
		}
		return imagePanner;
	}

	/**
	 * 
	 */
	private ImageZoom getZoom() {
		if (imageZoom == null) {
			imageZoom = new ImageZoom(navigatorImageDisplay, SMALL_DISPLAY_WIDTH, SMALL_DISPLAY_WIDTH, 4);
			imageZoom.setPropagateScale(true);
			imageZoom.setBorder(new LineBorder(navigatorImageDisplay.getBackground(), 1));
		}
		return imageZoom;
	}

	/**
	 * Creation of the mousePopUp menu which can permit : To set an object
	 * Referenced To remove an object To assign it to a slit To recalculate the
	 * centroid.
	 */

	public void buildMouseObjectPopupMenu() {
		mouseObjectPopupMenu = new JPopupMenu();

		mouseObjectPopupMenu.add(getRefCheckBoxMenuItem());
		mouseObjectPopupMenu.addSeparator();

		mouseObjectPopupMenu.add(getPlotSectrumMenuItem());
		mouseObjectPopupMenu.addSeparator();
		
		if (!isPickObjFrame) {
			mouseObjectPopupMenu.add(getRemoveObjectMenuItem());
			mouseObjectPopupMenu.addSeparator();
		}

		mouseObjectPopupMenu.add(getAssignToSlitMenuItem());
		mouseObjectPopupMenu.addSeparator();

		mouseObjectPopupMenu.add(getRecalculateCentroidMenuItem());
		mouseObjectPopupMenu.addSeparator();

		mouseObjectPopupMenu.add(revertCentroidMenuItem());
		/*
		mouseObjectPopupMenu.addSeparator();
		
		mouseObjectPopupMenu.add(addMaskAtPositionMenuItem());
		mouseObjectPopupMenu.addSeparator();
		
		mouseObjectPopupMenu.add(searchAtPositionMenuItem());
		*/
		mouseObjectPopupMenu.setVisible(false);
	}


	/** Menu Option - Revert calculation of the centroid 
	 * @return
	 */
	private JMenuItem revertCentroidMenuItem() 
	{
		JMenuItem revertCentroidMenuItem = new JMenuItem("Revert centroid value");
		
		revertCentroidMenuItem.addActionListener(new ActionListener() 
		{
			@Override
			public void actionPerformed(ActionEvent evt) 
			{
				int numObj = fov.getCurrentImage().getActiveObject();
				
				if (numObj> -1)
				{
				SkyObject sk = fov.getCurrentImage().getListObjects().get(numObj);
				sk.setPosPixRecalc(null);
				sk.setColorWithPriority(sk.getPriority());
//				String src=sk.getSrc().replace(" (R)", "");
//				sk.setSrc(src);
				updateByHand();
				//updateByHand("V revert cent");

				ospeControl.getActionControl().setSaveNeeded(true);
				mouseObjectPopupMenu.setVisible(false);
				}
			}
		});
		return revertCentroidMenuItem;
	}

	/** Menu Option - Recalculation of the centroid 
	 * @return
	 */
	private JMenuItem getRecalculateCentroidMenuItem() {
		JMenuItem recalcCentroidMenuItem = new JMenuItem("recalculate centroid");
		
		recalcCentroidMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				int numObj = fov.getCurrentImage().getActiveObject();
				
				if (numObj> -1)
				{
				SkyObject currentObject = fov.getCurrentImage().getListObjects().get(numObj);
				// mess = "DEBUG - MouseMenu  num Obj: " + numObj + " centre : "
				// + pCenter.x + " - " + pCenter.y;
				// System.out.println(mess);
				mouseObjectPopupMenu.setVisible(false);

				recalculateCentroid(currentObject);
				updateByHand();
				ospeControl.getActionControl().setSaveNeeded(true);
				}
			}
		});
		return recalcCentroidMenuItem;
	}

	/** Menu option : assigning a slit to the pointed object
	 * @return
	 */
	private JMenuItem getAssignToSlitMenuItem() {
		JMenuItem assignSlitMenuItem = new JMenuItem("assign to Slit");
		
		assignSlitMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				int refIdObj = fov.getCurrentImage().getActiveObject();
				if (refIdObj> -1)
				{
				associateObjectToSlit(refIdObj, fov
						.getCurrentImage().getCurrentMask());
				mouseObjectPopupMenu.setVisible(false);
				updateByHand();
				//updateByHand("V Asign slit menu");
				ospeControl.getActionControl().setSaveNeeded(true);
				}
			}
		});
		return assignSlitMenuItem;
	}

	/** Menu option : Removing the pointed object
	 * @return
	 */
	private JMenuItem getRemoveObjectMenuItem() {
		JMenuItem removeMenuItem = new JMenuItem("remove Object");
		
		removeMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				int refIdObj = fov.getCurrentImage().getActiveObject();
				if (refIdObj> -1)
				{
				fov.getCurrentImage().removeObject(refIdObj);
				mouseObjectPopupMenu.setVisible(false);
				navigatorImageDisplay.updateImage();
				updateByHand();
				//updateByHand("V del obj menu");
				ospeControl.getActionControl().setSaveNeeded(true);
				}
			}
		});
		return removeMenuItem;
	}

	/** Menu option : Plot the spectrum of the pointed object in the slit.
	 * @return
	 */
	private JMenuItem getPlotSectrumMenuItem() {
		JMenuItem plotSpectrumMenuItem = new JMenuItem("plot spectrum");
		
		plotSpectrumMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				Mask currentMask = fov.getCurrentImage().getCurrentMask();
				int refIdObj = fov.getCurrentImage().getActiveObject();
				if (refIdObj>-1)
				{
				int slitNum = searchAffectedSlitToObject(refIdObj);
				if (currentMask.getPlotSpectrum(slitNum))
					currentMask.setPlotSpectrum(slitNum, false);
				else
					currentMask.setPlotSpectrum(slitNum, true);

				accessMenuInterface.clickOnMenuDisplayPlotSelectedSpectra();
				mouseObjectPopupMenu.setVisible(false);
				}
			}
		});
		return plotSpectrumMenuItem;
	}

	/**
	 * @return
	 */
	private JCheckBoxMenuItem getRefCheckBoxMenuItem() {
		JCheckBoxMenuItem setRefCheckBoxMenuItem = new JCheckBoxMenuItem("is Reference");
		
		setRefCheckBoxMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				/** Set/unset the object reference propriety */
				final Image currentImage = fov.getCurrentImage();
				int refIdObj = currentImage.getActiveObject();
				if (refIdObj> -1)
				{
				SkyObject skyObject = currentImage.getListObjects().get(refIdObj);

				  if (skyObject.isRef()) 
				  {
					skyObject.setRef(false);

					if (currentImage.refObjNb > 0)
						currentImage.refObjNb--;
					else
						currentImage.refObjNb = 0;
				  }
				  else 
				  {
					skyObject.setRef(true);
					currentImage.refObjNb++;
				  }

				mouseObjectPopupMenu.setVisible(false);
				updateByHand();
				}
				//updateByHand("V Get ref check box menu");
			}
		});
		return setRefCheckBoxMenuItem;
	}

	/**
	 * Mouse menu when the pointed star is not an object
	 */
	public void buildMouseGeneralPopupMenu() {
		mouseGeneralPopupMenu = new JPopupMenu();

		mouseGeneralPopupMenu.add(addObjectMenuItem());
		//mouseGeneralPopupMenu.add(addObjectMenuItemMan());
		mouseGeneralPopupMenu.addSeparator();

		mouseGeneralPopupMenu.add(setNewCenterImageItem());
		/*
		mouseGeneralPopupMenu.addSeparator();
		
		mouseGeneralPopupMenu.add(addMaskAtPositionMenuItem());
		mouseGeneralPopupMenu.addSeparator();
		
		mouseGeneralPopupMenu.add(searchAtPositionMenuItem());
		*/
		mouseGeneralPopupMenu.setVisible(false);
	}
		
		/** Menu option : Add objects menu item
		 * @return
		 */
		private JMenuItem addObjectMenuItem() {
			JMenuItem addObjectMenuItem = new JMenuItem("Add Objects");
			addObjectMenuItem.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent evt) {
					setPickObjectFrame();
					
					mouseGeneralPopupMenu.setVisible(false);
					
				}
			});
			return addObjectMenuItem;
		}
		
		/** Menu option : 
		 * Centering image at the mouse position 
		 * @return 
		 */
		
		private JMenuItem setNewCenterImageItem() {
			JMenuItem newCenterImageItem = new JMenuItem("Center image at this position");
			newCenterImageItem.addActionListener(new ActionListener() 
			{
				@Override
				public void actionPerformed(ActionEvent evt) 
				{				
					//**  used for later traitement *// 
					if (fov.getSelectedImage() >= 0) 
					{
						/** Image center is in image coords */
						centerImage.x = fov.getCurrentImage().getCenter().getX();
						centerImage.y = fov.getCurrentImage().getCenter().getY();
						
						if (fov.getCurrentImage().getSelectedMask() >= 0) {
							// Set the new display coord of the mask - User Coord
							maskDisplayCenter.x = fov.getCurrentImage().getCurrentMask().getCenter().getX();
							maskDisplayCenter.y = fov.getCurrentImage().getCurrentMask().getCenter().getY();

						}
					}
					mouseGeneralPopupMenu.setVisible(false);
					
					Point2D.Double newOrig = new Point2D.Double(mousePosition.x, mousePosition.y);					
					icc.screenToCanvasCoords(newOrig, false);

					fov.getCurrentImage().setCenter(newOrig);
					fov.getCurrentImage().update();
					
				}
			});
			return newCenterImageItem;
		}	
		
		/** Menu option : add a new mask on image
		 * @return
		 */
		private JMenuItem addMaskAtPositionMenuItem() {
			JMenuItem addMaskItem = new JMenuItem("Add Masks at this position");
			addMaskItem.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent evt) {

//System.out.println("visu:setMaskWithCenter");	
//int x=(int) (mousePosition.x);
//int y=(int)(mousePosition.y);
//printTheMousePosition(x, y);
					icc.screenToCanvasCoords(mousePosition, false);
					ospeControl.addMask(mousePosition);
					mouseGeneralPopupMenu.setVisible(false);
				}
			});
			return addMaskItem;
		}
		
		/** Menu option : add a new mask on image
		 * @return
		 */
		private JMenuItem searchAtPositionMenuItem() {
			JMenuItem searchItem = new JMenuItem("Search masks at this position");
			searchItem.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent evt) {
					mouseGeneralPopupMenu.setVisible(false);
					icc.screenToCanvasCoords(mousePosition,	false);
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							new SearchWindow(OSPE_VisuPanel.this,mousePosition);
						}
					});
		
				}
			});
			return searchItem;
		}
	public void setPickObjectFrame() {
		if (!isPickObjFrame) {
			isPickObjFrame = true;
			pickObjFrame = new OSPE_PickObjectFrame(this);
			Cursor cursor = new Cursor(Cursor.DEFAULT_CURSOR);
			navigatorImageDisplay.setCursor(cursor);
			searchButton.setEnabled(false);
			validateButton.setEnabled(false);
			writeButton.setEnabled(false);
			accessMenuInterface.enableButtonsForPicObject(false);
			updateByHand();
			//updateByHand("V pick obj");
		}
	}
	
	/**
	 * Add object manually
	 * with the recalculation centroid proced
	 */
//	public void addObjectManual(Point2D.Double mPos) 
//	{
//		Point2D.Double pos= new Point2D.Double (mPos.x,mPos.y);
//		
//		this.icc.screenToCanvasCoords(pos, false);
//		
//		/* Get the nearest object from the click position
//		 */
//		pos=positonCalcul(pos);
//		
//		/* pass the object to the recalculation procedure */
//		   
//		addObject(-1,-1," ", pos,0);
//		updateByHand();
		
//	System.out.println("Visu - addObjMan ");
		
//	}

	
	/**
	 * Get the display of the visualization
	 * 
	 * @return display : OSPE_NavigatorImageDisplay
	 */
	@Override
	public OSPE_NavigatorImageDisplay getNavigatorImageDisplay() {
		if (navigatorImageDisplay == null) {
			navigatorImageDisplay = new OSPE_NavigatorImageDisplay();
			navigatorImageDisplay.setPreferredSize(new Dimension(450, 450));
			navigatorImageDisplay.setAutoCenterImage(false);
			navigatorImageDisplay.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					onNavigatorImageDisplayMousePressed(e);
				}
				@Override
				public void mouseReleased(MouseEvent e) {
					onNavigatorImageDisplayMouseReleased();
				}
				@Override
				public void mouseClicked(MouseEvent e) {
					onNavigatorImageDisplayMouseClicked(e);
				}
			});
			navigatorImageDisplay.addMouseMotionListener(new MouseMotionListener() {
				@Override
				public void mouseMoved(MouseEvent e) {
					onNavigatorImageDisplayMouseMoved(e.getX(), e.getY());
				}
				@Override
				public void mouseDragged(MouseEvent e) {
					onNavigatorImageDisplayMouseDragged(e);
				}
			});
			navigatorImageDisplay.addMouseWheelListener(new MouseWheelListener() {
				@Override
				public void mouseWheelMoved(MouseWheelEvent e) {
					onNavigatorImageDisplayMouseWheelMoved(e);
				}
			});
			navigatorImageDisplay.clear();
		}
		return navigatorImageDisplay;
	}
	
	/**
	 * The mouse click : <br>
	 * <b>Left</b> is used : <li>to change the image part you see in the field.
	 * <li>to move or turn a mask. <li>to pick, select an object or select a
	 * slit.</li> <b>Right</b>: <br>
	 * <i>if there is no mask :</i> <li>Add objects.</li>
	 * 
	 * <i> if there is a mask : </i> <li>To set reference object. <li>To
	 * de-select an object. <li>To assign the pointed object with a slit. <li>To
	 * recalculate the object centroid.
	 * 
	 */
	private void onNavigatorImageDisplayMouseClicked(MouseEvent e) {
		statusInterface.setStatusBarText("");
		removePopup();
		// get the screen mouse position
		mousePosition=new Point2D.Double(e.getX(),e.getY());
		
		if (fov.getSelectedImage() >= 0 && ! isPickObjFrame)
		{
		
//			final Image currentImage = fov.getCurrentImage();
//			final Mask currentMask = currentImage.getCurrentMask();
			if (SwingUtilities.isLeftMouseButton(e)) 
			{
//System.out.println(("Visu:mouse clic"));
//printTheMousePosition(e.getX(),e.getY());

				if (currentImage.getSelectedMask() >= 0) 
				{
					onNavigatorImageDisplayleftMouseClick(e, currentImage, currentMask);
				}
			} 
			else 
				if (SwingUtilities.isRightMouseButton(e))
				{
				//	int objectId = getTheNearObjectid(currentImage);	

				int objectId = getNearObjectid(currentImage);
//System.out.println("Visu onNavClicR - objectID "+objectId);
				rigthMouseClick(e, currentImage, currentMask, objectId);

			    }
		}
	}
 /**
  * Get the nearest object id of the mouse position
  * Calculation with canvas coord. 
  */
	private int getNearObjectid(Image currentImage) {
	
		boolean find = false;
		objectId=-1;
		List<SkyObject> tempList = currentImage.getListObjects();
		Point2D.Double tmpPoint = new Point2D.Double(mousePosition.x,mousePosition.y);
		
		icc.screenToCanvasCoords(tmpPoint, false);
		double testPtMinX=tmpPoint.getX()-10;
		double testPtMinY=tmpPoint.getY()-10;
		double testPtMaxX=tmpPoint.getX()+10;
		double testPtMaxY=tmpPoint.getY()+10;

		for (int i = 0; i < tempList.size() && !find; i++) 
		{
			WorldCoords tmpObj = new WorldCoords(tempList.get(i).getObjWorldCenter().getX(),tempList.get(i).getObjWorldCenter().getY());
			Point2D.Double tmpWc = new Point2D.Double(tmpObj.getX(),tmpObj.getY());
			icc.worldToCanvasCoords(tmpWc, false);	

			if ((testPtMinX < tmpWc.getX())
					&& (testPtMaxX > tmpWc.getX())
					&& (testPtMinY < tmpWc.getY())
					&& (testPtMaxY > tmpWc.getY()) )
			{
				// The pointed object is found.
				currentImage.setActiveObject(i);
			
				objectId = i;
				tableurPanel.selectCorrespondingRow(objectId);
				find = true;
			} 
			else
			{
				
				currentImage.setActiveObject(-1);
			}
			
			
			
		}
	
		return objectId;
	}
	

	/**
	 * Remove popup menus
	 */
	private void removePopup() {
		if (mouseObjectPopupMenu.isVisible()) {
			mouseObjectPopupMenu.setVisible(false);
		}
		if (mouseGeneralPopupMenu.isVisible()) {// || (isPickObjFrame) )
			mouseGeneralPopupMenu.setVisible(false);
		}
	}
	
	/**
	 * When rolling the mouse wheel, zoom in or zoom out. 
	 * @param e : mouse event
	 */
	private void onNavigatorImageDisplayMouseWheelMoved(MouseWheelEvent e) {
		if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL && fov.getSelectedImage() >= 0) {
			if (e.getWheelRotation() > 0){
				zoomIn();
			} else{
				zoomOut();
			}
		}
	}
	
	/**
	 * 
	 */
	private void onNavigatorImageDisplayMouseReleased() {
		navigatorImageDisplay.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

		if ((fov.getSelectedImage() >= 0) && (fov.getCurrentImage().getSelectedMask() >= 0)) {
			Mask currentMask = fov.getCurrentImage().getCurrentMask();
			maskDisplayCenter.x = fov.getCurrentImage().getCurrentMask().getCenter().getX();
			maskDisplayCenter.y = fov.getCurrentImage().getCurrentMask().getCenter().getY();
			
			Point2D.Double pt=new Point2D.Double(maskDisplayCenter.x,maskDisplayCenter.y);
			Point2D.Double ptL=new Point2D.Double(currentMask.getLeftCornerPix().getX(),currentMask.getLeftCornerPix().getY());
			
//System.out.println("Visu M relsed    Mlx: "+pt.x+" "+pt.y);
//icc.screenToWorldCoords(ptL, false);

//			icc.canvasToWorldCoords(pt, false);
// //			icc.userToWorldCoords(pt, false);
//			currentMask.setCenterDeg(pt);
//			currentMask.setCenterWc(pt.getX(), pt.getY());

			if (currentMask.moveEnable && !currentMask.turnEnable) {
				currentMask.moving = false;
				MaskHistoryEntry lastHistoryEntry = currentMask.getHistory().getLastEntry();
				if (currentMask.getCenter().equals(lastHistoryEntry.getValue("setCenter")))
					lastHistoryEntry.deleteAction("setCenter");
				if (currentMask.getCenter().equals(lastHistoryEntry.getValue("setCenterDeg")))
					lastHistoryEntry.deleteAction("setCenterDeg");
				if (currentMask.getAlpha().equals(lastHistoryEntry.getValue("setAlpha")))
					lastHistoryEntry.deleteAction("setAplha");
				if (currentMask.getDelta().equals(lastHistoryEntry.getValue("setDelta")))
					lastHistoryEntry.deleteAction("setDelta");
				if (lastHistoryEntry.isEmpty())
					currentMask.getHistory().deleteLastEntry();
			} else if (!currentMask.moveEnable && currentMask.turnEnable) {
				currentMask.turning = false;
				Double historyOmega = (Double) currentMask.getHistory().getLastEntry().getValue("setOmega");
				if (historyOmega == currentMask.getOmega())
					currentMask.getHistory().deleteLastEntry();
			}
		}
		evtMouse = null;
	}
	
	/**
	 * @param e
	 */
	private void onNavigatorImageDisplayMousePressed(MouseEvent e) {
		if ((fov.getSelectedImage() >= 0) && 
			(fov.getCurrentImage().getSelectedMask() >= 0)) {
			 currentMask = fov.getCurrentImage().getCurrentMask();

			if (currentMask.moveEnable) {
				moveCurrentMask(currentMask);
			} else if (currentMask.turnEnable) {
				turnCurrentMask(e, currentMask);
			}
		}

		originPointer.setLocation(e.getX(), e.getY());

		//**  used for later traitement *// 
		if (fov.getSelectedImage() >= 0) 
		{
			centerImage.x = fov.getCurrentImage().getCenter().getX();
			centerImage.y = fov.getCurrentImage().getCenter().getY();

			if (fov.getCurrentImage().getSelectedMask() >= 0) {
				// Set the new display coord of the mask - User Coord
				maskDisplayCenter.x = fov.getCurrentImage().getCurrentMask().getCenter().getX();
				maskDisplayCenter.y = fov.getCurrentImage().getCurrentMask().getCenter().getY();

			}
		}
	}

	/**
	 * @param e
	 * @param currentMask
	 */
	private void turnCurrentMask(MouseEvent e, Mask currentMask) {
		currentMask.turning = true;
		navigatorImageDisplay.setCursor(Cursor
				.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
		evtMouse = e;
//		eraseMask();
//		displayMask();
		originAngle = currentMask.getOmega();

		Double oldOmega = new Double(currentMask.getOmega());
		currentMask.getHistory().addEntry("Rotate mask");
		currentMask.getHistory().addAction("setOmega", oldOmega);
		ospeControl.getMainFrame().updateButtons();
	}

	/**
	 * @param currentMask
	 */
	private void moveCurrentMask(Mask currentMask) {
		currentMask.moving = true;
		navigatorImageDisplay.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));

		Point2D.Double oldCenter = new Point2D.Double(currentMask.getCenter().x,
				currentMask.getCenter().y);
		Point2D.Double oldCenterDeg = new Point2D.Double(
				currentMask.getCenterDeg().x, currentMask.getCenterDeg().y);
		Point2D.Double oldCenterWc = new Point2D.Double(
				currentMask.getMaskCenterWordlCoord().getRaDeg(), currentMask.getMaskCenterWordlCoord().getDecDeg());
		HMS oldAlpha = new HMS(currentMask.getAlpha());
		DMS oldDelta = new DMS(currentMask.getDelta());
		currentMask.getHistory().addEntry("Move mask");
		currentMask.getHistory().addAction("setCenter", oldCenter);
		currentMask.getHistory().addAction("setCenterDeg", oldCenterDeg);
		currentMask.getHistory().addAction("setCenterWc", oldCenterWc);
		ospeControl.getMainFrame().updateButtons();
//		currentMask.getHistory().addAction("setAlpha", oldAlpha);
//		currentMask.getHistory().addAction("setDelta", oldDelta);
		
	}

	/**
	 * Definition of the update function
	 */
	@Override
	public void updateByHand() 
	{	
		setProjectLabel();
		eraseVisu();
		checkSelectedImage();

		if (fov.getSelectedImage() >= 0) 
		{
			displayImage();
			setLabelFovSize();
			
			if (fov.getCurrentImage().getSelectedMask() >= 0 && !isPickObjFrame) 
			{
				enableCompo(true);
				displayMask();
				isMaskDisplayed = true;
			} else {
				enableCompo(false);
				isMaskDisplayed = false;

				if (isPickObjFrame) {
					displayMask();
					isMaskDisplayed = true;
				}
			}
			plotAllObjects();
			displayTableur();
		} 
		else 
		{
			int imNb = fov.getNbrImages();
			if (imNb > 0) 
			{
				fov.setSelectedImage((imNb - 1));
			} 
		}
		updateSlitProp();
		this.repaint();
		
//System.out.println("Visu 1532 -End updateByHand");
	}

	/**
	 * Erase all graphic components
	 */
	public void eraseVisu() {
		eraseSpectra();
		eraseMask();
		eraseAllObjects();
		eraseBary();
		eraseTableur();
	}

	/**
	 * @param enabled
	 */
	private void enableCompo(final boolean enabled) {
		slitCombo.setEnabled(enabled);
	//	jButtonMoveZoom.setEnabled(enabled);
		slide_position.setEnabled(enabled);
		slide_aperture.setEnabled(enabled);
		slitPropertiesPanel.getJComponent(OSPE_SlitPropPanel.posit).setEnabled(enabled);
		slitPropertiesPanel.getJComponent(OSPE_SlitPropPanel.aperture).setEnabled(enabled);
	}

	/**
	 * 
	 */
	private void checkSelectedImage() {
		if (selectImage != fov.getSelectedImage()) 
		{
			selectImage = fov.getSelectedImage();
			eraseImage();

			if (fov.getSelectedImage() >= 0) {
				//navigatorImageDisplay.setImage(fov.getCurrentImage().getFitsImage());
				navigatorImageDisplay.setFilename(fov.getCurrentImage().getAbsPath());
				int val= fov.getSelectedImage();
				updateCutLevels(val);
				updateColors(val);
				updateOfImageNavigatorDisplay();
				jButtonUnUn.setEnabled(true);
				jButtonZoomPlus.setEnabled(true);
				jButtonZoomMoins.setEnabled(true);
		//		jButtonMoveZoom.setEnabled(true);
			}
		}
	}

	/**
	 * Called when Observer event.
	 * 
	 */
	@Override
	public void update(Observable changed, Object arg) {
		updateByHand();
	}

	/**
	 * Update the slits properties when changes are validated.
	 */
	private void updateSlitProp() {

		slitPropertiesPanel.setValue(0, "");
		slitPropertiesPanel.setValue(1, "");

		if (fov.getSelectedImage() >= 0) {
			final Image currentImage = fov.getCurrentImage();
			if (currentImage.getSelectedMask() >= 0) {
				final Mask currentMask = currentImage.getCurrentMask();
				final Slit currentSlit = currentMask.getCurrentSlit();
				slitPropertiesPanel.setValue(0, currentSlit.getPosition());
				slitPropertiesPanel.setValue(1, currentSlit.getAperture());

//				imageZoom.setActive(true);
				Point2D.Double tmp = new Point2D.Double();
				at2.transform(currentSlit.getPosXY(), tmp);
//				imageZoom.zoom((int) tmp.getX(), (int) tmp.getY(), false);
//				imageZoom.setActive(false);
			}
		}
	}

	/**
	 * Update the slides properties
	 */
	@Override
	public void updateSlides() {
		isFromSlitComboBox = true;
//System.out.print(" Visu 1296 - UpdateSlide flag true ");	
		Slit currentSlit = fov.getCurrentImage().getCurrentMask().getCurrentSlit();

		int maxPos = (int) currentSlit.PosMax;
		int minPos = (int) currentSlit.PosMin;
		int midPos = 0;
		int valPos = (int) currentSlit.getPosition();
//System.out.print(" val : "+valPos+" ");		
		slide_position.setMaximum(maxPos);
		slide_position.setMinimum(minPos);
		slide_position.setValue(valPos);
		Hashtable<Integer, JLabel> labelTablePos = new Hashtable<Integer, JLabel>();
		labelTablePos.put(new Integer(minPos), new JLabel(String.valueOf(minPos)));
		labelTablePos.put(new Integer(midPos), new JLabel(String.valueOf(midPos)));
		labelTablePos.put(new Integer(maxPos), new JLabel(String.valueOf(maxPos)));
		slide_position.setLabelTable(labelTablePos);
		slide_position.setPaintLabels(true);

		int maxApe = (int) currentSlit.ApeMax;
		int minApe = (int) currentSlit.ApeMin;
		int valApe = (int) currentSlit.getAperture();

		slide_aperture.setMaximum(maxApe);
		slide_aperture.setMinimum(minApe);
		slide_aperture.setValue(valApe);
		Hashtable<Integer, JLabel> labelTableApe = new Hashtable<Integer, JLabel>();
		labelTableApe.put(new Integer(minApe), new JLabel(String.valueOf(minApe)));
		labelTableApe.put(new Integer(maxApe), new JLabel(String.valueOf(maxApe)));
		slide_aperture.setLabelTable(labelTableApe);
		slide_aperture.setPaintLabels(true);
//System.out.println("Visu 1316 - end updSlides flag false");
		isFromSlitComboBox = false;
	}

	/**
	 * Display the image and mask names in the title of the display.
	 */
	public void setProjectLabel() {
		String texte = null;

		if (fov.getSelectedImage() >= 0) {
			texte = "Selected image : " + fov.getCurrentImage().getProjImName();

			if (fov.getCurrentImage().getSelectedMask() >= 0) {
				texte = texte + " - Selected mask : "
						+ fov.getCurrentImage().getCurrentMask().getName();
			} else {
				texte = texte + "- No selected mask";
			}
		} else {
			texte = "No image - No mask";
		}
		projectLabel.setText(texte);
	}

	/**
	 * Erase the current image.
	 */
	public void eraseImage() {
		if (navigatorImageDisplay.getImage() != null){
			navigatorImageDisplay.clear();
		}

		jLabelDisplay.setText(" - ");

		jLabelFovSize.setText(" - ");

		jButtonUnUn.setEnabled(false);
		jButtonZoomPlus.setEnabled(false);
		jButtonZoomMoins.setEnabled(false);
	}


	/**
	 * This function is used to plot the image on the display.<br>
	 * <br>
	 * If an image is selected, the following events occur :
	 * <UL>
	 * <LI>Set the scale of the display to the current image scale.
	 * <LI>Compute the new origin in X and Y direction to keep the center of the
	 * display unchanged :<br>
	 * <b>NewOrigin.X = (ImageCenter.X * ImageScale) - (Display.Width / 2.0)</b>
	 * <br>
	 * <b>NewOrigin.Y = (ImageCenter.Y * ImageScale) - (Display.Height /
	 * 2.0)</b>
	 * <LI>Set the origin of the display to this shift.
	 * <LI>Display the image.
	 * <LI>Enable the access to the "Catalogue" menu.
	 * <LI>Enable the access to the "Fov->Remove Image" sub-menu.
	 * </UL>
	 * Else nothing appends.
	 */
	private void displayImage() {
		if (fov.getSelectedImage() >= 0){
		
			currentImage = fov.getCurrentImage();
			getImageDisplayParameters(currentImage);
	
			if ((currentImage.getAlpha()== null) || (currentImage.getDelta()==null))
			{	
				WorldCoords imCenter=getWorldCoords(currentImage.getCenter().getX(),
						currentImage.getCenter().getY());
				currentImage.setAlpha(imCenter.getRA());
				currentImage.setDelta(imCenter.getDec());
			}
			
			//navigatorImageDisplay.setScale(currentImage.getScale());
			navigatorImageDisplay.setScale(imScale);
			
			Point2D.Double newOrig = new Point2D.Double();
			newOrig.x = imCenter.getX() * imScale
					- navigatorImageDisplay.getWidth() / 2.0;
			newOrig.y = imCenter.getY() * imScale
					- navigatorImageDisplay.getHeight() / 2.0;
			navigatorImageDisplay.setOrigin(newOrig);
			navigatorImageDisplay.updateImage();
			ospeControl.getMainFrame().setTitle("OSP EDITOR - " + ospeControl.projectCompletePath );
			this.validate();
		}
	}

	/**
	 * Set the size of the field of view symbolized by the display window.
	 * 
	 */
	private void setLabelFovSize() {
		// Print the image size.
		DecimalFormat df = new DecimalFormat("########.00");

		double Wf = navigatorImageDisplay.getWidth() * fov.getCurrentImage().getResol()
				/ fov.getCurrentImage().getScale();
		double Hf = navigatorImageDisplay.getHeight() * fov.getCurrentImage().getResol()
				/ fov.getCurrentImage().getScale();

		jLabelFovSize.setText("Fov Size : " + df.format(Wf) + " x " + df.format(Hf) + " arcsec.");
	}

	/**
	 * When displaying an image with a mask with the positionned slits, the
	 * slits affected on objects are displayed in an array. This function tests
	 * if there is a slit affected to the object.
	 * 
	 * @param numObj
	 *            : id of the object
	 * @return slit id : slit id if found / else return (-1)
	 */
	private int searchAffectedSlitToObject(int numObj) {
		if (fov.getSelectedImage() < 0 || fov.getCurrentImage().getSelectedMask() < 0)
			return -1;

		for (int i = 1; i < ((Mask._NBRSLITS_)-1); i++) {
			if (fov.getCurrentImage().getCurrentMask().getSlit(i).getAffectedObject() == numObj)
				return i;
		}
		return -1;
	}

	/**
	 * Reinit the slits array.
	 */
	private void eraseTableur() {
		tablMod = tableurPanel.getModel();
		colTab = tablMod.getColumnCount() + 1;
		lineTab = 0;
		Object[][] tableData = new Object[lineTab][colTab];
		tableurPanel.getModel().fillTableModelPerso(tableData);
		tableurPanel.updateByHand();
	}

	/**
	 * Display the array with the slits affected to an object
	 */
	private void displayTableur() {
	    colTab  = tablMod.getColumnCount();
		final Image currentImage = fov.getCurrentImage();
		lineTab = currentImage.getListObjects().size();
		
		int nbIm=currentImage.getId();		
		
		Object[][] tableData = new Object[lineTab][colTab];

		for (int i = 0; i < lineTab; i++) {
			int j;
			for (j = 0; j < (colTab); j++) {
				tableData[i][j] = getObjectProp(i, j);
			}
		}

		for (int i = 0; i < currentImage.getListObjects().size(); i++) {
			if (currentImage.getSelectedMask() >= 0) {
				int affectedSlit = searchAffectedSlitToObject(i);
				if (affectedSlit <= 0)
					tableData[i][4] = "none";
				else
					tableData[i][4] = String.valueOf(affectedSlit + 1);
			} else
				tableData[i][4] = "none";
		}
		tableurPanel.getModel().fillTableModelPerso(tableData);
		//tableurPanel.getModel().setnewData(currentImage.getListObjects());
		tableurPanel.updateByHand();
	}

	
	
	/**
	 * Get the properties of an object for the tableur
	 * 
	 * @param objNum
	 *            The number of the object
	 * @param propNum
	 *            The property to retrieve
	 * @return The property corresponding to the given number.
	 */
	public Object getObjectProp(int objNum, int propNum) {
		SkyObject sk = fov.getCurrentImage().getListObjects().get(objNum);
		int idSlit=-1;
		switch (propNum) {
		    case 0 :
		    	// return the object num in project / on Image
				return sk.getNum();
		    case 1: 
		    	// return the object id
				return sk.getTargetId();			
			case 2:
				// Flag if is a reference
				return sk.isRef();
			case 3:
				// return the object priority
				return sk.getPriority();
			case 4:
				if (fov.getCurrentMaskOfCurrentImage() != null)
				{		
				  idSlit=getAffectedSlit(objNum);
				}
				// return the slit number if selected
			    return idSlit;	
			case 5:
				// get the object source type
				 String txt3;
				if (sk.getGroup() == -1) txt3=" ";
				else txt3=String.valueOf(sk.getGroup());
				return txt3;
			case 6:
			case 7:			
				// object world coordinates				 
				WorldCoords coords;
				boolean recalc=false;
				
				if (sk.isCenterRecalc())
				{
				   coords=sk.getObjWorldRecalc();
				   recalc=true;
				}
				else 
					coords=sk.getObjWorldCenter();
				
				if (propNum == 6)
				{
					  String txt1=coords.getRA().toString();
					  if (recalc) txt1=txt1+" (R)";
						return txt1;
					
				}
				else
				{
					String txt2=coords.getDec().toString();
					if (recalc) txt2=txt2+" (R)";
					return txt2;					
				}
								
			case 8:
				// return the object source catalog name 
				return sk.getProperty();
			default:
				return null;
		}
	}

	private int getAffectedSlit(int numObj) {
		// TODO Auto-generated method stub
		int idSlit=-1;
		Mask m=fov.getCurrentMaskOfCurrentImage();
		for (int i=0; i<55;i++)
		{
			Slit s=m.getSlit(i);
			int affObj=s.getAffectedObject();
			if (affObj==numObj) idSlit=i;
		}
		return idSlit;
	}

	/**
	 * Erase the current mask.
	 */
	public void eraseMask() {
		eraseSpectra();

		if (canevasD != null)
			divaImageGraphics.remove(canevasD);
		for (int i = 0; i < Mask._NBRSLITS_; i++) {
			if (canevasH[i] != null)
				divaImageGraphics.remove(canevasH[i]);
			if (canevasMH[i] != null)
				divaImageGraphics.remove(canevasMH[i]);
			if (canevasMB[i] != null)
				divaImageGraphics.remove(canevasMB[i]);
			if (canevasB[i] != null)
				divaImageGraphics.remove(canevasB[i]);
			if (canevasHS[i] != null)
				divaImageGraphics.remove(canevasHS[i]);
			if (canevasMHS[i] != null)
				divaImageGraphics.remove(canevasMHS[i]);
			if (canevasMBS[i] != null)
				divaImageGraphics.remove(canevasMBS[i]);
			if (canevasBS[i] != null)
				divaImageGraphics.remove(canevasBS[i]);
		}

		if (canevasT1 != null)
			divaImageGraphics.remove(canevasT1);
		if (canevasT2 != null)
			divaImageGraphics.remove(canevasT2);
		if (canevasT3 != null)
			divaImageGraphics.remove(canevasT3);
		if (canevasT4 != null)
			divaImageGraphics.remove(canevasT4);
		if (canevasM != null)
			divaImageGraphics.remove(canevasM);
	}

	/**
	 * Erase the spectra affected to the mask to be erased.
	 */
	public void eraseSpectra() {
		for (int i = 0; i < Mask._NBRSLITS_; i++) {
			if (canevasSpectre[i] != null)
				divaImageGraphics.remove(canevasSpectre[i]);
		}
	}

	/**
	 * Display the mask
	 */
	public void displayMask() {
		if (fov.getSelectedImage() < 0)
		 currentImage = fov.getCurrentImage();
		if (currentImage.getSelectedMask() < 0)
			return;

		currentMask = currentImage.getCurrentMask();
		
		double mCenterX = currentMask.getCenter().getX();
		double mCenterY = currentMask.getCenter().getY();
//		maskDisplayCenter.x = currentMask.getCenter().getX();
//		maskDisplayCenter.y = currentMask.getCenter().getY();
		double resol = currentImage.getResol();
		
		if (accessMenuInterface.isMenuDisplayPlotDetectorSelected()) {
			displayDetector(mCenterX, mCenterY, resol);
		}
		if (accessMenuInterface.isMenuDisplayPlotMaskSelected()) {
			displayPlotMask(currentMask, mCenterX, mCenterY, resol);
		}
		getTransformOfMask(currentMask);
		
		divaImageGraphics.repaint();
		this.validate();
	}

	/**
	 * @param currentMask
	 **/
	private void getTransformOfMask(Mask currentMask)
	{
		at = navigatorImageDisplay.getAffineTransform();
		at2.setToRotation(-currentMask.getOmega() * Math.PI / 180.0,
				currentMask.getCenter().getX(), currentMask.getCenter().getY());
		at2.preConcatenate(at);
		divaImageGraphics.transform(at2);
	}
	/**
	 * Drawing the mask on image.
	 * @param currentMask
	 * @param mkCenterX in canvas coord
	 * @param mkCenterY
	 * @param resol : image resolution
	 */
	private void displayPlotMask(Mask currentMask, double mkCenterX, double mkCenterY,
			double resol) {
		double l = currentMask.getlSlit2Display();
		/** Get mask Canvas dimensions */
		double width = currentMask.getWidth2Display();
		double height = currentMask.getHeight2Display();
		/** Get mask bottom left top corner coordinates in . coord */
		/** Get mask left top corner coordinates in screen coord */
		double maskStartX = mkCenterX - (width / 2.0);
		double maskStartY = mkCenterY - (height / 2.0);
	
		/** If the mask left bottom corner is not defined when displaying, fill it */
		
		    double maskStartYl = mkCenterY + (height / 2.0);
//System.out.println("Visu Plot M X "+mkCenterX+" "+mkCenterY);
			Point2D.Double tmpCorner = new Point2D.Double(maskStartX, maskStartYl);
			currentMask.setLeftCornerPix(tmpCorner);

		displaySlits(currentMask, resol, l, height, maskStartX, maskStartY);
		displayAssociatedSlits(currentMask, resol, l, height, maskStartX, maskStartY);
		
		if ((accessMenuInterface.isMenuDisplayPlotMaskCenterSelected()) && (!currentMask.moveEnable) && (!currentMask.turnEnable)) {
			drawCross(mkCenterX, mkCenterY, Color.orange);
		}	
		if (currentMask.moveEnable) {
			displayMovedMask(mkCenterX, mkCenterY, width, height, maskStartX, maskStartY);
		}
		
		if (currentMask.turnEnable) {
			displayTurnMask(currentMask);
		}
			
		isMaskDisplayed = true;
	}

	/**
	 * Drawing the mask when turning. 
	 * @param currentMask
	 */
	private void displayTurnMask(Mask currentMask) {
		Point2D.Double tmp = new Point2D.Double();
		// add to test - EB
		Point2D.Double mkCenter=new Point2D.Double(currentMask.getCenter().x,currentMask.getCenter().y);
		tmp=mkCenter;
		// end add
		//at2.transform(currentMask.getCenter(), tmp);
		
		Ellipse2D.Double ellipseH = new Ellipse2D.Double(tmp.x - 50, tmp.y - 50, 100, 100);
		canevasT1 = divaImageGraphics.makeEllipse(ellipseH, 1, trans, red, 5, null);
		divaImageGraphics.add(canevasT1);
		
		drawCross(tmp.x, tmp.y,red);

		if (evtMouse != null) {
			canevasT2 = divaImageGraphics.makeFigure(new Line2D.Double(tmp.x, tmp.y,
					evtMouse.getX(), evtMouse.getY()), red, red, lWidth);
			divaImageGraphics.add(canevasT2);
		}
	}

	/** Drawing the mask when moving. 
	 * @param mkCenterX (in canvas coord) 
	 * @param mkCenterY
	 * @param width
	 * @param height
	 * @param maskDebutX
	 * @param maskDebutY
	 */
	private void displayMovedMask(double mkCenterX, double mkCenterY, double width,
			double height, double maskDebutX, double maskDebutY) {
		Rectangle2D.Double peri = new Rectangle2D.Double(maskDebutX, maskDebutY, width,
				height);
		canevasM = divaImageGraphics.makeRectangle(peri, 1, trans, red, lWidth, null);
		divaImageGraphics.add(canevasM);
		drawCross(mkCenterX, mkCenterY, red);
	}

	/**
	 *  To draw a cross at the given coordinates . 
	 *   (used for mask center)
	 * @param x : x coordinate of the cross center
	 * @param y : y coordinate of the cross center
	 * @param co : drawing color
	 * lWidth : line thickness 
	 */
	private void drawCross(double x, double y, Color co) {
		canevasT3 = divaImageGraphics.makeFigure(new Line2D.Double(x - 10,
				y, x + 10, y), co, co, lWidth+1);
		divaImageGraphics.add(canevasT3);
		canevasT4 = divaImageGraphics.makeFigure(new Line2D.Double(x,
				y - 10, x, y + 10), co, co, lWidth+1);
		divaImageGraphics.add(canevasT4);
	}

	
	
	/**
	 * Displaying joined slits when selected (TBC) 
	 * @param currentMask : displayed mask
	 * @param resol : image resolution
	 * @param l : mask length
	 * @param height : mask height
	 * @param maskStartX : x start mask coordinate
	 * @param maskStartY : y start mask coordinate
	 */
	private void displayAssociatedSlits(Mask currentMask, double resol, double l, double height,
			double maskStartX, double maskStartY) {
		int selectedSlit = currentMask.getSelectedSlit();
		int associatedMinSlit = currentMask.getAssociatedMinSlit(selectedSlit);
		int associatedMaxSlit = currentMask.getAssociatedMaxSlit(selectedSlit);

		if (associatedMinSlit < 0)
			associatedMinSlit = selectedSlit;
		if (associatedMaxSlit < 0)
			associatedMaxSlit = selectedSlit;
		
		for (int k = associatedMinSlit; k <= associatedMaxSlit; k++) {
			double X1 = maskStartX + l * k;
			double Y1 = maskStartY;
			double W1 = l;
		
			double SP = (currentMask.getSlit(k).PosMax + currentMask.getSlit(k).getPosition())
					/ resol;
			double SW = (currentMask.getSlit(k).getAperture()) / resol;

			double H1 = height - SP - (SW / 2.0);
			Rectangle2D.Double rect1 = new Rectangle2D.Double(X1, Y1, W1, H1);

			double X2 = maskStartX + l * k;
			double Y2 = maskStartY + H1 + SW;
			double W2 = l;
			double H2 = SP - (SW / 2.0);
			Rectangle2D.Double rect2 = new Rectangle2D.Double(X2, Y2, W2, H2);

			double X3 = X1;
			double Y3 = Y1 + H1;
			double W3 = l;
			double H3 = SW;
			Rectangle2D.Double rect3 = new Rectangle2D.Double(X3, Y3, W3, 0);
			Rectangle2D.Double rect4 = new Rectangle2D.Double(X3, Y3 + H3, W3, 0);

			canevasHS[k] = divaImageGraphics.makeRectangle(rect1, 1, greenTrans, green, lWidth, null);
			canevasBS[k] = divaImageGraphics.makeRectangle(rect2, 1, greenTrans, green, lWidth, null);
			canevasMHS[k] = divaImageGraphics.makeRectangle(rect3, 1, trans, yellow, lWidth, null);
			canevasMBS[k] = divaImageGraphics.makeRectangle(rect4, 1, trans, yellow, lWidth, null);

			divaImageGraphics.add(canevasHS[k]);
			divaImageGraphics.add(canevasBS[k]);
			divaImageGraphics.add(canevasMHS[k]);
			divaImageGraphics.add(canevasMBS[k]);

			// Non pas correct. 
//			currentMask.getSlit(k).setPosXY((X2 + currentMask.getlSlit2Display() / 2.0),
//					(Y2 - SW / 2.0));
//			double x, y;
//			x=X3+(W3/2);
//			y=Y3+(-H3/2);
//			Slit s=currentMask.getSlit(k);
//			System.out.println("Visu displAssSlit "+k+" "+X3+" "+Y3);
		}
	}

	/**
	 * Displaying the mask slits
	 @param currentMask : displayed mask
	 * @param resol : image resolution
	 * @param lg : mask length
	 * @param height : mask height
	 * @param maskStartX : x start mask coordinate
	 * @param maskStartY : y start mask coordinate
	 */
	private void displaySlits(Mask currentMask, double resol, double lg, double height,
			double maskStartX, double maskStartY) {
		for (int i = 0; i < Mask.get_NBRSLITS_(); i++) {
			
			double X1 = maskStartX + lg * i;
			double Y1 = maskStartY;
			double W1 = lg;

			/** SW aperture size */ 
			/** l : slit length */
			double SP = (currentMask.getSlit(i).PosMax + currentMask.getSlit(i).getPosition()) / resol;
			double SW = (currentMask.getSlit(i).getAperture()) / resol;

			double H1 = height - SP - (SW / 2.0);
			Rectangle2D.Double rect1 = new Rectangle2D.Double(X1, Y1, W1, H1);

			double X2 = maskStartX + i * lg;
			double Y2 = maskStartY + H1 + SW;
			double W2 = lg;
			double H2 = SP - (SW / 2.0);
			Rectangle2D.Double rect2 = new Rectangle2D.Double(X2, Y2, W2, H2);

			double X3 = X1;
			double Y3 = Y1 + H1;
			double W3 = lg;
			double H3 = SW;
			Rectangle2D.Double rect3 = new Rectangle2D.Double(X3, Y3, W3, 0);
			Rectangle2D.Double rect4 = new Rectangle2D.Double(X3, Y3 + H3, W3, 0);
			
			double slitX;
			double slitY;
			double omg=currentMask.getOmega();
			
			if (omg == 0.0)
			{
			 slitX=X3+(lg/2.0);
			 slitY=Y3+(H3/2.0);
			}
			else 
			{
				slitX=X3+(Math.pow((Math.pow(lg,2)+Math.pow(SW,2)),(1/2))*(Math.cos(omg+Math.atan(SW/lg))));
				slitY=Y3+(Math.pow((Math.pow(lg,2)+Math.pow(SW,2)),(1/2))*(Math.sin(omg+Math.atan(SW/lg))));;
			} 
			
		//	setSlitSkyCoord(currentMask, i, slitX, slitY);
			
			canevasH[i] = divaImageGraphics.makeRectangle(rect1, 1, blueTrans, blue, lWidth, null);
			canevasB[i] = divaImageGraphics.makeRectangle(rect2, 1, blueTrans, blue, lWidth, null);
			canevasMH[i] = divaImageGraphics.makeRectangle(rect3, 1, trans, yellow, lWidth, null);
			canevasMB[i] = divaImageGraphics.makeRectangle(rect4, 1, trans, yellow, lWidth, null);

			divaImageGraphics.add(canevasH[i]);
			divaImageGraphics.add(canevasB[i]);
			divaImageGraphics.add(canevasMH[i]);
			divaImageGraphics.add(canevasMB[i]);

			if (fov.getPlotSpectra() == FieldOfView._PLOTALL_ || currentMask.getPlotSpectrum(i)
					&& fov.getPlotSpectra() != FieldOfView._PLOTNONE_)
				displaySpectra(i, X3, Y3, W3, H3);
		}
		
		
	}

	/**
	 * Display Detector : the frame of the mask
	 * @param mCenterX maskCenter
	 * @param mCenterY
	 * @param resol
	 */
	private void displayDetector(double mCenterX, double mCenterY, double resol) {
		double detectWidth = Detector._WIDTH_ / resol;
		double detectHeight = Detector._HEIGHT_ / resol;
		double detecDebutX = mCenterX - (detectWidth / 2.0);
		double detecDebutY = mCenterY - (detectHeight / 2.0);
		Rectangle2D.Double detector = new Rectangle2D.Double(detecDebutX, detecDebutY, detectWidth,
				detectHeight);
		canevasD = divaImageGraphics.makeRectangle(detector, 1, trans, salmon, lWidth, null);
		divaImageGraphics.add(canevasD);
	}


	/**
	 * Display the spectrum to the selected slit which coordinates are in
	 * parameters
	 * 
	 * @param i
	 *            : slit id ??
	 * @param X
	 *            : X slit coordinate
	 * @param Y
	 *            : Y slit coordinate
	 * @param W
	 *            : slit Width
	 * @param H
	 *            : slit Height
	 */
	public void displaySpectra(int i, double X, double Y, double W, double H) {
		if (fov.getCurrentImage().getCurrentMask().getSlit(i).getAffectedObject() < 0)
			return;

		Color orange = new Color(255, 128, 64);
		Color orangeTrans = new Color(255, 128, 64, 100);

		Rectangle2D.Double peri = new Rectangle2D.Double(X, (Y - H / 2.0) - 100, W, 200);
		canevasSpectre[i] = divaImageGraphics.makeRectangle(peri, 1, orangeTrans, orange, lWidth, null);
		divaImageGraphics.add(canevasSpectre[i]);
	}

	public void recalculateCentroid(SkyObject sk) {
		Image currentImage = fov.getCurrentImage();
		
		Point2D.Double pos = new Point2D.Double(0.0,0.0);
		
		pos = positonCalcul(sk.getPosition());
		 
		 sk.setPosPixRecalc(pos);
		 sk.setColor(Color.GREEN);
		 
		icc.imageToCanvasCoords(pos, false);
		
		sk.setObjWorldRecalc(getWorldCoords(pos.getX(), pos.getY()));
		
		/**
		 * Information that the object center has been recalculated
		 */
//		String src="";
//		if (!sk.getSrc().isEmpty())  src=sk.getSrc();
//		
//		if (!sk.getSrc().endsWith("(R)"))
//		{
//			sk.setSrc(src + " (R)");
//		}
//		
		/**
		 * Update object position in the image associated List, when affected to a slit.
		 */
		for (int maskNum = 0; maskNum < currentImage.getNbrMasks(); maskNum++) {
			for (int slitNum = 0; slitNum < Mask.get_NBRSLITS_(); slitNum++) {
				if (currentImage.getMask(maskNum).getSlit(slitNum).getAffectedObject() == sk
						.getNum()) {
					currentImage.getMask(maskNum).getSlit(slitNum).setAffectedObject(-1);
					if (getSelectedSlit(pos.x, pos.y, currentImage.getMask(maskNum), false) == slitNum)
						associateObjectToSlit(sk.getNum(), currentImage.getMask(maskNum));

					break;
				}
			}
		}
	}

	/**
	 * Calculation of object position
	 * @param skPos : object position
	 * @return pos : new position after recalculation.
	 */
	private Point2D.Double positonCalcul( Point2D.Double skPos) {
		boolean isCentered = false;
		/**
		 * While the center position is not good, calculate. 
		 */ 
		Double compX=skPos.getX();
		Double compY=skPos.getY();
		Point2D.Double pos=new Point2D.Double(0.0,0.0);
				
		int i=0;

		while (!isCentered)
		{
			pos = computeCentroid(skPos, 10);
			
			i++;
			float resX=(float) (pos.getX()-compX);
			float resY=(float) (pos.getY()-compY);
			
			//if (pos.getX()!=compX)
			if (Math.abs( resX) > 0.5)
			{
				isCentered=false;
				compX=pos.getX();
				skPos=pos;
			}
			else
			if (Math.abs( resY) > 0.5)
			{
				isCentered=false;
				compY=pos.getY();
				skPos=pos;
			}
			
			else
			{		
				isCentered=true;
			}
			if (i==6) break;
		}
		return pos;
	}

	/**
	 * 
	 * @param pointer
	 *            : Point2D mouse position
	 * @param n_win
	 *            : window dimensions to calculate the new centroid position
	 * @return new centroid in image coord
	 */

	private Point2D.Double computeCentroid(Point2D.Double point, int n_win) {
		Point2D.Double pointer = new Point2D.Double(point.x, point.y);
		int ix = (int) Math.ceil(pointer.getX());
		int iy = (int) Math.ceil(pointer.getY());
		icc.imageToUserCoords(pointer, false);
		float value = navigatorImageDisplay.getPixelValue(pointer, 0);
		icc.userToImageCoords(pointer, false);
		double v_min = value * 9 / 10;
		double v_max = value * 3;

		int npixels = (int) Math.ceil(fov.getCurrentImage().getWidth());
		int nlines = (int) Math.ceil(fov.getCurrentImage().getHeight());

		int nca = (int) Math.ceil(n_win / 2.0);
		double sum = 0.0, xc = 0.0, yc = 0.0;

		int imin = ix - nca;
		if (imin < 1)
			imin = 1;
		int imax = ix + nca;
		if (imax > npixels)
			imax = npixels;

		int jmin = iy - nca;
		if (jmin < 1)
			jmin = 1;
		int jmax = iy + nca;
		if (jmax > nlines)
			jmax = nlines;

		for (int i = imin; i <= imax; i++) {
			for (int j = jmin; j <= jmax; j++) {
				pointer.setLocation(i, j);
				icc.imageToUserCoords(pointer, false);
				value = navigatorImageDisplay.getPixelValue(pointer, 0);
				icc.userToImageCoords(pointer, false);
				if (value >= v_min && value <= v_max) {
					xc += (value * i);
					yc += (value * j);
					sum += value;
				}
			}
		}

		if (sum > 0.0) {
			xc = xc / sum;
			yc = yc / sum;
		} 
		else 
		{
			xc = ix;
			yc = iy;
		}

		return new Point2D.Double(xc, yc); // In Image Coords 
	}

	/**
	 * Erase all objects selected on the current image
	 */
	public void eraseAllObjects() {
		divaImageGraphics.getGraphicsPane().repaint();
		for (int i = listCanvasObjects1.size() - 1; i >= 0; i--) {
			eraseObject(i);
		}
		erasePointedObject();
		
	}

	/**
	 * Erase the object selected.
	 * 
	 * @param i
	 *            : Object id
	 */
	public void eraseObject(int i) {
		divaImageGraphics.remove(listCanvasObjects1.get(i));
		listCanvasObjects1.remove(i);

		divaImageGraphics.remove(listCanvasObjects2.get(i));
		listCanvasObjects2.remove(i);

		divaImageGraphics.remove(listCanvasObjects3.get(i));
		listCanvasObjects3.remove(i);

		divaImageGraphics.remove(listCanvasObjects4.get(i));
		listCanvasObjects4.remove(i);
	}

	/**
	 * Plot the pointed object
	 * 
	 * @param i : Object id
	 * 				Plot it with a cross,
	 * 
	 */
	public void plotObject(int i) {
		SkyObject sk = fov.getCurrentImage().getListObjects().get(i);
		
//		SkyObject tempObject = new SkyObject(-1, sk.isRef(), sk.getPosPix(), sk.getPosPixRecalc(),sk.getColor());
		SkyObject tempObject = new SkyObject(-1, sk.isRef(), sk.getInitPos(), sk.getPosPixRecalc(),sk.getColor(), sk.getPointed());
//System.out.println(" ref "+sk.isRef()+"  "+ sk.getInitPos().x+" "+sk.getInitPos().y);
		 //SkyObject tempObject = new SkyObject(-1, sk.isRef(), sk.getSrc(), sk.getCatLibFrom(), sk.getPosPix(),
		//		sk.getObjWorldCenter(), sk.getPosPixRecalc(), sk.getPriority());
		
		if (icc.isWCS()) {
			icc.imageToScreenCoords(tempObject.getPosition(), false);
			WorldCoords tempPosition=getWorldCoords(tempObject.getPosition().getX(), tempObject.getPosition().getY());
			tempObject.setObjWorldCenter(tempPosition);
		}
	
		if (tempObject.getPointed())
		{		
			Color col=Color.GREEN;
			drawCrossOnPointedObject(tempObject.getPosition().x, tempObject.getPosition().y, col);
		}

		  if (tempObject.isRef()) 
		  {
			drawCrossOnObject(i,tempObject);
		  } 
		  else 
		  {
			drawSquareAroundObject(i, tempObject);
		  }
		
	}
		
	/**
	 * Erase the canvaObj
	 */
	public void erasePointedObject() {
		if (canvasTo1 != null)
			divaImageGraphics.remove(canvasTo1);
		if (canvasTo2 != null)
			divaImageGraphics.remove(canvasTo2);
	}
	
	/**
	 * Draw a blue square around the object
	 * @param i : id object
	 * @param tempObject : object.
	 */
	private void drawSquareAroundObject(int i, SkyObject tempObject) {
		
		Color cl=tempObject.getColor();
//System.out.println("Visu DrawSqObj - "+i+" color "+cl.toString());
		
		listCanvasObjects1.add(divaImageGraphics.makeFigure(
				new Line2D.Double(tempObject.getPosition().x - 5,
						tempObject.getPosition().y - 5, tempObject.getPosition().x + 5,
						tempObject.getPosition().y - 5), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects1.get(i));

		listCanvasObjects2.add(divaImageGraphics.makeFigure(
				new Line2D.Double(tempObject.getPosition().x + 5,
						tempObject.getPosition().y - 5, tempObject.getPosition().x + 5,
						tempObject.getPosition().y + 5), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects2.get(i));

		listCanvasObjects3.add(divaImageGraphics.makeFigure(
				new Line2D.Double(tempObject.getPosition().x + 5,
						tempObject.getPosition().y + 5, tempObject.getPosition().x - 5,
						tempObject.getPosition().y + 5), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects3.get(i));

		listCanvasObjects4.add(divaImageGraphics.makeFigure(
				new Line2D.Double(tempObject.getPosition().x - 5,
						tempObject.getPosition().y + 5, tempObject.getPosition().x - 5,
						tempObject.getPosition().y - 5), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects4.get(i));
	}

	/**
	 *  To draw a cross at the given coordinates . 
	 *   (used for mask center)
	 * @param x : x coordinate of the cross center
	 * @param y : y coordinate of the cross center
	 * @param co : drawing color
	 * lWidth : line thickness 
	 */
	private void drawCrossOnPointedObject(double x, double y, Color co) {
		canvasTo1 = divaImageGraphics.makeFigure(new Line2D.Double(x - 10,
				y, x + 10, y), co, co, lWidth+2);
		divaImageGraphics.add(canvasTo1);
		canvasTo2 = divaImageGraphics.makeFigure(new Line2D.Double(x,
				y - 10, x, y + 10), co, co, lWidth+2);
		divaImageGraphics.add(canvasTo2);
	}
	
	/**
	 * Draw cross on the object
	 * @param i : id object
	 * @param sk : Sky object
	 * @param tempObject : object
	 */
	private void drawCrossOnObject(int i, SkyObject tempObject) {
		Point2D.Double pt = new Point2D.Double();
		Color cl=tempObject.getColor();
		pt = tempObject.getPosition();

	//	 c = new Color(255, 0, 0);
			
		listCanvasObjects1.add(divaImageGraphics.makeFigure(new Line2D.Double(pt.x, pt.y - 10,
				pt.x, pt.y + 10), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects1.get(i));
		
		listCanvasObjects2.add(divaImageGraphics.makeFigure(new Line2D.Double(pt.x - 10, pt.y,
				pt.x + 10, pt.y), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects2.get(i));
		
		listCanvasObjects3.add(divaImageGraphics.makeFigure(new Line2D.Double(pt.x, pt.y - 10,
				pt.x, pt.y + 10), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects3.get(i));
		
		listCanvasObjects4.add(divaImageGraphics.makeFigure(new Line2D.Double(pt.x - 10, pt.y,
				pt.x + 10, pt.y), cl, cl, lWidth));
		divaImageGraphics.add(listCanvasObjects4.get(i));
		
	}


	/**
	 * When the objects are download from a server, they are displayed all
	 * selected.
	 */
	public void plotAllObjects() {

		if (fov.getCurrentImage().getListObjects().size() <= 0)
			return;

		if (! accessMenuInterface.isMenuDisplayPlotObjectsSelected())
			return;

		for (int i = 0; i < fov.getCurrentImage().getListObjects().size(); i++) 
		{
			plotObject(i);
		}
//System.out.println("");
//		if (idObjChoosen> -1) 
//			{
//			erasePointedObject();
//			}
		plotBary(fov.getTheBrain().getBary());

	}

	/**
	 * Erase the barycenter
	 */
	public void eraseBary() {
		if (canvasBary != null)
			divaImageGraphics.remove(canvasBary);
	}

	/**
	 * Plot the barycenter of all objects selected.
	 * 
	 * @param b
	 *            : point to display.
	 */
	public void plotBary(Point2D.Double b) {
		accessMenuInterface.isMenuDisplayPlotObjectsSelected();
		if (! accessMenuInterface.isMenuDisplayPlotObjectsSelected())
			return;

		Point2D.Double temp = new Point2D.Double(b.getX(), b.getY());
		eraseBary();

		if (icc.isWCS())
			icc.imageToScreenCoords(temp, false);
		// else
		// {
		// icc.imageToCanvasCoords(temp, false);
		//
		// temp.x = display.getWidth()/2.0 + ( temp.getX()
		// - fov.getCurrentImage().getCenter().getX()
		// ) * fov.getCurrentImage().getScale();
		// temp.y = display.getHeight()/2.0 + ( temp.getY()
		// - fov.getCurrentImage().getCenter().getY()
		// ) * fov.getCurrentImage().getScale();
		// }

		Ellipse2D.Double ellipse = new Ellipse2D.Double(temp.getX() - 3, temp.getY() - 3, 6, 6);
		canvasBary = divaImageGraphics.makeEllipse(ellipse, 1, red, red, 5, null);
		divaImageGraphics.add(canvasBary);
		divaImageGraphics.repaint();
	}

	/**
	 * Add an object on image
	 * 
	 * @param type : object source type (if it came from server's catalog or local cat, it's a number. When choosen manually (-1))
	 * @param props : Libelle of where it comes from (catalog name, ...) or properties when it comes from local catalog
	 * @param c : coordinates of the object in image coordinates system.<br>
	 *            For objects from catalog or from local import, 
	 *            the position is converted from world to image coords
	 * @param priority : object priority, when it's set.
	 *  Set object world coordinates. 
	 *  
	 *  Int id -> String id
	 */

//	public void addObject(int id, int type,String fromLib, Point2D.Double c, int priority) {
	public void addObject(String id, int type,String props, Point2D.Double c, int priority) {
		
		this.icc = new ImageCoordinateConverter(getNavigatorImageDisplay());
		WorldCoords wcoord;
	
//System.out.println("Visu addObj Ty "+type+" Pos "+c.x+","+c.y);
		if (type >-1)
		{
			/** From servers or local catalogs */
			 wcoord=new WorldCoords(c.x,c.y);
			icc.worldToImageCoords(c, false);
		}
		else
		{
			/** Choosen manually */
//System.out.print ("Visu Addobj else ");
			Point2D.Double tmpo=new Point2D.Double(c.x,c.y);
			icc.imageToCanvasCoords(tmpo,false); 
			wcoord= getWorldCoords(tmpo.x,tmpo.y);
			
		}
		

		/** A verifier il peut y avoir des objets souhaités non visibles **/
//		if (type > -1)
//		{
//
//			if (navigatorImageDisplay.getPixelValue(c, 0) == 0)
//			{
//				System.out.println("Visu addObj not display");
//				return;
//			}
//		}

		Image im=fov.getCurrentImage();
		
//System.out.print ("Visu Addobj "+ im.getNbrObjects() );
		fov.getCurrentImage().addObject(id,false, type, props, c, wcoord, priority);
		fov.getCurrentImage().getLastObject().setObjWorldCenter(wcoord);
		
		fov.getTheBrain().computeBary(fov.getCurrentImage().getListObjects());
//System.out.println("  "+ im.getListObjects().size() );		
		updateByHand();
		ospeControl.getActionControl().setSaveNeeded(true);
		ospeControl.getMainFrame().updateButtons();
	}

	/**
	 * Remove selected object
	 * 
	 * @param i
	 *            : object id.
	 */
	public void removeObject(int i) {
		fov.getCurrentImage().removeObject(i);
		int idSlit=getAffectedSlit(i);
		if (idSlit>0) fov.getCurrentMaskOfCurrentImage().getSlit(idSlit).setAffectedObject(-1);
		fov.getTheBrain().computeBary(fov.getCurrentImage().getListObjects());
		updateByHand();
		}

	/**
	 * Associate all the objects to a slit.
	 * 
	 * @param theMask
	 *            : current mask.
	 */
	public void associateAllObjectsToSlits(Mask theMask) {
		List<SkyObject> tempList = fov.getCurrentImage().getListObjects();

		for (int i = 0; i < tempList.size(); i++) {
			associateObjectToSlit(i, theMask);
		}
	}

	/**
	 * Set a slit to an object.
	 * 
	 * @param numObject
	 *            : object id.
	 * @param theMask
	 *            : current mask.
	 * 
	 */
	public void associateObjectToSlit(int numObject, Mask theMask) {
		SkyObject obj = fov.getCurrentImage().getListObjects().get(numObject);
//		Point2D.Double posObject = new Point2D.Double(obj.getPosition().getX(), obj.getPosition().getY());
		Point2D.Double posObject=new Point2D.Double(obj.getObjWorldCenter().getX(), obj.getObjWorldCenter().getY());
//		icc.imageToScreenCoords(posObject, false);
		icc.worldToScreenCoords(posObject, false);

		int slitNum = getSelectedSlit(posObject.x, posObject.y, theMask, true);
		
		if ((slitNum > 0) && (slitNum < 54)) {
			// System.out.println("DEBUG: VisuPanel::associateObjectToSlit : "
			// + "Associate Object(" + numObject + ") with Slit(" + (slitNum+1)
			// +
			// ").");
			Integer affectedObjectNum = new Integer(theMask.getSlit(slitNum).getAffectedObject());
			theMask.getHistory().addAction("setAffectedObject " + slitNum, affectedObjectNum);

			theMask.getSlit(slitNum).setAffectedObject(numObject);
			
			double oldAperture= theMask.getSlit(slitNum).getAperture();
			theMask.getSlit(slitNum).setToDefaultAperture();
			theMask.getHistory().addEntry("Change width of slit");
			theMask.getHistory().addAction("setAperture " + slitNum, oldAperture);
			theMask.update();
		}
	}

	/**
	 * Select the slit to associate to an object.
	 * Testing what slit the coordinates objects can be in. 
	 * 
	 * @param ex : object x coordinate
	 * @param ey : object y coordinate
	 * @param mask : the mask to search slits on
	 * @param associate : true/false if the slit will be associated or no with the object.        
	 * @return slit id. : Slit number 
	 */
	public int getSelectedSlit(double ex, double ey, Mask mask, boolean associate) {
		// distSrc : Distance between object coord and display center in display canvas values.
		Point2D.Double distSrc = new Point2D.Double(ex - (navigatorImageDisplay.getWidth() / 2.0),
				ey - (navigatorImageDisplay.getHeight() / 2.0));
		// distDst : Distance after scale transformation
		Point2D.Double distDst = new Point2D.Double();
		at.deltaTransform(distSrc, distDst);

		// Overwrite of distDst with rotation transformation
		double hyp = Math.sqrt((distDst.x * distDst.x) + (distDst.y * distDst.y));
		double ang = (Math.acos(distDst.x / hyp) * 180.0 / Math.PI) % 180.0;
		if (distDst.y > 0)
			ang = (360.0 - ang) % 360.0;
		distDst.x = hyp * Math.cos((ang - mask.getOmega()) * Math.PI / 180.0);
		distDst.y = -hyp * Math.sin((ang - mask.getOmega()) * Math.PI / 180.0);
		
		// Compute distance between mask center and image center
		double dx2 = (mask.getCenter().getX() - fov.getCurrentImage().getCenter().getX())
				* fov.getCurrentImage().getScale();
		double dy2 = (mask.getCenter().getY() - fov.getCurrentImage().getCenter().getY())
				* fov.getCurrentImage().getScale();

		double hyp2 = Math.sqrt((dx2 * dx2) + (dy2 * dy2));
		if (hyp2 != 0.0) {
			double ang2 = (Math.acos(dx2 / hyp2) * 180.0 / Math.PI) % 180.0;
			if (dy2 > 0)
				ang2 = (360.0 - ang2) % 360.0;
			dx2 = hyp2 * Math.cos((ang2 - mask.getOmega()) * Math.PI / 180.0);
			dy2 = -hyp2 * Math.sin((ang2 - mask.getOmega()) * Math.PI / 180.0);
		}
	
		
		double dx = (distDst.x / fov.getCurrentImage().getScale() - dx2);
		double dy = (distDst.y / fov.getCurrentImage().getScale() - dy2);
		double epY = mask.getHeight2Display() / 2.0 * fov.getCurrentImage().getScale();

		if (Math.abs(dy) < epY) {
			if (Mask._NBRSLITS_ % 2 == 1) {
				dx = dx - (mask.getlSlit2Display() / 2.0 * fov.getCurrentImage().getScale());
			}
			dx = dx / (mask.getlSlit2Display() * fov.getCurrentImage().getScale());

			int selSlit = (int) Math.ceil(Mask._NBRSLITS_ / 2) + (int) Math.ceil(dx);
	
			if (selSlit > 0 && selSlit < ((Mask._NBRSLITS_)-1)) {
				/** If associated with an object */
				if (associate) 
				{
					double posY = mask.getSlit(selSlit).PosDef
							- (dy * fov.getCurrentImage().getResol())
							/ fov.getCurrentImage().getScale();

					Double oldPosition = new Double(mask.getSlit(selSlit).getPosition());
					mask.getHistory().addEntry("Affect object to slit");
					mask.getHistory().addAction("setPosition " + selSlit, oldPosition);
					
					mask.getSlit(selSlit).setPosition(posY);
//					Point2D.Double p=new Point2D.Double();
//					p.y=currentMask.getCenterDeg().getY()+posY;
//					p.x=currentMask.getCenterDeg().getX()+dx;
				//	mask.getSlit(selSlit).setPosCenter(p);
					
					Point2D.Double p2=new Point2D.Double();
					
				//	p2=calculSlitCenterSkyPosition(currentMask, posY, selSlit);
					p2=testCalculSlitPos(currentMask, posY, selSlit);
					mask.getSlit(selSlit).setWcPosCenter(p2);
					Slit s=	mask.getSlit(selSlit);
//System.out.println("visu getSelSlit "+selSlit+" P2 "+p2.x+" "+p2.y+" "+s.getWcPosCenter().getRA()+" "+s.getWcPosCenter().getDec());									
				

					if (!mask.isAssigned) mask.isAssigned=true;

					if (selSlit == mask.getSelectedSlit() && !fov.getCurrentImage().searching)
						slide_position.setValue((int) Math.floor(posY));
					
					ospeControl.getToolBar().getButtonUndoToolBar().setEnabled(true);
				}
				
				
				return selSlit;
			}
		}
		return -1;

	}

	private Point2D.Double testCalculSlitPos(Mask currentMask, double posY, int selSlit) {
		// TODO Auto-generated method stub
		Point2D.Double pt= new Point2D.Double(0.0,0.0);
		double lgSlit=6.5454; // in arcsec
		Point2D.Double cMk = currentMask.getCenterDeg();
		double unitConv=0.00027777777777778; // convertir arc sec en degre
		
		int f=0;
		if (selSlit>27)
		{
			f=selSlit-27;
		}
		else 
		{
			f=27-selSlit;
		}
		
		double py=0.0;
		double px=0.0;
		if (currentMask.getOmega()==0.0)
		{
			py=cMk.getY()+(posY* unitConv);
			px=cMk.getX()+(lgSlit*f* unitConv);
		}
		else 
		{
			
		}
		//System.out.println("visu test Slit "+selSlit+" px "+px+" "+py);
		
		pt.setLocation(px, py);
		return pt;
	}

	/**
	 * @param source
	 * @param currentSlit
	 * @param apeOri
	 */
	private void adjustSlitAperture(double value, Slit currentSlit, double apeOri) {
		if (apeOri >= 0)
			apeOri = apeOri - Math.floor(apeOri);
		else
			apeOri = apeOri - Math.ceil(apeOri);

		Double oldAperture = new Double(currentSlit.getAperture());
//System.out.print("Visu 2401 - fct adjAper : "+oldAperture+" val "+value+" ori "+apeOri);		
		if (oldAperture.doubleValue() != value + apeOri) {
//System.out.print("-> eff. ");
			fov.getCurrentImage().getCurrentMask().getHistory()
					.addEntry("Change width of slit");
			fov.getCurrentImage().getCurrentMask().getHistory()
					.addAction("setAperture " + currentSlit.getId(), oldAperture);
			ospeControl.getToolBar().getButtonUndoToolBar().setEnabled(true);
		}
//System.out.println();
		currentSlit.setAperture(value + apeOri);
		fov.getCurrentImage().getCurrentMask().update();
		//updateByHand(); modif pour voir. 
	}

	/**
	 * @param source
	 * @param currentSlit
	 * @param posOri
	 */
	private void adjustSlitPosition(double value, Slit currentSlit, double posOri) {
		posOri = posOri - Math.floor(posOri);
       
		Double oldPosition = new Double(currentSlit.getPosition());
//System.out.print("Visu 2425 - adjSlitPos - 1: "+oldPosition+" val "+value+" ori:"+posOri);
		if (oldPosition.doubleValue() != value + posOri) {
//System.out.print(" -> eff. ");
			fov.getCurrentImage().getCurrentMask().getHistory()
					.addEntry("Change position of slit");
			fov.getCurrentImage().getCurrentMask().getHistory()
					.addAction("setPosition " + currentSlit.getId(), oldPosition);
			ospeControl.getToolBar().getButtonUndoToolBar().setEnabled(true);
		}
//System.out.println();
		currentSlit.setPosition(value + posOri);
		updateByHand();
	}



	/**
	 * Action when mouse left button clic on image (with a mask or not)
	 * @param e : mouse event
	 * @param currentImage
	 * @param currentMask
	 */
	private void onNavigatorImageDisplayleftMouseClick(MouseEvent e, 
			final Image currentImage, final Mask currentMask) {
//System.out.print(("Visu mouse left clic - mask  "));
//printTheMousePosition(e.getX(),e.getY());	


		Point2D.Double p=new Point2D.Double(e.getX(),e.getY());
		this.icc.screenToCanvasCoords(p, false);
        Point2D.Double p2=new Point2D.Double(0.0,0.0);		
		
		// distSrc : Distance between mouse click and display center in display pixels values.
		Point2D.Double distSrc = new Point2D.Double(
				e.getX() - (navigatorImageDisplay.getWidth() / 2.0), 
				e.getY() - (navigatorImageDisplay.getHeight() / 2.0));
			
		// distDst : Distance after scale transformation
		Point2D.Double distDst = new Point2D.Double();
		at.deltaTransform(distSrc, distDst);

		// Overwrite of distDst with rotation transformation
		double hyp = Math.sqrt((distDst.x * distDst.x) + (distDst.y * distDst.y));
		double ang = (Math.acos(distDst.x / hyp) * 180.0 / Math.PI) % 180.0;
		if (distDst.y > 0){
			ang = (360.0 - ang) % 360.0;
		}
		distDst.x = hyp * Math.cos((ang - currentMask.getOmega()) * Math.PI / 180.0);
		distDst.y = -hyp * Math.sin((ang - currentMask.getOmega()) * Math.PI / 180.0);
		// Compute distance between mask center and image center
		double dx2 = (currentMask.getCenter().getX() - currentImage.getCenter().getX())
				* currentImage.getScale();
		double dy2 = (currentMask.getCenter().getY() - currentImage.getCenter().getY())
				* currentImage.getScale();

		double hyp2 = Math.sqrt((dx2 * dx2) + (dy2 * dy2));
		if (hyp2 != 0.0) {
			double ang2 = (Math.acos(dx2 / hyp2) * 180.0 / Math.PI) % 180.0;
			if (dy2 > 0)
				ang2 = (360.0 - ang2) % 360.0;
			dx2 = hyp2 * Math.cos((ang2 - currentMask.getOmega()) * Math.PI / 180.0);
			dy2 = -hyp2 * Math.sin((ang2 - currentMask.getOmega()) * Math.PI / 180.0);
		}

		double dx = (distDst.x / currentImage.getScale() - dx2);
		double dy = (distDst.y / currentImage.getScale() - dy2);

		double epY = currentMask.getHeight2Display() / 2.0 * currentImage.getScale();

		if (Math.abs(dy) < epY) {
			if (Mask._NBRSLITS_ % 2 == 1) {
				dx = dx - (currentMask.getlSlit2Display() / 2.0 * currentImage.getScale());
			}
			dx = dx / (currentMask.getlSlit2Display() * currentImage.getScale());

			int selSlit = (int) Math.ceil(Mask._NBRSLITS_ / 2) + (int) Math.ceil(dx);

			if (selSlit >= 0 && selSlit < Mask._NBRSLITS_) {
				if (e.isControlDown()) {
					displayJoinSlitDialog(currentMask, selSlit);
				} else {
					if (e.getClickCount() >= 2) {
						
						double posY = currentMask.getCurrentSlit().PosDef
								- (dy * currentImage.getResol()) / currentImage.getScale();
						slide_position.setValue((int) Math.floor(posY));
						
						Slit s=currentMask.getCurrentSlit();
					
						double oldSlitPos=s.getPosition();
						if (oldSlitPos != posY) 
						{
							s.setAffectedObject(-1);
						}
						s.setPosition(posY);
						s.setToDefaultAperture();
					//	s.setPosCenter(p); // mouse position
						int is=s.getId();
				
						p2=calculSlitCenterSkyPosition(currentMask, posY, is);
						
						// Set slit center coordinates.
						s.setWcPosCenter(p2);
																
//System.out.println("visu Clic2 "+is+" P2 "+p2.x+" "+p2.y+" "+s.getWcPosCenter().getRA()+" "+s.getWcPosCenter().getDec());						

						currentMask.update();
					}
					slitCombo.setSelectedIndex(selSlit);
					//updateSlides();
				}
			}
		}
	}

	/**
	 * Calculation Slit center Sky position
	 * @param currentMask : current mask
	 * @param posY : slit position on mask
	 * @param idSlit :  slit id
	 */
	public Point2D.Double calculSlitCenterSkyPosition(final Mask currentMask, double posY,
			int idSlit) {
	    Point2D.Double p2=new Point2D.Double(0.0,0.0);	
		double raDeg = currentMask.getCenterDeg().getX();
		double decDeg= currentMask.getCenterDeg().getY();
		double raMk=raDeg*Math.PI/180.0;
		double decMk=decDeg*Math.PI/180.0;
		
		p2.y=currentMask.getCenterDeg().getY()+(posY/3600.0);
		
		double om=currentMask.getOmega()*Math.PI/180.0;
		double fv=400.0;
		double hs=fv/currentMask._NBRSLITS_;
		double hsr=hs*Math.PI/180.0/3600.0;
		
		double nbslit=(double)27-(idSlit);
		double x0=(nbslit*hsr);
		double n0=posY*Math.PI/180.0/3600.0;
		
		double xi=x0*Math.cos(om)+n0*Math.sin(om);
		double ni=-x0*Math.sin(om)+n0*Math.cos(om);
		
		double rai=raMk+ Math.atan(xi/(Math.cos(decMk)-ni*Math.sin(raMk)));
		double dai=Math.asin((Math.sin(decMk)+ ni*Math.cos(decMk))/(Math.sqrt(1+Math.pow(ni, 2)+Math.pow(xi, 2) )));
		p2.x=rai;
		//p2.y=dai;
		p2.x=rai*180/Math.PI;
		//p2.y=dai*180/Math.PI;
		
		return p2;
	}
	
	
	/**
	 * @param currentMask
	 * @param selSlit
	 */
	private void displayJoinSlitDialog(final Mask currentMask, int selSlit) {
		int n1 = currentMask.getSelectedSlit();
		int n2 = selSlit;

		if (n2 < n1) {
			int temp = n1;
			n1 = n2;
			n2 = temp;
		}

		new OSPE_QuickJoinSlitsPanel(currentMask,ospeControl, n1, n2);
	}

	/** What happens on rigth Mouse Click :
	 * @param e : mouse event 
	 * @param currentImage 
	 * @param currentMask : if there is a current mask
	 * @param objectId : if the click is on an object, get its id.
	 */
	private void rigthMouseClick(MouseEvent e, final Image currentImage, final Mask currentMask,
			int objectId) {
		// If a mask is moving or turning
		int mMaskFlag = ospeControl.getMaskControl().getmMaskFlag();
		if ((mMaskFlag == 1) || (mMaskFlag == 2)) 
		{
			// stop the moves
			accessMenuInterface.clickOnMaskStop();
			Mask m=fov.getCurrentMaskOfCurrentImage();
			isMaskDisplayed = true;
			
			updateMaskCoords(m);

		} 
		else 
		{
			// if the mask is displayed or not
			if (!isMaskDisplayed) 
			{
				// Turn off the "assign to slit" option
				mouseObjectPopupMenu.getComponent(5).setVisible(false);
				mouseObjectPopupMenu.getComponent(6).setVisible(false);
			} 
			else 
			{
				// Turn on the "assign to slit" option
				mouseObjectPopupMenu.getComponent(5).setVisible(true);
				mouseObjectPopupMenu.getComponent(6).setVisible(true);
			}

			final Point locationOnScreen = navigatorImageDisplay.getLocationOnScreen();
			/**
			 * If there is an object designed
			 */
			if (objectId >= 0) 
			{
				// Checkbox if the object id referenced
				if (currentImage.getListObjects().get(objectId).isRef())
					((JCheckBoxMenuItem) mouseObjectPopupMenu.getComponent(0)).setSelected(true);
				else
					((JCheckBoxMenuItem) mouseObjectPopupMenu.getComponent(0)).setSelected(false);

				int affectedSlitNum = searchAffectedSlitToObject(objectId);
				if (affectedSlitNum >= 0) 
				{
					mouseObjectPopupMenu.getComponent(1).setVisible(true);
					mouseObjectPopupMenu.getComponent(2).setVisible(true);
					if (currentMask.getPlotSpectrum(affectedSlitNum))
						((JMenuItem) mouseObjectPopupMenu.getComponent(2)).setText("unplot spectrum");
					else
						((JMenuItem) mouseObjectPopupMenu.getComponent(2)).setText("plot spectrum");
				} 
				else
				{
					mouseObjectPopupMenu.getComponent(1).setVisible(false);
					mouseObjectPopupMenu.getComponent(2).setVisible(false);
				}

				if (currentImage.getListObjects().get(objectId).isCenterRecalc()) {
					mouseObjectPopupMenu.getComponent(9).setVisible(true);
					mouseObjectPopupMenu.getComponent(10).setVisible(true);
				} 
				else 
				{
					mouseObjectPopupMenu.getComponent(9).setVisible(false);
					mouseObjectPopupMenu.getComponent(10).setVisible(false);

				}

			// Display the popup menu at the pointer position?
			Point p = new Point((int) locationOnScreen.getX() + e.getX(),
					(int) locationOnScreen.getY() + e.getY());
			mouseObjectPopupMenu.setLocation(p);
			mouseObjectPopupMenu.setVisible(true);
			}
			else
			{	
				if (!isPickObjFrame) 
				{ // Add objects manually ?
				Point p = new Point((int) locationOnScreen.getX() + e.getX(),
						(int) locationOnScreen.getY() + e.getY());
				mouseGeneralPopupMenu.setLocation(p);
				mouseGeneralPopupMenu.setVisible(true);
				}
			
			}
			
		}
	}
 /**
  * Update mask center world coordinates
  * @param m : current mask
  * Called when stop moving. 
  */
	public void updateMaskCoords(Mask m) {
		// TODO Auto-generated method stub
		
		Point2D.Double pt=new Point2D.Double(m.getCenter().getX(), m.getCenter().getY());
//		System.out.println(" MaskCenter x: "+pt.x+" y: "+pt.y);		
		icc.userToImageCoords(pt, false);
//		System.out.print(" U2Im x: "+pt.x+" y: "+pt.y);
		icc.imageToWorldCoords(pt, false);
//		WorldCoords wc = new WorldCoords(pt.x,pt.y);
		m.setCenterWc(pt.x,pt.y);
//		System.out.println(" I2Wc x: "+m.getMaskCenterWordlCoord().getRA()+" y: "+m.getMaskCenterWordlCoord().getDec());
	}

	/**
	 * Change point coordinates from canvas to world Coordinates.
	 * @param x 
	 * @param y
	 * @return : Word coordinates
	 */
	public WorldCoords getWorldCoords(double x, double y) {
		Point2D.Double coordInSky = new Point2D.Double(x, y);

		icc.canvasToWorldCoords(coordInSky, false);

		return new WorldCoords(coordInSky.getX(), coordInSky.getY());
	}


	/** What mouse motion can do in navigator image display
	 * @param x : x mouse position on screen
	 * @param y : y mouse position on screen
	 */
	private void onNavigatorImageDisplayMouseMoved(final int x, final int y) {
		if (fov.getSelectedImage() < 0)
			return;

	//	final PlanarImage image = navigatorImageDisplay.getImage();
		Image image = fov.getCurrentImage();
		if (image != null) {
			if (icc.isWCS() == true) {
				boolean isOnImage = isOnImage(x, y, image);

			     

				// Then Get them and print them.
				if (isOnImage == true) {	
					icc.screenToCanvasCoords(pointerPosDble, false);
					jLabelDisplay.setText(getWorldCoords(pointerPosDble.getX(),
							pointerPosDble.getY()).toString());
				}
				//else System.out.print(".");

				setLabelFovSize();

			} else {
				jLabelDisplay.setText("WARNING: World Coordinates Convertion"
						+ " is not available !");
			}
		}
	}

	/**
	 * Test if the mouse is on image
	 * @param x
	 * @param y
	 * @param image
	 * @return
	 */
	private boolean isOnImage(final int x, final int y, Image image) {
		
		boolean isOnImage = false;

		/**
		 * Get the image navigator screen coordinates
		 * to test if the pointer is on the image screen location
		 */	
		// Point left top image corner min
		Point2D.Double coordImMin = new Point2D.Double();
		// point right bottom image corner Max
		Point2D.Double coordImMax = new Point2D.Double();
		
		/** Image Limits */ 
		coordImMin.setLocation(0, 0);
		coordImMax.setLocation(image.getWidth(), image.getHeight());
		
		// Point left top image corner // min in screen
		Point2D.Double coordInScreenMin = new Point2D.Double();
		// point right bottom image corner // Max in screen
		Point2D.Double coordInScreenMax = new Point2D.Double();
		
		
		
		// Convert those coordinates in screen coord.
		icc.imageToScreenCoords(coordImMin, false);
		icc.imageToScreenCoords(coordImMax, false);
		
		/** Set the min and the max on screen coord */
		double valx1, valx2,valy1, valy2;
		if (coordImMin.getX() < coordImMax.getX()) 
			{
			valx1=coordImMin.getX();
			valx2=coordImMax.getX();
			}
			else 
			{
				valx1=coordImMax.getX();
				valx2=coordImMin.getX();
			}
		
		if (coordImMin.getY() < coordImMax.getY()) 
		{
		valy1=coordImMin.getY();
		valy2=coordImMax.getY();
		}
		else 
		{
			valy1=coordImMax.getY();
			valy2=coordImMin.getY();
		}
		
		coordInScreenMin.setLocation(valx1, valy1);
		coordInScreenMax.setLocation(valx2, valy2);
	
		// Get the  mouse position in screen coord.
		pointerPosDble = new Point2D.Double(x, y); 

		// set the mouse position in screen coord 
	     mousePosition=new Point2D.Double(x, y); 

		// Test if pointer is on Image
		if (pointerPosDble.x > coordInScreenMin.getX()
				&& pointerPosDble.x < coordInScreenMax.getX()
			&& pointerPosDble.y > coordInScreenMin.getY()
					&& pointerPosDble.y < coordInScreenMax.getY())
				isOnImage = true;
		
		return isOnImage;
	}



	/**
	 * To go to the specify slit
	 * 
	 * @param numSlit336251362621055E
	 */
	public void moveToSlit(int numSlit) {
		AffineTransform at3 = new AffineTransform();
		final Mask currentMask = fov.getCurrentImage().getCurrentMask();
		at3.setToRotation(-currentMask.getOmega() * Math.PI / 180.0, currentMask.getCenter().getX(), currentMask.getCenter().getY());
		Point2D.Double tmp = new Point2D.Double();
		at3.transform(currentMask.getSlit(numSlit).getPosXY(), tmp);
		fov.getCurrentImage().setCenter(tmp);
	}

	/**
	 * Sets the image zoom.
	 * 
	 * @param echelleNew
	 *            : new field displaying scale.
	 */
	public void zoomSet(float echelleNew) {
		navigatorImageDisplay.setScale(echelleNew);
		navigatorImageDisplay.updateImage();
		fov.setScale(echelleNew);

		statusInterface.setStatusBarText(Color.blue, "INFO: Image scale is reset to "+ echelleNew);
		
	}

	/**
	 * To zoom the screen field of the image.
	 * 
	 */
	private void zoomIn() {
		zoom(true);
	}

	/**
	 * To zoom out the display.
	 */
	private void zoomOut() {
		zoom(false);
	}

	
	protected void zoom(boolean in) {
		float zoomFactor = navigatorImageDisplay.getScale();
			
		if (in) {
			if (zoomFactor < 1.0) {
				int i = Math.round(1.0F / zoomFactor) - 1;
				zoomFactor = 1.0F / i;

			} else {
				zoomFactor += 1;
			}
		} else {
			if (zoomFactor <= 1.0) {
				int i = Math.round(1.0F / zoomFactor) + 1;
				zoomFactor = 1.0F / i;

			} else {
				zoomFactor -= 1;
			}
		}

		if (zoomFactor < ImageDisplayMenuBar.MIN_SCALE
				|| zoomFactor > ImageDisplayMenuBar.MAX_SCALE) {
			return;
		}
		
		navigatorImageDisplay.setScale(zoomFactor);
		navigatorImageDisplay.updateImage();

		fov.setScale(zoomFactor);
		
		setLabelFovSize();
		if (!in){
			statusInterface.setStatusBarText(Color.blue, "INFO: Image scale is decreased !");
		} else {
			statusInterface.setStatusBarText(Color.blue, "INFO: Image scale is increased !");
		}
		
	}

	/**
	 * Test if there are reference objects before writing or validating the mask
	 * 
	 * @return true if there are at least 4 reference objects on the mask
	 */
	public boolean testRefObjects() {
		List<SkyObject> refObjectsList = new ArrayList<SkyObject>();
		if (fov.getCurrentImage().getCurrentMask().getRefObjectsList().size()== 0 )
		{
			refObjectsList = fov.getCurrentImage().getCurrentMask().getRefObjects();
			return refObjectsList != null && refObjectsList.size() >= 3;
		}
		else 
			return true;
	}

	@Override
	public CatalogNavigator getNavigator() {
		return getNavigatorImageDisplay().getNavigator();
	}

	public Object getImageProcessor() {
		return getNavigatorImageDisplay().getImageProcessor();
	}

	public FieldOfView getFov() {
		return fov;
	}

	/**
	 * Updates the cut levels and sets them to those of the
	 * <i>k</i><sup>th</sup> image.
	 * 
	 * @param k
	 *            Image number.
	 */
	@Override
	public void updateCutLevels(int k) {
		double hi, lo; // High/Low cut levels values for the image.
//System.out.println("visu 2694  num:"+ k+" hi "+fov.getImage(k).getHighCut()+" lo "+fov.getImage(k).getLowCut());
 
		hi = fov.getImage(k).getHighCut();
		lo = fov.getImage(k).getLowCut();

		getNavigatorImageDisplay().getImageProcessor().setDefaultColormap();
		getNavigatorImageDisplay().getImageProcessor().setCutLevels(lo, hi);
		getImageCutDialog().updateCutLevels(lo, hi);
		getNavigatorImageDisplay().getImageProcessor().update();
		

	}

	@Override
	public void updateColors(int k) {
		String cmap;
		String cIntens;
		int cAlg;

		cmap = fov.getImage(k).getColorMap();
		cIntens = fov.getImage(k).getColorIntensity();
		cAlg = fov.getImage(k).getColorAlgorithm();

		if (cmap != null) {
			getNavigatorImageDisplay().getImageProcessor().setColorLookupTable(cmap);
		}
		if (cIntens != null) {
			getNavigatorImageDisplay().getImageProcessor().setIntensityLookupTable(cIntens);
		}
		getNavigatorImageDisplay().getImageProcessor().setScaleAlgorithm(cAlg);

		// if ((cmap != null) || (cIntens != null) || (cAlg>0))
		// visuPanel.imColorsPanel.imageColors.updateColors(fov.getImage(k));
	}

	@Override
	public void updateOfImageNavigatorDisplay() {
		
		// Add test
		getNavigatorImageDisplay().getImageProcessor().update();
		//getNavigatorImageDisplay().updateImage();
	}

	@Override
	public void enableValidateAndGenerateButton(boolean maskValidated) {
		if (maskValidated) {
			validateButton.setText("Unvalidate");
		} else {
			validateButton.setText("Validate");
		}

		if (!validateButton.isEnabled())
			validateButton.setEnabled(true);
		if (!writeButton.isEnabled())
			writeButton.setEnabled(true);
	}

	public OspeControl getOspeControl() {
		return ospeControl;
	}

	public ImageCoordinateConverter getIcc() {
		return icc;
	}

	/**
	 * @param e
	 */
	private void onNavigatorImageDisplayMouseDragged(MouseEvent e) {
		if (e.getModifiers() != InputEvent.BUTTON1_MASK) // left button
			return;
		evtMouse = e;

		double scale = navigatorImageDisplay.getScale();
//		if (fov.getSelectedImage() >= 0)
//			scale = fov.getCurrentImage().getScale();

		double dX = (originPointer.getX() - e.getX()) / scale;
		double dY = (originPointer.getY() - e.getY()) / scale;

		if (fov.getSelectedImage() >= 0) {
			if (fov.getCurrentImage().getSelectedMask() >= 0) {
				final Mask currentMask = fov.getCurrentMaskOfCurrentImage();
				if (currentMask.moveEnable && !currentMask.turnEnable) {
//	System.out.println("visu move enable ");
					// Move the mask
					Point2D.Double tmpMask = new Point2D.Double();
					// get the new mask's coordinates
					tmpMask.setLocation(maskDisplayCenter.getX() - dX, maskDisplayCenter.getY() - dY);
					currentMask.setCenter(tmpMask);

					// set the new mask's coordinates
					WorldCoords wc = getWorldCoords(tmpMask.getX(), tmpMask.getY());

					currentMask.setCenterWc(wc.getRaDeg(), wc.getDecDeg());
					
//					icc.canvasToWorldCoords(tmpMask, false);
		//			icc.userToWorldCoords(tmpMask, false);

//					Point2D.Double tmp = new Point2D.Double();
//					tmp.x = wc.getRaDeg();
//					tmp.y = wc.getDecDeg();
      //					currentMask.setCenterDeg(tmpMask);
//
//					// set the new mask's Corner left coordinates
//					double width = currentMask.getWidth2Display();
//					double height = currentMask.getHeight2Display();
//					double maskDebutX = tmpMask.getX() - (width / 2.0);
//					double maskDebutY = tmpMask.getY() - (height / 2.0);
//					
//					Point2D.Double tmpCorner = new Point2D.Double();
//					tmpCorner.setLocation(maskDebutX, maskDebutY);
//					currentMask.setLeftDownCornerPix(tmpCorner);
//					
//					wc = getWorldCoords(tmpCorner.getX(), tmpCorner.getY());
////					currentMask.setAlphaCorner(wc.getRA());
////					currentMask.setDeltaCorner(wc.getDec());
//					currentMask.setLeftCornerWc(wc.getRaDeg(), wc.getDecDeg());
//					
//					
//					Point2D.Double tmpC = new Point2D.Double();
//					tmpC.x = wc.getRaDeg();
//					tmpC.y = wc.getDecDeg();
//					currentMask.setLeftDownCornerDeg(tmpC);
					
					currentMask.update();
					return;
				}

				if (!currentMask.moveEnable && currentMask.turnEnable) {
					// Turn the mask
					double Xopt = (originPointer.getX() - maskDisplayCenter.getX());
					double Yopt = -(originPointer.getY() - maskDisplayCenter.getY());
					double Xevt = (evtMouse.getX() - maskDisplayCenter.getX());
					double Yevt = -(evtMouse.getY() - maskDisplayCenter.getY());

					if ((Xopt == 0.0 || Yopt == 0.0) || (Xevt == 0.0 || Yevt == 0.0))
						return;

					double A_originPointer = Math.atan(Yopt / Xopt);
					A_originPointer = A_originPointer * 180.0 / Math.PI;
					if (Xopt > 0.0 && Yopt < 0.0)
						A_originPointer = 360.0 + A_originPointer;
					if (Xopt < 0.0 && Yopt < 0.0)
						A_originPointer = 180.0 + A_originPointer;
					if (Xopt < 0.0 && Yopt > 0.0)
						A_originPointer = 180.0 + A_originPointer;

					double A_evtMouse = Math.atan(Yevt / Xevt);
					A_evtMouse = A_evtMouse * 180.0 / Math.PI;
					if (Xevt > 0.0 && Yevt < 0.0)
						A_evtMouse = 360.0 + A_evtMouse;
					if (Xevt < 0.0 && Yevt < 0.0)
						A_evtMouse = 180.0 + A_evtMouse;
					if (Xevt < 0.0 && Yevt > 0.0)
						A_evtMouse = 180.0 + A_evtMouse;

					double dAngle = A_evtMouse - A_originPointer;
					double angle = (originAngle + dAngle) % 360.0;
					currentMask.setOmega(angle);

					currentMask.update();
					return;
				}
			}// Fi a mask is on the image and move or turn activated.
	
			/**Calculate the new position of the image center in canvas coord.  */
			Point2D.Double tmpImage = new Point2D.Double();
			tmpImage.setLocation(centerImage.getX() + dX, centerImage.getY() + dY);
			if (tmpImage.x < 0.0)
				tmpImage.x = 0.0;
			if (tmpImage.x > fov.getCurrentImage().getWidth())
				tmpImage.x = fov.getCurrentImage().getWidth() - 1;
			if (tmpImage.y < 0.0)
				tmpImage.y = 0.0;
			if (tmpImage.y > fov.getCurrentImage().getHeight())
				tmpImage.y = fov.getCurrentImage().getHeight() - 1;

			fov.getCurrentImage().setCenter(tmpImage);
			fov.getCurrentImage().update();
		} 
		else 
		{	
			originPointer.setLocation(originPointer.x - dX, originPointer.y - dY);
			Point2D.Double tmpImage = new Point2D.Double();
			tmpImage.setLocation(navigatorImageDisplay.getOrigin().x + dX,
					navigatorImageDisplay.getOrigin().y + dY);
			navigatorImageDisplay.setOrigin(tmpImage);
			navigatorImageDisplay.updateImage();
		}
//		imagePanner.update(imagePanner.getGraphics());
	}

	public void closePickObjFrame() {
		isPickObjFrame = false;
		accessMenuInterface.enableButtonsForPicObject(true);
		getFov().update();
		
	}

	@Override
	public void addImageFromServerToProject() {

		// Copy the remote file on project's directory
		final String filename = getNavigatorImageDisplay().getFilename();
		String pathOfFitsFile = new String(filename);
		if (filename != null){
			final File source = new File(pathOfFitsFile);
			
			final File destination = new File(fov.getPath() + File.separator + source.getName());
			if (!FileUtil.copyTo(source, destination)) {
				new CustomJDialog("Impossible to copy the image in the workspace !",
						CustomJDialog._ERROR_, CustomJDialog._CLOSE_BUTTON_, this);
				return;
			}
			try {
				ospeControl.addImageToProject(destination);
			} catch (IOException | FitsException e) {
				e.printStackTrace();
			}
			currentImage=fov.getCurrentImage();
		}
	}

	/**
	 * Centering image at the choosen object position and hightlight the object 
	 * @return 
	 */
	
	public void setImageAtObjectPosition(int param) 
	{
		Point2D.Double newOrig=new Point2D.Double(0.0,0.0);
		erasePointedObject();
		objChoosen=fov.getCurrentImage().getObject(param);
		idObjChoosen=param;
		if (objChoosen.getPointed()) 
		{
			objChoosen.setPointed(false);
			tableurPanel.razTableSelect();

 // Pb when moving the image to center on object choosen. The zoom part is not part of calculation. 
 // See if it's useful to have this function or not. 			
 
//			if (fov.getCurrentImage().getSelectedMask()>=0)
//			{
//				newOrig = new Point2D.Double(0.0,0.0);
//				newOrig = new Point2D.Double(fov.getCurrentMaskOfCurrentImage().getCenter().x, fov.getCurrentMaskOfCurrentImage().getCenter().y);
//				icc.userToCanvasCoords(newOrig, false);
//			}
//			else 
//			{
//				// set display center at bary point
//				newOrig.setLocation(fov.getTheBrain().getBary().x, fov.getTheBrain().getBary().y);
//				icc.imageToCanvasCoords(newOrig, false);
//			}
		    
		}
		else  objChoosen.setPointed(true);
		
		if (objChoosen.getPointed())
		{
//System.out.print("Visu setImageAtObjPos idObj "+idObjChoosen+" Last id "+idLastObjChoosen);
		   if ((idLastObjChoosen > -1) && (idLastObjChoosen!= idObjChoosen))
		   {
			  fov.getCurrentImage().getObject(idLastObjChoosen).setPointed(false);
		   }
		   idLastObjChoosen=idObjChoosen;
//System.out.println("  chg Last id "+idLastObjChoosen);
//		   WorldCoords wc=objChoosen.getObjWorldCenter();	
//		   newOrig = new Point2D.Double(wc.getX(), wc.getY());				
//		   icc.worldToCanvasCoords(newOrig, false);
		}
	//	   fov.getCurrentImage().setCenter(newOrig);
		   fov.getCurrentImage().update();
		   eraseAllObjects();
		   plotAllObjects();
		
	}
	
/**
 * testing the mouse position and the various conversions
 * @param x : X screen coord
 * @param y : Y screen coord
 */
	private void printTheMousePosition(int x, int y)
	{
       Image image = fov.getCurrentImage();
		// Point left top image corner // min in screen
		Point2D.Double coordInScreenMin = new Point2D.Double();
		// point right bottom image corner // Max in screen
		Point2D.Double coordInScreenMax = new Point2D.Double();
		
		/** This coords  are in canvas coord */ 
		coordInScreenMin.setLocation(0, 0);
		coordInScreenMax.setLocation(image.getWidth(), image.getHeight());
//System.out.println("w "+image.getWidth()+" H "+image.getHeight());
		
		icc.imageToScreenCoords(coordInScreenMax, false);
		icc.imageToScreenCoords(coordInScreenMin, false);
		
		
System.out.println("Visu:printMousePos screen  x: "+x+" y: "+y+" "+ isOnImage(x, y, image));		
		Point2D.Double ptTmp = new Point2D.Double(x,y);
		Point2D.Double ptTmp2 = new Point2D.Double(x,y);
		Point2D.Double ptTmp3 = new Point2D.Double(x,y);
		Point2D.Double ptTmp4 = new Point2D.Double(x,y);
	icc.screenToImageCoords(ptTmp2, false);
System.out.print(" Image x: "+ptTmp2.x+" y: "+ptTmp2.y);
icc.screenToUserCoords(ptTmp4, false);
System.out.print(" User x: "+ptTmp4.x+" y: "+ptTmp4.y);
		icc.screenToCanvasCoords(ptTmp, false);
System.out.println(" Canva x: "+ptTmp.x+" y: "+ptTmp.y);


//System.out.println("Im Screen Min  "+coordInScreenMin.getX()+","+ coordInScreenMin.getY()+" Max "+coordInScreenMax.getX()+","+ coordInScreenMax.getY());

icc.screenToWorldCoords(ptTmp3, false);
		WorldCoords wcTmp= getWorldCoords(ptTmp.getX(),ptTmp.getY());
//System.out.print("  xdeg: "+wcTmp.getRaDeg()+" ydeg: "+wcTmp.getDecDeg());		
//System.out.println("    x: "+wcTmp.getRA()+" y: "+wcTmp.getDec()+"  x: "+wcTmp.getRaDeg()+" y: "+wcTmp.getDecDeg());

//Mask m=fov.getCurrentMaskOfCurrentImage();
//System.out.println(" mask Om : "+m.getOmega());


	}
	
	@Override
	public String setNewImageCatalog(String cat) 
	{
	   newImageCatalog=cat;
		return null;
	}
	public String getNewImageCatalog()
	{
		return newImageCatalog;
	}

	@Override
	public String setNewImageName(String imName)
	{
		newImageName=imName;
		return null;
	}
	public String getNewImageName()
	{
		return newImageName;
	}
	
	
	public void getImageDisplayParameters(Image currIm)
	{
		imResol=currIm.getResol();
		imWidth=currIm.getWidth();
		imHeight=currIm.getHeight();
		imScale=currIm.getScale();
		imCenter=currIm.getCenter();
	}
	public void getMaskDisplayParameters(Mask mk)
	{
		maskDisplayCenter=mk.getCenter();
		maskDisplayLeftCorner=mk.getLeftCornerPix();
		
	}
	
	public Point2D.Double setNewMaskCenter(Point2D.Double pt)
	{
		Point2D.Double tmpPoint=new Point2D.Double(pt.x,pt.y);
		icc.worldToUserCoords(tmpPoint, false);
		Point2D.Double newMaskCenter=new Point2D.Double(tmpPoint.x,tmpPoint.y);
		return newMaskCenter;
	}
}