1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://docbook.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY url_refdocs_base_glib_html "http://developer.gnome.org/glibmm/unstable/">
<!ENTITY url_refdocs_base_glib "&url_refdocs_base_glib_html;classGlib_1_1">
<!ENTITY url_refdocs_base_gtk_html "http://developer.gnome.org/gtkmm/unstable/">
<!ENTITY url_refdocs_base_gtk "&url_refdocs_base_gtk_html;classGtk_1_1">
<!ENTITY url_refdocs_base_gtk_namespace "&url_refdocs_base_gtk_html;namespaceGtk_1_1">
<!ENTITY url_figures_base "figures/">
<!ENTITY url_examples_base "http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/">
<!ENTITY url_examples_branchsuffix "master">
<!ENTITY gtkmm "<application>gtkmm</application>">
<!ENTITY uuml "ü">
<!ENTITY szlig "ß">
<!ENTITY verbar "|">
<!ENTITY copy "©">
<!ENTITY nbsp " ">
]>
<!--
NOTE TO TUTORIAL DOCUMENTATION AUTHORS:
When referring to the gtkmm project in this document, please use the form
>kmm; so that the name is consistent throughout the document. This will wrap
gtkmm with <application></application> tags which can then be styled by CSS if
desired (e.g. boldface, monospace, etc) to make it stand out as the project
name
-->
<!-- The XSL for developer.gnome.org requires this id. -->
<book id="index" lang="es">
<bookinfo>
<title>Programar con <application>gtkmm</application> 3</title>
<authorgroup>
<author lang="en">
<firstname>Murray</firstname>
<surname>Cumming</surname>
</author>
<author lang="en">
<firstname>Bernhard</firstname>
<surname>Rieder</surname>
<contrib>Chapter on "Timeouts".</contrib>
</author>
<author lang="en">
<firstname>Jonathon</firstname>
<surname>Jongsma</surname>
<contrib>Chapter on "Drawing with Cairo".</contrib>
<contrib>Chapter on "Working with gtkmm's Source Code".</contrib>
<contrib>Chapter on "Recent Files".</contrib>
</author>
<author lang="en">
<firstname>Ole</firstname>
<surname>Laursen</surname>
<contrib>Parts of chapter on "Internationalization".</contrib>
</author>
<author lang="en">
<firstname>Marko</firstname>
<surname>Anastasov</surname>
<contrib>Chapter on "Printing".</contrib>
<contrib>Parts of chapter on "Internationalization".</contrib>
</author>
<author lang="en">
<firstname>Daniel</firstname>
<surname>Elstner</surname>
<contrib>Section "Build Structure" of chapter
on "Wrapping C Libraries with gmmproc".</contrib>
</author>
<author lang="en">
<firstname>Chris</firstname>
<surname>Vine</surname>
<contrib>Chapter on "Multi-threaded programs".</contrib>
</author>
<author lang="en">
<firstname>David</firstname>
<surname>King</surname>
<contrib>Section on Gtk::Grid.</contrib>
</author>
<author lang="en">
<firstname>Pedro</firstname>
<surname>Ferreira</surname>
<contrib>Chapter on Keyboard Events.</contrib>
</author>
<author lang="en">
<firstname>Kjell</firstname>
<surname>Ahlstedt</surname>
<contrib>Parts of the update from gtkmm 2 to gtkmm 3.</contrib>
</author>
</authorgroup>
<abstract>
<!-- This text is copied from the introduction. -->
<para>Este libro explica conceptos clave sobre la API <application>gtkmm</application> de C++ para la creación de interfaces de usuario. También introduce los elementos principales de la interfaz de usuario («widgets»).</para>
</abstract>
<copyright lang="en">
<year>2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010</year>
<holder>Murray Cumming</holder>
</copyright>
<legalnotice>
<para>Se otorga permiso para copiar, distribuir y/o modificar este documento en virtud de los términos de la Versión 1.2 de la Licencia de Documentación Libre de GNU o de cualquier versión posterior publicada por la Fundación para el Software Libre; sin Secciones Invariantes, sin Textos de Portada y sin Textos de Contraportada. Puede conseguir una copia de la Licencia de Documentación Libre de GNU, visitando la página oficial o escribiendo a: Free Software Fundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, EE. UU.</para>
</legalnotice>
</bookinfo>
<chapter id="chapter-introduction">
<title>Introducción</title>
<sect1 id="sec-this-book">
<title>Este libro</title>
<para>Este libro explica conceptos clave sobre la API <application>gtkmm</application> de C++ para la creación de interfaces de usuario. También introduce los elementos principales de la interfaz de usuario («widgets»). A pesar de que se hace mención a las clases, constructores y métodos, estas no se explican en gran detalle. Por lo tanto, para obtener información completa sobre la API, diríjase a los enlaces en la documentación de referencia.</para>
<para>Este libro asume un buen entendimiento sobre C++, y cómo crear programas en C++.</para>
<para>Nos encantaría que nos informara sobre cualquier problema que encuentre aprendiendo <application>gtkmm</application> con este documento, y apreciaríamos cualquier información sobre mejoras en el mismo. Consulte la sección <link linkend="chapter-contributing">contribuir</link> para obtener más información.</para>
</sect1>
<sect1 id="sec-gtkmm">
<title>gtkmm</title>
<para><application>gtkmm</application> es un envoltorio de C++ para <ulink url="http://www.gtk.org/">GTK+</ulink>, una biblioteca usada para crear interfaces gráficas de usuario. Esta liberado bajo la licencia LGPL, para que pueda desarrollar software abierto, software gratuito o software comercial usando <application>gtkmm</application> sin comprar ninguna licencia.</para>
<para><application>gtkmm</application> fue originalmente llamado gtk-- debido a que GTK+ ya tenía el signo + en el nombre. Sin embargo, debido a que -- no puede ser indexado fácilmente en los motores de búsqueda, el paquete fue generalmente llamado <application>gtkmm</application>, y eso fue con lo que nos quedamos.</para>
<sect2 id="why-use-gtkmm">
<title>¿Por qué usar <application>gtkmm</application> en vez de GTK+?</title>
<para><application>gtkmm</application> le permite escribir código usando técnicas normales de C++ tales como encapsulación, derivación y polimorfismo. Como programador de C++, probablemente ya se habrá dado cuenta de que esto conlleva a un código más limpio y mejor organizado.</para>
<para><application>gtkmm</application> es más seguro, por lo que el compilador puede detectar errores que sólo pudieran detectarse durante ejecución al usar C. Este uso de tipos específicos también hace la API más limpia debido a que puede ver qué tipos deberían usarse con sólo mirar la declaración de un método.</para>
<para>Se puede hacer uso de herencia para derivar nuevos widgets. Derivar nuevos widgets en código C GTK+ es tan complicado y propenso a errores que casi ningún codificador de C lo hace. Como programador en C++ usted sabe que la derivación es una técnica orientada a objetos esencial.</para>
<para>Pueden usarse instancias de miembros, simplificando la gestión de memoria. Todos los widgets C GTK+ son tratados usando punteros. Como programador en C++ usted sabe que los punteros deben evitarse siempre que sea posible.</para>
<para><application>gtkmm</application> implica menos código en comparación con GTK+, el cual usa nombres de funciones prefijadas y muchos macros.</para>
</sect2>
<sect2 id="gtkmm-vs-qt">
<title><application>gtkmm</application> comparado con Qt</title>
<para>Qt de Trolltech es el competidor más cercano de <application>gtkmm</application>, por lo que merece discusión.</para>
<para lang="en"><application>gtkmm</application> developers tend to prefer <application>gtkmm</application> to Qt because <application>gtkmm</application> does things in a more C++ way. Qt originates from a time when C++ and the standard library were not standardised or well supported by compilers. It therefore duplicates a lot of stuff that is now in the standard library, such as containers and type information. Most significantly, Trolltech modified the C++ language to provide signals, so that Qt classes cannot be used easily with non-Qt classes. <application>gtkmm</application> was able to use standard C++ to provide signals without changing the C++ language.
See the <ulink url="https://wiki.gnome.org/Projects/gtkmm/FAQ">FAQ</ulink> for more detailed differences.</para>
</sect2>
<sect2 id="gtkmm-is-a-wrapper">
<title><application>gtkmm</application> es un envoltorio</title>
<para><application>gtkmm</application> no es un kit de herramientas nativo de C++, pero si es un envoltorio C++ de un conjunto de herramientas de C. Esta separación de la interfaz e implementación tiene sus ventajas. Los desarrolladores de <application>gtkmm</application> pasan la mayor parte de su tiempo hablando sobre cómo <application>gtkmm</application> puede presentar una API lo mas clara posible, sin compromisos incómodos debido a oscuros detalles técnicos. Nosotros contribuimos un poco al código fuente subyacente de GTK+, pero también lo hacen los programadores de C, los programadores de Perl, los programadores de Python, etc. Por ello, GTK+ se beneficia de una base de usuarios de mayor proporción que el lenguaje de herramientas específicas; hay más desarrolladores, más personas que prueban software en desarrollo, y más usuarios.</para>
</sect2>
</sect1>
</chapter>
<chapter id="chapter-installation">
<title>Instalación</title>
<sect1 id="sec-installation-dependencies">
<title>Dependecias</title>
<para>Antes de intentar instalar <application>gtkmm</application> 3.0, probablemente deba instalar primero estos otros paquetes.</para>
<itemizedlist>
<listitem><para lang="en"><application>libsigc++ 2.0</application></para></listitem>
<listitem><para lang="en"><application>GTK+ 3.0</application></para></listitem>
<listitem><para lang="en"><application>glibmm</application></para></listitem>
<listitem><para lang="en"><application>cairomm</application></para></listitem>
<listitem><para lang="en"><application>pangomm</application></para></listitem>
<listitem><para lang="en"><application>atkmm</application></para></listitem>
</itemizedlist>
<para>Estas dependencias tienen sus propias dependencias, incluyendo las siguientes aplicaciones y bibliotecas:</para>
<itemizedlist>
<listitem><para lang="en"><application>pkg-config</application></para></listitem>
<listitem><para lang="en"><application>glib</application></para></listitem>
<listitem><para lang="en"><application>ATK</application></para></listitem>
<listitem><para lang="en"><application>Pango</application></para></listitem>
<listitem><para lang="en"><application>cairo</application></para></listitem>
<listitem><para lang="en"><application>gdk-pixbuf</application></para></listitem>
</itemizedlist>
</sect1>
<sect1 id="sec-install-unix-and-linux">
<title>Unix y Linux</title>
<sect2 id="sec-linux-install-from-packages">
<title>Paquetes preconstruidos</title>
<para>Las versiones recientes de <application>gtkmm</application> se empaquetan en casi todas las distribuciones principales de Linux actualmente. Si usted utiliza Linux, es probable que pueda empezar a trabajar con <application> gtkmm </application> instalando el paquete desde el repositorio oficial para su distribución Linux. Las distribuciones que cuentan con <application>gtkmm</application> en sus repositorios son Debian, Ubuntu, Red Hat, Fedora, Mandriva, Suse, y muchas otras.</para>
<para>Los nombres de los paquetes de <application>gtkmm</application> varían de distribución en distribución (por ejemplo, <application>libgtkmm-3.0-dev</application> en Debian y en Ubuntu o <application>gtkmm30-devel</application> en Red Hat y Fedora), por lo que se recomienda consultar el nombre del paquete correcto en el gestor de paquetes de su distribución para instalarlo como lo haría con cualquier otro paquete.</para>
<note>
<para>Los nombres de los paquetes no cambiarán cuando se libere la nueva API/ABI compatible con versiones de <application>gtkmm</application>. De lo contrario, no sería una API/ABI compatible. Así que no se sorprenda, por ejemplo, de encontrar <application>gtkmm</application> 3.8 suministrado por el paquete <application>libgtkmm-3.0-dev</application> de Debian.</para>
</note>
</sect2>
<sect2 id="sec-install-from-source">
<title>Instalar desde las fuentes</title>
<para>Si su distribución no proporciona un paquete <application>gtkmm</application> pre-construido, o si desea instalar una versión diferente a la proporcionada por su distribución, también puede instalar <application>gtkmm</application> desde las fuentes. El código fuente para <application>gtkmm</application> se puede descargar desde <ulink url="http://www.gtkmm.org/"/>.</para>
<para>Después de haber instalado todas las dependencias, descargue el código fuente de <application>gtkmm</application>, descomprímalo y cámbiese a la carpeta creada. <application>gtkmm</application> se puede construir e instalar con la siguiente secuencia de comandos:</para>
<screen>
# ./configure
# make
# make install
</screen>
<note>
<para>Recuerde que en un sistema Unix o Linux, probablemente tendrá que ser <literal>root</literal> para instalar el software. Los comandos <command>su</command> o <command>sudo</command> le permitirán introducir la contraseña de <literal>root</literal>para tener el acceso de <literal>root</literal> temporalmente.</para>
</note>
<para>El script <filename>configure</filename> hará comprobaciones para asegurarse de que todas las dependencias necesarias ya están instaladas. Si le falta alguna dependencia, terminará y mostrará un error.</para>
<para lang="en">
By default, <application>gtkmm</application> will be installed under the
<filename>/usr/local</filename> directory. On some systems you may need to
install to a different location. For instance, on Red Hat Linux systems
you might use the <literal>--prefix</literal> option with configure, like
so:
<screen lang="en">
# ./configure --prefix=/usr
</screen>
</para>
<warning>
<para>Debe tener mucho cuidado al instalar en prefijos estándar del sistema, como <filename>/usr</filename>. Las distribuciones de Linux instalan paquetes de software en <filename>/usr</filename>, por lo que instalar un paquete de fuentes en este prefijo puede corromper o crear un conflicto con el software instalado usando el sistema de gestión de paquetes de su distribución. De manera ideal, debería usar un prefijo separado para todo el software que instale desde las fuentes.</para>
</warning>
<para>Si quiere ayudar al desarrollo de <application>gtkmm</application> o experimentar con nuevas características, puede instalar <application>gtkmm</application> desde git. La mayoría de los usuarios nunca tendrán que hacer esto, pero si está interesado en involucrarse directamente con el desarrollo de <application>gtkmm</application>, consulte el apéndice <link linkend="chapter-working-with-source">Trabajando con el código fuente de gtkmm</link>.</para>
</sect2>
</sect1>
<sect1 id="sec-packages-windows">
<title>Microsoft Windows</title>
<para lang="en">GTK+ and <application>gtkmm</application> were designed to work well with Microsoft Windows, and the developers encourage its use on the win32 platform. However, Windows has no standard installation system for development libraries. Please see the <ulink url="https://wiki.gnome.org/Projects/gtkmm/MSWindows">Windows Installation</ulink>
page for Windows-specific installation instructions and notes.</para>
</sect1>
</chapter>
<chapter id="chapter-basics">
<title>Conceptos básicos</title>
<para>En este capítulo se presentan algunos de los aspectos más importantes de la codificación <application>gtkmm</application>. Que se validarán con un ejemplo de trabajo de código. Sin embargo, esta es sólo una pequeña muestra, por lo que es necesario leer otros capítulos para obtener más información importante.</para>
<para>Conocer C++ le ayudará con <application>gtkmm</application> como lo haría con cualquier otra biblioteca. A menos que se indique lo contrario, el comportamiento de las clases de <application>gtkmm</application> será como el de cualquier otra clase C++, de manera que podrá utilizar sus actuales técnicas de C++ con las clases de <application>gtkmm</application>.</para>
<sect1 id="sec-basics-simple-example">
<title>Ejemplo simple</title>
<para>Para iniciar nuestra introducción a <application>gtkmm</application>, vamos a empezar con el programa más simple posible. Este programa va a crear una ventana vacía de 200 x 200 píxeles.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/base?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>base.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <gtkmm.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app =
Gtk::Application::create(argc, argv,
"org.gtkmm.examples.base");
Gtk::Window window;
window.set_default_size(200, 200);
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
<para>Ahora se explicará cada línea del ejemplo</para>
<programlisting>#include <gtkmm.h></programlisting>
<para>Todos los programas <application>gtkmm</application> deben incluir ciertas cabeceras <application>gtkmm</application>: <literal>gtkmm.h</literal> incluye el kit completo de <application>gtkmm</application>. Esto no suele ser una buena idea, ya que incluye casi un megabyte de cabeceras, pero para programas sencillos, basta.</para>
<para lang="en">
The next statement:
<programlisting lang="en">Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");</programlisting>
creates a <classname>Gtk::Application</classname> object, stored in a <classname>RefPtr</classname> smartpointer. This is needed in all <application>gtkmm</application>
applications. The <methodname>create()</methodname> method for this object initializes <application>gtkmm</application>, and checks the
arguments passed to your application on the command line, looking for
standard options such as <literal>--display</literal>. It takes these from the argument list, leaving anything it does not
recognize for your application to parse or ignore. This ensures
that all <application>gtkmm</application> applications accept the same set of standard arguments.
</para>
<para>Las dos siguientes líneas de código crean una ventana y establecen su tamaño (inicial) predeterminado:</para>
<programlisting>Gtk::Window window;
window.set_default_size(200, 200);</programlisting>
<para>La última línea muestra la ventana y entra al bucle principal de <application>gtkmm</application>, que terminará cuando la ventana se cierre. Su función <function>main()</function> entonces retornará con un éxito apropiado o un código de error.</para>
<programlisting>return app->run(window);</programlisting>
<para lang="en">
After putting the source code in <literal>simple.cc</literal> you can compile
the above program with <application>gcc</application> using:
<programlisting lang="en">g++ simple.cc -o simple `pkg-config gtkmm-3.0 --cflags --libs`</programlisting>
Note that you must surround the <literal>pkg-config</literal> invocation with backquotes.
Backquotes cause the shell to execute the command inside them, and to use
the command's output as part of the command line.
Note also that <literal>simple.cc</literal> must come before the <literal>pkg-config</literal>
invocation on the command line.
</para>
</sect1>
<sect1 id="sec-headers-and-linking">
<title>Cabeceras y enlazado</title>
<para lang="en">
Although we have shown the compilation command for the simple example, you really should use the automake and autoconf tools, as described in "Autoconf, Automake, Libtool", by G. V. Vaughan et al. The examples used in this book are included in the <application>gtkmm-documentation</application> package, with appropriate build files, so we won't show the build commands in future. You'll just need to find the appropriate directory and type <literal>make</literal>.
</para>
<para>Para simplificar la compilación, se usa <literal>pkg-config</literal>, que está presente en todas las instalaciones correctas de <application>gtkmm</application>. Este programa «sabe» qué opciones de compilación son necesarias para compilar los programas que usan <application>gtkmm</application>. La opción <literal>--cflags</literal> hace que <literal>pkg-config</literal> devuelva la lista de carpetas en las que el compilador buscará los archivos de cabecera; la opción <literal>--libs</literal> solicita la lista de bibliotecas a las que el compilador enlazará y las carpetas en las que encontrarlas. Intente ejecutarlo desde su intérprete de comandos para ver los resultados en su sistema.</para>
<para lang="en">
However, this is even simpler when using the <function>PKG_CHECK_MODULES()</function> macro in a standard configure.ac file with autoconf and automake.
For instance:
<programlisting lang="en">PKG_CHECK_MODULES([MYAPP], [gtkmm-3.0 >= 3.8.0])</programlisting>
This checks for the presence of gtkmm and defines MYAPP_LIBS and MYAPP_CFLAGS for use in your Makefile.am files.
</para>
<para lang="en">gtkmm-3.0 is the name of the current stable API. There was an older API called gtkmm-2-4 which installs in parallel when it is available. There were several versions of gtkmm-2.4, such as gtkmm 2.10 and there are several versions of the gtkmm-3.0 API. Note that the API name does not change for every version because that would be an incompatible API and ABI break. Theoretically, there might be a future gtkmm-4.0 API which would install in parallel with gtkmm-3.0 without affecting existing applications.
</para>
<para>Tenga en cuenta que si menciona módulos adicionales, además de gtkmm-3.0, deben estar separados por espacios, no por comas.</para>
<para>Openismus tiene más <ulink url="http://www.openismus.com/documents/linux/automake/automake.shtml">ayuda básica con automake y autoconf</ulink></para>
</sect1>
<sect1 id="sec-widgets-overview">
<title>Widgets</title>
<para>Las aplicaciones <application>gtkmm</application> están compuestas por ventanas, estas a su vez contienen widgets, tales como botones y cuadros de texto. En algunos otros sistemas, los widgets se llaman «controles». Hay un objeto C++ en el código de la aplicación para cada widget contenido en las ventanas de una aplicación. Sólo debe llamar a un método de la clase widget para afectar al widget visible.</para>
<para lang="en">Widgets are arranged inside container widgets such as frames and notebooks, in a hierarchy of widgets within widgets. Some of these container widgets, such as <classname>Gtk::Grid</classname>, are not visible - they exist only to arrange other widgets. Here is some example code that adds 2 <classname>Gtk::Button</classname> widgets to a <classname>Gtk::Box</classname> container widget:
<programlisting lang="en">m_box.pack_start(m_Button1);
m_box.pack_start(m_Button2);</programlisting>
and here is how to add the <classname>Gtk::Box</classname>, containing those buttons, to a <classname>Gtk::Frame</classname>, which has a visible frame and title:
<programlisting lang="en">m_frame.add(m_box);</programlisting>
</para>
<para>La mayoría de los capítulos de este libro tratan de widgets específicos. Consulte la sección <link linkend="chapter-container-widgets">Widgets contenedores</link> para obtener más detalles sobre de cómo agregar widgets a widgets contenedores.</para>
<para>Aunque se puede especificar el diseño y apariencia de las ventanas y widgets con código C++, es probable que resulte más conveniente usar <literal>Glade</literal> para el diseño de la interfaz de usuario y cargarlos en tiempo de ejecución con <literal>Gtk::Builder</literal>. Consulte el capítulo <link linkend="chapter-builder">Glade y Gtk::Builder</link>.</para>
<para>A pesar de que las instancias de widgets <application>gtkmm</application> tienen ámbito y duración de la misma manera que otras clases de C++, <application>gtkmm</application> tiene una característica opcional para ahorrar tiempo que verá en algunos de los ejemplos. <function>Gtk::manage()</function> le permite decir que un widget hijo es propiedad del contenedor en el que lo ubica. Esto le permite utilizar <function>new</function> en el widget, añadirlo al contenedor, y olvidarse de eliminarlo. Puede aprender más de las técnicas de gestión de memoria de <application>gtkmm</application> en el <link linkend="chapter-memory">capítulo de gestión de memoria</link>.</para>
</sect1>
<sect1 id="sec-signals-overview">
<title>Señales</title>
<para><application>gtkmm</application>, como la mayoría de kits de herramientas de la IGU, está <emphasis>dirigido por eventos</emphasis>. Cuando ocurre un evento, como la pulsación de un botón del ratón sobre un widget, éste emitirá la señal apropiada. Cada widget puede emitir un conjunto de señales diferente. Para hacer que la pulsación de un botón resulte en una acción, establecemos un <emphasis>manejador de señales</emphasis> para atrapar la señal «clicked» del botón.</para>
<para lang="en"><application>gtkmm</application> uses the libsigc++ library to implement signals. Here is an example line of code that connects a Gtk::Button's "clicked" signal with a signal handler called "on_button_clicked":
<programlisting lang="en">m_button1.signal_clicked().connect( sigc::mem_fun(*this,
&HelloWorld::on_button_clicked) );</programlisting>
</para>
<para>Para obtener información más detallada acerca de señales, consulte el <link linkend="chapter-signals">apéndice</link>.</para>
<para>Para obtener información acerca de la implementación de sus propias señales en vez de sólo conectar a las señales existentes de <application>gtkmm</application>, consulte el <link linkend="chapter-custom-signals">apéndice</link>.</para>
</sect1>
<sect1 id="sec-basics-ustring">
<title>Glib::ustring</title>
<para>Puede sorprenderle aprender que <application>gtkmm</application> no utiliza <classname>std::string</classname> en sus interfaces. En cambio, usa <classname>Glib::ustring</classname>, que es tan similar y discreto que en realidad puede pretender que cada <classname>Glib::ustring</classname> es un <classname>std::string</classname> e ignorar el resto de esta sección. Pero siga leyendo si quiere aplicar otros lenguajes además del inglés en su aplicación.</para>
<para>std::string utiliza 8 bits por carácter, pero 8 bits no son suficientes para codificar lenguajes como árabe, chino y japonés. A pesar de que las codificaciones de estos lenguajes ahora las ha especificado el Consorcio Unicode, los lenguajes C y C++ todavía no proporcionan ningún soporte Unicode estándar. GTK+ y GNOME eligen implementar Unicode usando UTF-8, y eso es lo que está envuelto en Glib::ustring. Proporciona casi exactamente la misma interfaz que std::string, además de conversiones automáticas desde y hacia std::string.</para>
<para>Uno de los beneficios de UTF-8 es que no necesita usarlo a menos que quiera, por lo que no necesita reconvertir todo su código de una vez. <classname>std::string</classname> todavía funcionará para cadenas de 7 bits ASCII. Pero cuando intente localizar su aplicación para lenguajes como chino, por ejemplo, empezará a ver errores extraños y posibles fallos. Entonces, todo lo que necesitará hacer es empezar a utilizar <classname>Glib::ustring</classname> en su lugar.</para>
<para>tenga en cuenta que UTF-8 no es compatible con codificaciones de 8 bits como ISO-8859-1. Por ejemplo, las diéresis alemanas no están en el rango ASCII y necesitan más de un byte en la codificación UTF-8. Si su código contiene cadenas literales de 8 bits, debe convertirlas a UTF-8 (por ejemplo, el saludo bávaro «Grüß Gott» sería «Gr\xC3\xBC\xC3\x9F Gott»).</para>
<para>Evite la aritmética de punteros al estilo C, y funciones como strlen(). En UTF-8, cada carácter podría necesitar entre 1 y 6 bytes, por lo que no es posible asumir que el próximo byte es otro carácter. <classname>Glib::ustring</classname> se ocupa de estos detalles, por lo que puede usar métodos como Glib::ustring::substr() y seguir pensando en términos de caracteres en vez de bytes.</para>
<para>A diferencia de la solución Unicode de Windows UCS-2, esto no requiere ninguna opción especial de compilación para procesar cadenas literales, y no resulta en que los ejecutables y bibliotecas Unicode sean incompatibles con las ASCII.</para>
<para lang="en"><ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1ustring.html">Reference</ulink></para>
<para>Para obtener más información acerca de cómo proporcionar cadenas literales UTF-8, consulte la sección <link linkend="chapter-internationalization">Internacionalización</link>.</para>
</sect1>
<sect1 id="sec-intermediate-types">
<title>Tipos intermedios</title>
<para>Algunas API relacionadas con gtkmm utilizan contenedores de datos intermedios, como <classname>Glib::StringArrayHandle</classname>, en vez de un contenedor específico estándar de C++ como <classname>std::vector</classname> o <classname>std::list</classname>, a pesar de que <application>gtkmm</application> en sí mismo ahora sólo usa <classname>std::vector</classname> desde <application>gtkmm</application> 3.0.</para>
<para lang="en">You should not declare these types yourself. You should instead use whatever Standard C++ container you prefer. glibmm will do the conversion for you. Here are some of these intermediate types:
<itemizedlist>
<listitem><para lang="en"><classname>Glib::StringArrayHandle</classname> or <classname>Glib::ArrayHandle<Glib::ustring></classname>: Use <classname>std::vector<Glib::ustring></classname>, <classname>std::list<Glib::ustring></classname>, <type>const char*[]</type>, etc.</para></listitem>
<listitem><para lang="en"><classname>Glib::ListHandle<Gtk::Widget*></classname>: Use <classname>std::vector<Gtk::Widget*></classname>, <classname>std::list<Gtk::Widget*></classname>, etc.</para></listitem>
<listitem><para lang="en"><classname>Glib::SListHandle<Gtk::Widget*></classname>: Use <classname>std::vector<Gtk::Widget*></classname>, <classname>std::list<Gtk::Widget*></classname>, etc.</para></listitem>
</itemizedlist>
</para>
</sect1>
<sect1 id="sec-basics-gobj-and-wrap">
<title>Mezclando las API de C y C++</title>
<para>Puede usar las API de C que no tengan todavía interfaces C++ convenientes. Generalmente no es un problema usar las API de C desde C++, y <application>gtkmm</application> le ayuda proporcionándole acceso al objeto C subyacente y una forma fácil de crear un objeto C++ envoltorio desde un objeto C, si la API de C también está basada en el sistema GObject.</para>
<para>Para usar una instancia de <application>gtkmm</application> con una función C que requiere una instancia GObject C, use la función <function>gobj()</function> para obtener un puntero a la instancia GObject subyacente. Por ejemplo</para>
<para>
<programlisting>
Gtk::Button* button = new Gtk::Button("example");
gtk_button_do_something_new(button->gobj());
</programlisting>
</para>
<para>Para obtener una instancia <application>gtkmm</application> desde una instancia C GObject, use la función Glib::wrap(). Por ejemplo</para>
<para>
<programlisting>
GtkButton* cbutton = get_a_button();
Gtk::Button* button = Glib::wrap(cbutton);
</programlisting>
</para>
</sect1>
<sect1 id="sec-helloworld">
<title>«Hola mundo» en <application>gtkmm</application></title>
<para>Ahora ha aprendido lo suficiente para ver un ejemplo real. De acuerdo con una antigua tradición de la informática, se introducirá la aplicación Hola Mundo en <application>gtkmm</application>:</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/helloworld?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>helloworld.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H
#define GTKMM_EXAMPLE_HELLOWORLD_H
#include <gtkmm/button.h>
#include <gtkmm/window.h>
class HelloWorld : public Gtk::Window
{
public:
HelloWorld();
virtual ~HelloWorld();
protected:
//Signal handlers:
void on_button_clicked();
//Member widgets:
Gtk::Button m_button;
};
#endif // GTKMM_EXAMPLE_HELLOWORLD_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include <gtkmm/application.h>
int main (int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
HelloWorld helloworld;
//Shows the window and returns when it is closed.
return app->run(helloworld);
}
</programlisting>
<para lang="en">File: <filename>helloworld.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include <iostream>
HelloWorld::HelloWorld()
: m_button("Hello World") // creates a new button with label "Hello World".
{
// Sets the border width of the window.
set_border_width(10);
// When the button receives the "clicked" signal, it will call the
// on_button_clicked() method defined below.
m_button.signal_clicked().connect(sigc::mem_fun(*this,
&HelloWorld::on_button_clicked));
// This packs the button into the Window (a container).
add(m_button);
// The final step is to display this newly created widget...
m_button.show();
}
HelloWorld::~HelloWorld()
{
}
void HelloWorld::on_button_clicked()
{
std::cout << "Hello World" << std::endl;
}
</programlisting>
<!-- end inserted example code -->
<para>Intente compilarla y ejecutarla antes de continuar. Debería ver algo así:</para>
<figure id="figure-helloworld">
<title>Hello World</title>
<screenshot>
<graphic format="PNG" fileref="figures/helloworld.png"/>
</screenshot>
</figure>
<para>Fascinante, ¿verdad? Examinemos el código. Primero, la clase <classname>HelloWorld</classname>:</para>
<programlisting>class HelloWorld : public Gtk::Window
{
public:
HelloWorld();
virtual ~HelloWorld();
protected:
//Signal handlers:
virtual void on_button_clicked();
//Member widgets:
Gtk::Button m_button;
};</programlisting>
<para>Esta clase implementa la ventana «Hello World». Deriva de <classname>Gtk::Window</classname> y tiene un único <classname>Gtk::Button</classname> como miembro. Se eligió usar el constructor para realizar todo el trabajo de inicialización de la ventana, incluyendo establecer las señales. Aquí está, sin los comentarios:</para>
<programlisting>HelloWorld::HelloWorld()
:
m_button ("Hello World")
{
set_border_width(10);
m_button.signal_clicked().connect(sigc::mem_fun(*this,
&HelloWorld::on_button_clicked));
add(m_button);.
m_button.show();
}</programlisting>
<para>Tenga en cuenta que se ha usado una declaración de inicialización para darle al objeto <literal>m_button</literal> la etiqueta «Hello World».</para>
<para>A continuación, llamamos al método <methodname>set_border_width()</methodname> de la ventana. Esto establece el tamaño del espacio entre los lados de la ventana y el widget que contiene.</para>
<para>Luego, se le engancha un manejador de señales a la señal <literal>clicked</literal> de <literal>m_button</literal>. Esto imprime nuestro amigable saludo a <literal>stdout</literal>.</para>
<para>A continuación usamos el método <methodname>add()</methodname> de la ventana para situar el <literal>m_button</literal> en ella. (<methodname>add()</methodname> deriva de <classname>Gtk::Container</classname>, que se describe en el capítulo sobre widgets contenedores). El método <methodname>add()</methodname> ubica al widget en la ventana, pero no lo muestra. Los widgets de <application>gtkmm</application> siempre son invisibles cuando se crean: para mostrarlos, debe llamar a su método <methodname>show()</methodname>, que es lo que se hace en la siguiente línea.</para>
<para>Ahora eche un vistazo a la función <function>main()</function> del programa. Aquí está, sin comentarios:</para>
<programlisting>int main(int argc, char** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
HelloWorld helloworld;
return app->run(helloworld);
}</programlisting>
<para>Primero, se instancia un objeto almacenado en un puntero inteligente <classname>RefPtr</classname> llamado <literal>app</literal>. Éste es del tipo <classname>Gtk::Application</classname>. Cada programa de <application>gtkmm</application> debe tener uno de estos. Le pasamos nuestros argumentos de línea de comandos a su método «create()». Toma los argumentos que quiere, y le deja el resto, como se ha descrito anteriormente.</para>
<para lang="en">
Next we make an object of our <classname>HelloWorld</classname> class, whose constructor
takes no arguments, but it isn't visible yet. When we call <methodname>Gtk::Application::run()</methodname>, giving it the helloworld Window, it shows the Window and starts the <application>gtkmm</application> <emphasis>event loop</emphasis>. During the event loop <application>gtkmm</application> idles, waiting for actions from the user, and responding appropriately. When the user closes the Window, run() will return, causing the final line of our main() function be to executed. The application will then finish.
</para>
</sect1>
</chapter>
<chapter id="changes-gtkmm3">
<title>Cambios en <application>gtkmm</application> 3</title>
<para><application>gtkmm</application>-3.0 es una versión nueva de la API <application>gtkmm</application> que se instala en paralelo con la API <application>gtkmm</application>-2.4, más vieja. La última versión de la API <application>gtkmm</application>-2.4 fue <application>gtkmm</application> 2.24. <application>gtkmm</application> 3 no tiene diferencias fundamentales importantes con respecto a <application>gtkmm</application> 2, pero hace varios cambios pequeños que no fueron posibles mientras se mantenía la compatibilidad de los binarios. Si nunca ha usado la API <application>gtkmm</application>-2.4, entonces puede ignorar con seguridad este capítulo.</para>
<para>La biblioteca de <application>gtkmm</application> 3 se llama <literal>libgtkmm-3.0</literal>, en vez de <literal>libgtkmm-2.4</literal> e instala sus archivos de cabecera en una carpeta versionada similarmente, por lo que su verificación pkg-config debería buscar <literal>gtkmm-3.0</literal> en vez de <literal>gtkmm-2.4</literal>.</para>
<para><application>gtkmm</application> 3 añadió algunas clases nuevas:</para>
<orderedlist>
<listitem><simpara><classname>Gtk::AppChooser</classname>, <classname>Gtk::AppChooserButton</classname>, <classname>Gtk::AppChooserDialog</classname> permiten al usuario seleccionar una aplicación instalada para abrir un determinado tipo de contenido.</simpara></listitem>
<listitem><simpara><classname>Gtk::Grid</classname> es un widget contenedor nuevo que eventualmente reemplazará a <classname>Gtk::Box</classname> y a <classname>Gtk::Table</classname>. Ordena a sus hijos de acuerdo a sus propiedades en lugar de sus propios detalles de disposición.</simpara></listitem>
<listitem><simpara><classname>Gtk::Switch</classname> muestra los estados Encendido/Apagado más explícitamente que <classname>Gtk::CheckBox</classname>. Puede ser útil, por ejemplo, al permitir a los usuarios activar hardware.</simpara></listitem>
</orderedlist>
<para><application>gtkmm</application> 3 también hizo varios cambios pequeños a la API, que probablemente encontrará cuando porte código que usaba <application>gtkmm</application>-2.4. Aquí hay una lista corta:</para>
<para>
<orderedlist>
<listitem><simpara><classname>Gtk::CellLayout</classname>, usada por <classname>Gtk::IconView</classname>, <classname>Gtk::TreeView::Column</classname> y <classname>Gtk::ComboBox</classname> ahora tiene una <classname>Gtk::CellArea</classname>, que puede usarse para especificar más detalles acerca de cómo las <classname>CellRenderer</classname> se ordenan y alinean.</simpara></listitem>
<listitem><simpara>Gtk::ComboBox ahora deriva de CellLayout, permitiendo una disposición y alineación más fácil de sus <classname>Gtk::CellRenderer</classname>.</simpara></listitem>
<listitem><simpara><classname>Gtk::Adjustment</classname>, <classname>IconSet</classname> y <classname>Gdk::Cursor</classname> se usan ahora a través de <classname>Glib::RefPtr</classname>.</simpara></listitem>
<listitem><simpara><classname>Gtk::Box</classname>, <classname>Gtk::ButtonBox</classname>, <classname>Gtk::IconView</classname>, <classname>Gtk::Paned</classname>, <classname>Gtk::ProgressBar</classname>, <classname>Gtk::ScaleButton</classname>, <classname>Gtk::Scrollbar</classname> y <classname>Gtk::Separator</classname> ahora derivan de <classname>Gtk::Orientable</classname>, permitiendo especificar su orientación (vertical u horizontal) sin requerir el uso de una clase derivada como <classname>Gtk::HBox</classname>.</simpara></listitem>
<listitem><simpara><classname>Gtk::IconView</classname>, <classname>Gtk::TextView</classname>, <classname>Gtk::TreeView</classname> y otros widgets derivan de Scrollable en vez de tener sus propios métodos como <methodname>get_vadjustment()</methodname> y su propia señal set_scroll_adjustments.</simpara></listitem>
<listitem><simpara><classname>Gtk::Style</classname> y <classname>Gtk::Rc</classname> se quitaron y se reemplazaron por <classname>Gtk::StyleContext</classname>, y <classname>Gtk::StyleProvider</classname>, así como <classname>Gtk::CssProvider</classname>.</simpara></listitem>
<listitem><simpara>Widget::on_expose_event() se reemplazó por Widget::on_draw(), que asume que cairomm se usa para dibujar, a través del <classname>Cairo::Context</classname> provisto y no requiere que llame a <methodname>Cairo::Context::clip()</methodname>.</simpara></listitem>
<listitem><simpara><classname>Gdk::RGBA</classname> reemplaza a <classname>Color</classname>, añadiendo un componente alfa para la opacidad. <classname>Colormap</classname> se eliminó, junto con su molesto uso para asignar colores.</simpara></listitem>
<listitem><simpara><classname>Gdk::Pixmap</classname> y <classname>Gdk::Bitmap</classname> se eliminaron en favor de <classname>Gdk::Pixbuf</classname>.</simpara></listitem>
<listitem><simpara><classname>Gdk::Drawable</classname> se quitó, y sus métodos se movieron a <classname>Gdk::Window</classname>.</simpara></listitem>
<listitem><simpara>Ahora se usa std::vector en muchos métodos en vez de los tipos intermedios *Handle para hacer a la API más clara.</simpara></listitem>
</orderedlist>
</para>
<para>Toda la API obsoleta se quitó en <application>gtkmm</application> 3.0, sin embargo, se marcarán más partes como obsoletas en versiones futuras.</para>
<para lang="en">As a first step to porting your source code to <application>gtkmm</application>-3.0 you should probably ensure that your application builds with the deprecated <application>gtkmm</application>-2.4 API disabled, by defining macro such as GTKMM_DISABLE_DEPRECATED. There are some autotools macros that can help with this by defining them optionally at build time. See the <ulink url="https://wiki.gnome.org/Projects/gtkmm/PortingToGtkmm3">gtkmm 3 porting wiki page</ulink> for more details.</para>
</chapter>
<chapter id="chapter-button-widget">
<title>Botones</title>
<para><application>gtkmm</application> proporciona cuatro tipos básicos de botones:</para>
<variablelist>
<varlistentry>
<term>Pulsadores</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Button.html"><classname>Gtk::Button</classname></ulink>. Botones estándar, normalmente marcados con una etiqueta o imagen. Presionar uno desencadena una acción. Consulte la sección <link linkend="sec-pushbuttons">botón</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Botones conmutables</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html"><classname>Gtk::ToggleButton</classname></ulink>. A diferencia de un botón normal, que baja y sube en la misma pulsación, un botón conmutable se queda abajo hasta que lo vuelve a presionar. Puede ser útil como conmutador de encendido/apagado. Consulte la sección <link linkend="sec-toggle-buttons">botón conmutador</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Casillas de verificación</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html"><classname>Gtk::CheckButton</classname></ulink>. Estos actúan como botones conmutadores, pero muestran su estado en pequeños cuadrados, con su etiqueta a un lado. Los puede usar en la mayoría de las situaciones que requieren una configuración de encendido/apagado. Consulte la sección<link linkend="sec-checkboxes">casilla de verificación</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Botones de radio</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html"><classname>Gtk::RadioButton</classname></ulink>. Su nombre proviene de los selectores de estación en las antiguas radios de coches. Estos botones se usan en grupos para opciones que se excluyen mutuamente. Pulsar uno de ellos hace que los otros botones de su grupo se apaguen. Son similares a las casillas de verificación (un pequeño widget con una etiqueta a un lado), pero normalmente se ven diferentes. Consulte la sección <link linkend="sec-radio-buttons">botón de radio</link>.</para>
</listitem>
</varlistentry>
</variablelist>
<para>Tenga en cuenta que, debido a sistema de tema de GTK+, las apariencia de estos widgets variará. En el caso de las casillas y de los botones de radio, variará considerablemente.</para>
<sect1 id="sec-pushbuttons">
<title>Botón</title>
<sect2 id="pushbutton-constructors"><title>Constructores</title>
<para>Hay dos maneras de crear un botón. Puede especificar una etiqueta en el constructor de <classname>Gtk::Button</classname>, o establecerla más tarde con <methodname>set_label()</methodname>.</para>
<para>Para definir un atajo para la navegación por teclado, ponga un guión bajo antes de uno de los caracteres y especifique <literal>true</literal> para el parámetro opcional <literal>mnemonic</literal>. Por ejemplo:</para>
<programlisting>Gtk::Button* pButton = new Gtk::Button("_Something", true);</programlisting>
<para lang="en">
Stock items have been recommended for use in buttons. From <application>gtkmm</application>-3.10 they are deprecated.
They should not be used in newly-written code. However, the documentation of
<ulink url="http://developer.gnome.org/gtkmm/unstable/namespaceGtk_1_1Stock.html">namespace Gtk::Stock</ulink>
shows recommended labels and named icons to show in buttons.
</para>
<para><classname>Gtk::Button</classname> también es un contenedor, por lo que puede poner otro widget, como un <classname>Gtk::Image</classname> dentro de él.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Button.html">Reference</ulink></para>
</sect2>
<sect2 id="pushbutton-example"><title>Ejemplo</title>
<para>Este ejemplo crea un botón con una imagen y una etiqueta.</para>
<figure id="figure-buttons">
<title>ejemplo de botones</title>
<screenshot>
<graphic format="PNG" fileref="figures/buttons.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttons/button?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>buttons.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_BUTTONS_H
#define GTKMM_EXAMPLE_BUTTONS_H
#include <gtkmm/window.h>
#include <gtkmm/button.h>
class Buttons : public Gtk::Window
{
public:
Buttons();
virtual ~Buttons();
protected:
//Signal handlers:
void on_button_clicked();
//Child widgets:
Gtk::Button m_button;
};
#endif //GTKMM_EXAMPLE_BUTTONS_H
</programlisting>
<para lang="en">File: <filename>buttons.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "buttons.h"
#include <iostream>
Buttons::Buttons()
{
m_button.add_pixlabel("info.xpm", "cool button");
set_title("Pixmap'd buttons!");
set_border_width(10);
m_button.signal_clicked().connect( sigc::mem_fun(*this,
&Buttons::on_button_clicked) );
add(m_button);
show_all_children();
}
Buttons::~Buttons()
{
}
void Buttons::on_button_clicked()
{
std::cout << "The Button was clicked." << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "buttons.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Buttons buttons;
//Shows the window and returns when it is closed.
return app->run(buttons);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="pushbutton-signals"><title>Señales</title>
<para>El widget <classname>Gtk::Button</classname> tiene las siguientes señales, pero la mayor parte del tiempo sólo manejara la señal <literal>clicked</literal>:</para>
<para>
<variablelist>
<varlistentry>
<term lang="en"><literal>pressed</literal></term>
<listitem>
<para>Emitida cuando se pulsa el botón.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>released</literal></term>
<listitem>
<para>Emitida cuando se suelta el botón.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>clicked</literal></term>
<listitem>
<para>Emitida cuando el botón se pulsa y se suelta.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>enter</literal></term>
<listitem>
<para>Emitida cuando se mueve el puntero del ratón sobre el botón de la ventana.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>leave</literal></term>
<listitem>
<para>Emitida cuando el puntero del ratón sale del botón de la ventana.</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect2>
</sect1>
<sect1 id="sec-toggle-buttons">
<title>Botón Conmutable</title>
<para>Los <classname>ToggleButton</classname> son como los <classname>Button</classname> normales, pero cuando se pulsan quedan activados, o presionados, hasta que se vuelvan a pulsar.</para>
<para>Para recuperar el estado de un <classname>ToggleButton</classname>, puede usar el método <methodname>get_active()</methodname>. Esto devuelve <literal>true</literal> si el botón está «abajo». También puede establecer el estado del botón conmutador con <methodname>set_active()</methodname>. Tenga en cuenta que, si hace esto, y el estado efectivamente cambia, hace que se emita la señal «clicked». Esto normalmente será lo que quiera.</para>
<para>Puede usar el método <methodname>toggled()</methodname> para conmutar el botón, en vez de forzarlo a estar arriba o abajo: esto conmuta el estado del botón, y hace que se emita la señal <literal>toggled</literal>.</para>
<para><classname>Gtk::ToggleButton</classname> es más útil como clase base para las clases <classname>Gtk::CheckButton</classname> y <classname>Gtk::RadioButton</classname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html">Reference</ulink></para>
</sect1>
<sect1 id="sec-checkboxes">
<title>Casilla de verificación</title>
<para><classname>Gtk::CheckButton</classname> hereda de <classname>Gtk::ToggleButton</classname>. La única diferencia real entre ambos es la apariencia de <classname>Gtk::CheckButton</classname>. Puede verificar, establecer, y conmutar una casilla de verificación utilizando los mismos métodos miembro que para <classname>Gtk::ToggleButton</classname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html">Reference</ulink></para>
<sect2 id="checkbutton-example"><title>Ejemplo</title>
<figure id="figure-checkbutton">
<title>Casilla de verificación</title>
<screenshot>
<graphic format="PNG" fileref="figures/checkbutton.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttons/checkbutton?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_BUTTONS_H
#define GTKMM_EXAMPLE_BUTTONS_H
#include <gtkmm/window.h>
#include <gtkmm/checkbutton.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_clicked();
//Child widgets:
Gtk::CheckButton m_button;
};
#endif //GTKMM_EXAMPLE_BUTTONS_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_button("something")
{
set_title("checkbutton example");
set_border_width(10);
m_button.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_clicked) );
add(m_button);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_clicked()
{
std::cout << "The Button was clicked: state="
<< (m_button.get_active() ? "true" : "false")
<< std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-radio-buttons">
<title>Botón de radio</title>
<para>Al igual que las casillas de verificación, los botones de radio también heredan de <classname>Gtk::ToggleButton</classname>, pero trabajan en grupos, y sólo se puede seleccionar un un botón de radio en un grupo a la vez.</para>
<sect2 id="radiobutton-groups"><title>Grupos</title>
<para>Hay dos maneras de establecer un grupo de botones de radio. La primera manera es crear los botones, y establecer sus grupos luego. Sólo los dos primeros constructores se usan. En el siguiente ejemplo, se crea una clase de ventana nueva llamada <classname>RadioButtons</classname> y luego se ubican tres botones de radio en ella:</para>
<programlisting>class RadioButtons : public Gtk::Window
{
public:
RadioButtons();
protected:
Gtk::RadioButton m_rb1, m_rb2, m_rb3;
};
RadioButtons::RadioButtons()
: m_rb1("button1"),
m_rb2("button2"),
m_rb3("button3")
{
Gtk::RadioButton::Group group = m_rb1.get_group();
m_rb2.set_group(group);
m_rb3.set_group(group);
}</programlisting>
<para>Se indicó a <application>gtkmm</application> que colocase los tres <classname>RadioButton</classname> en el mismo grupo obteniéndolo con <methodname>get_group()</methodname> y usando <methodname>set_group()</methodname> para indicarle a los otros <classname>RadioButton</classname> que compartan ese grupo.</para>
<para lang="en">
Note that you can't just do
<programlisting lang="en">m_rb2.set_group(m_rb1.get_group()); //doesn't work</programlisting>
because the group is modified by <methodname>set_group()</methodname> and therefore
non-const.
</para>
<para>La segunda manera de establecer botones de radio es hacer primero un grupo y luego añadirle los botones a él. Aquí hay un ejemplo:</para>
<programlisting>class RadioButtons : public Gtk::Window
{
public:
RadioButtons();
};
RadioButtons::RadioButtons()
{
Gtk::RadioButton::Group group;
Gtk::RadioButton *m_rb1 = Gtk::manage(
new Gtk::RadioButton(group,"button1"));
Gtk::RadioButton *m_rb2 = manage(
new Gtk::RadioButton(group,"button2"));
Gtk::RadioButton *m_rb3 = manage(
new Gtk::RadioButton(group,"button3"));
}</programlisting>
<para>Se creó un grupo nuevo simplemente declarando una variable, <literal>group</literal>, del tipo <classname>Gtk::RadioButton::Group</classname>. Luego, se hicieron tres botones de radio, usando un constructor para hacer que cada uno sea parte de <literal>group</literal>.</para>
</sect2>
<sect2 id="radiobutton-methods"><title>Métodos</title>
<para>Los <classname>RadioButtons</classname> están «apagados» cuando se crean; esto significa que cuando hace un grupo de ellos, primero estarán todos apagados. No olvide encender uno de ellos usando <methodname>set_active()</methodname>:</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html">Reference</ulink></para>
</sect2>
<sect2 id="radiobutton-example"><title>Ejemplo</title>
<para>El siguiente ejemplo muestra el uso de <classname>RadioButton</classname>:</para>
<figure id="figure-radiobutton">
<title>Botón de radio</title>
<screenshot>
<graphic format="PNG" fileref="figures/radiobuttons.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttons/radiobutton?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>radiobuttons.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_RADIOBUTTONS_H
#define GTKMM_EXAMPLE_RADIOBUTTONS_H
#include <gtkmm/box.h>
#include <gtkmm/window.h>
#include <gtkmm/radiobutton.h>
#include <gtkmm/separator.h>
class RadioButtons : public Gtk::Window
{
public:
RadioButtons();
virtual ~RadioButtons();
protected:
//Signal handlers:
void on_button_clicked();
//Child widgets:
Gtk::Box m_Box_Top, m_Box1, m_Box2;
Gtk::RadioButton m_RadioButton1, m_RadioButton2, m_RadioButton3;
Gtk::Separator m_Separator;
Gtk::Button m_Button_Close;
};
#endif //GTKMM_EXAMPLE_RADIOBUTTONS_H
</programlisting>
<para lang="en">File: <filename>radiobuttons.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "radiobuttons.h"
RadioButtons::RadioButtons() :
m_Box_Top(Gtk::ORIENTATION_VERTICAL),
m_Box1(Gtk::ORIENTATION_VERTICAL, 10),
m_Box2(Gtk::ORIENTATION_VERTICAL, 10),
m_RadioButton1("button1"),
m_RadioButton2("button2"),
m_RadioButton3("button3"),
m_Button_Close("close")
{
// Set title and border of the window
set_title("radio buttons");
set_border_width(0);
// Put radio buttons 2 and 3 in the same group as 1:
Gtk::RadioButton::Group group = m_RadioButton1.get_group();
m_RadioButton2.set_group(group);
m_RadioButton3.set_group(group);
// Add outer box to the window (because the window
// can only contain a single widget)
add(m_Box_Top);
//Put the inner boxes and the separator in the outer box:
m_Box_Top.pack_start(m_Box1);
m_Box_Top.pack_start(m_Separator);
m_Box_Top.pack_start(m_Box2);
// Set the inner boxes' borders
m_Box2.set_border_width(10);
m_Box1.set_border_width(10);
// Put the radio buttons in Box1:
m_Box1.pack_start(m_RadioButton1);
m_Box1.pack_start(m_RadioButton2);
m_Box1.pack_start(m_RadioButton3);
// Set the second button active
m_RadioButton2.set_active();
// Put Close button in Box2:
m_Box2.pack_start(m_Button_Close);
// Make the button the default widget
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
// Connect the clicked signal of the button to
// RadioButtons::on_button_clicked()
m_Button_Close.signal_clicked().connect(sigc::mem_fun(*this,
&RadioButtons::on_button_clicked) );
// Show all children of the window
show_all_children();
}
RadioButtons::~RadioButtons()
{
}
void RadioButtons::on_button_clicked()
{
hide(); //to close the application.
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "radiobuttons.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
RadioButtons buttons;
//Shows the window and returns when it is closed.
return app->run(buttons);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-range-widgets">
<title>Widgets de Rango</title>
<para><classname>Gtk::Scale</classname> y <classname>Gtk::Scrollbar</classname> heredan de <classname>Gtk::Range</classname> y comparten mucha funcionalidad. Contienen un «canal» y un «control deslizante» (a veces llamado «rueda» en otros entornos IGU). Deslizar el control con el puntero lo mueve dentro del canal, mientras que pulsar en el canal avanza al control deslizante hacia la ubicación de la pulsación, completamente o en una cantidad definida dependiendo del botón que se use. Este es el comportamiento normal de las barras de desplazamiento.</para>
<para>Como se explicará en la sección <link linkend="chapter-adjustment">ajuste</link>, todos los widgets del rango están asociados a un objeto <classname>Adjustment</classname>. Para cambiar los valores inferior, superior y actual del widget debe usar los métodos de su <classname>Adjustment</classname>, que puede obtenerlos con el método <methodname>get_adjustment()</methodname>. Los constructores predeterminados de los widgets <classname>Range</classname> crean un <classname>Adjustment</classname> automáticamente, o puede especificar un <classname>Adjustment</classname> existente, tal vez para compartirlo con otro widget. Consulte la sección <link linkend="chapter-adjustment">ajuste</link> para obtener más detalles.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Range.html">Reference</ulink></para>
<sect1 id="sec-scrollbar-widgets">
<title>Widgets de barras de desplazamiento</title>
<para>Estas son las barras de desplazamiento estándar. Sólo se deben ser usar para desplazar otro widget, como un <classname>Gtk::Entry</classname>, o un <classname>Gtk::Viewport</classname>, aunque generalmente es más fácil usar el widget <classname>Gtk::ScrolledWindow</classname> en la mayoría de los casos.</para>
<para>La orientación de una <classname>Gtk::Scrollbar</classname> puede ser horizontal o vertical.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scrollbar.html">Reference</ulink></para>
</sect1>
<sect1 id="sec-scale-widgets">
<title>Widgets de Escala</title>
<para>Los widgets <classname>Gtk::Scale</classname> (o «deslizadores») le permiten al usuario seleccionar y manipular visualmente un valor dentro de un rango específico. Puede usar uno, por ejemplo, para ajustar el nivel de ampliación en una previsualización de una imagen, o para controlar el brillo de un color, o especificar la cantidad de minutos de inactividad antes de que aparezca un salvapantallas.</para>
<para>Al igual que con las <classname>Scrollbar</classname>s, la orientación puede ser horizontal o vertical. El constructor predeterminado crea un <classname>Adjustment</classname> con todos sus valores establecidos a <literal>0.0</literal>. Esto no es útil, por lo que necesitará establecer algunos detalles del <classname>Adjustment</classname> para obtener un comportamiento significativo.</para>
<sect2 id="scale-useful-methods">
<title>Métodos útiles</title>
<para>Los widgets <classname>Scale</classname> pueden mostrar su valor actual como un número junto al canal. De manera predeterminada muestran el valor, pero puede cambiar esto con el método <methodname>set_draw_value()</methodname>.</para>
<para>El valor mostrado en un widget de escala se redondea a un dígito decimal de manera predeterminada, como es el campo <literal>value</literal> en su <classname>Gtk::Adjustment</classname>. Puede cambiar esto con el método <methodname>set_digits()</methodname>.</para>
<para>Además, pueden dibujar el valor en diferentes posiciones relativas al canal, especificadas por el método <methodname>set_value_pos()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scale.html">Reference</ulink></para>
</sect2>
</sect1>
<sect1 id="sec-range-example">
<title>Ejemplo</title>
<para>Este ejemplo muestra una ventana con tres widgets de rango, todos conectados al mismo ajuste, junto con un par de controles para establecer algunos de los parámetros mencionados anteriormente y en la sección de ajustes, para que pueda ver cómo afectan la manera en la que estos widgets funcionan para el usuario.</para>
<figure id="figure-range-widgets">
<title>Widgets de Rango</title>
<screenshot>
<graphic format="PNG" fileref="figures/range_widgets.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/range_widgets?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_RANGEWIDGETS_H
#define GTKMM_EXAMPLE_RANGEWIDGETS_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_checkbutton_toggled();
void on_combo_position();
void on_adjustment1_value_changed();
void on_adjustment2_value_changed();
void on_button_quit();
//Child widgets:
Gtk::Box m_VBox_Top, m_VBox2, m_VBox_HScale;
Gtk::Box m_HBox_Scales, m_HBox_Combo, m_HBox_Digits, m_HBox_PageSize;
Glib::RefPtr<Gtk::Adjustment> m_adjustment, m_adjustment_digits, m_adjustment_pagesize;
Gtk::Scale m_VScale;
Gtk::Scale m_HScale, m_Scale_Digits, m_Scale_PageSize;
Gtk::Separator m_Separator;
Gtk::CheckButton m_CheckButton;
Gtk::Scrollbar m_Scrollbar;
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_position_type); add(m_col_title); }
Gtk::TreeModelColumn<Gtk::PositionType> m_col_position_type;
Gtk::TreeModelColumn<Glib::ustring> m_col_title;
};
ModelColumns m_Columns;
//Child widgets:
Gtk::ComboBox m_ComboBox_Position;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLE_RANGEWIDGETS_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
:
m_VBox_Top(Gtk::ORIENTATION_VERTICAL, 0),
m_VBox2(Gtk::ORIENTATION_VERTICAL, 20),
m_VBox_HScale(Gtk::ORIENTATION_VERTICAL, 10),
m_HBox_Scales(Gtk::ORIENTATION_HORIZONTAL, 10),
m_HBox_Combo(Gtk::ORIENTATION_HORIZONTAL, 10),
m_HBox_Digits(Gtk::ORIENTATION_HORIZONTAL, 10),
m_HBox_PageSize(Gtk::ORIENTATION_HORIZONTAL, 10),
// Value, lower, upper, step_increment, page_increment, page_size:
// Note that the page_size value only makes a difference for
// scrollbar widgets, and the highest value you'll get is actually
// (upper - page_size).
m_adjustment( Gtk::Adjustment::create(0.0, 0.0, 101.0, 0.1, 1.0, 1.0) ),
m_adjustment_digits( Gtk::Adjustment::create(1.0, 0.0, 5.0, 1.0, 2.0) ),
m_adjustment_pagesize( Gtk::Adjustment::create(1.0, 1.0, 101.0) ),
m_VScale(m_adjustment, Gtk::ORIENTATION_VERTICAL),
m_HScale(m_adjustment, Gtk::ORIENTATION_HORIZONTAL),
m_Scale_Digits(m_adjustment_digits),
m_Scale_PageSize(m_adjustment_pagesize),
// A checkbutton to control whether the value is displayed or not:
m_CheckButton("Display value on scale widgets", 0),
// Reuse the same adjustment again.
// Notice how this causes the scales to always be updated
// continuously when the scrollbar is moved.
m_Scrollbar(m_adjustment),
m_Button_Quit("Quit")
{
set_title("range controls");
set_default_size(300, 350);
//VScale:
m_VScale.set_digits(1);
m_VScale.set_value_pos(Gtk::POS_TOP);
m_VScale.set_draw_value();
m_VScale.set_inverted(); // highest value at top
//HScale:
m_HScale.set_digits(1);
m_HScale.set_value_pos(Gtk::POS_TOP);
m_HScale.set_draw_value();
add(m_VBox_Top);
m_VBox_Top.pack_start(m_VBox2);
m_VBox2.set_border_width(10);
m_VBox2.pack_start(m_HBox_Scales);
//Put VScale and HScale (above scrollbar) side-by-side.
m_HBox_Scales.pack_start(m_VScale);
m_HBox_Scales.pack_start(m_VBox_HScale);
m_VBox_HScale.pack_start(m_HScale);
//Scrollbar:
m_VBox_HScale.pack_start(m_Scrollbar);
//CheckButton:
m_CheckButton.set_active();
m_CheckButton.signal_toggled().connect( sigc::mem_fun(*this,
&ExampleWindow::on_checkbutton_toggled) );
m_VBox2.pack_start(m_CheckButton, Gtk::PACK_SHRINK);
//Position ComboBox:
//Create the Tree model:
m_refTreeModel = Gtk::ListStore::create(m_Columns);
m_ComboBox_Position.set_model(m_refTreeModel);
m_ComboBox_Position.pack_start(m_Columns.m_col_title);
//Fill the ComboBox's Tree Model:
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_position_type] = Gtk::POS_TOP;
row[m_Columns.m_col_title] = "Top";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_position_type] = Gtk::POS_BOTTOM;
row[m_Columns.m_col_title] = "Bottom";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_position_type] = Gtk::POS_LEFT;
row[m_Columns.m_col_title] = "Left";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_position_type] = Gtk::POS_RIGHT;
row[m_Columns.m_col_title] = "Right";
m_VBox2.pack_start(m_HBox_Combo, Gtk::PACK_SHRINK);
m_HBox_Combo.pack_start(
*Gtk::manage(new Gtk::Label("Scale Value Position:", 0)), Gtk::PACK_SHRINK);
m_HBox_Combo.pack_start(m_ComboBox_Position);
m_ComboBox_Position.signal_changed().connect( sigc::mem_fun(*this, &ExampleWindow::on_combo_position) );
m_ComboBox_Position.set_active(0); // Top
//Digits:
m_HBox_Digits.pack_start(
*Gtk::manage(new Gtk::Label("Scale Digits:", 0)), Gtk::PACK_SHRINK);
m_Scale_Digits.set_digits(0);
m_adjustment_digits->signal_value_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_adjustment1_value_changed));
m_HBox_Digits.pack_start(m_Scale_Digits);
//Page Size:
m_HBox_PageSize.pack_start(
*Gtk::manage(new Gtk::Label("Scrollbar Page Size:", 0)),
Gtk::PACK_SHRINK);
m_Scale_PageSize.set_digits(0);
m_adjustment_pagesize->signal_value_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_adjustment2_value_changed));
m_HBox_PageSize.pack_start(m_Scale_PageSize);
m_VBox2.pack_start(m_HBox_Digits, Gtk::PACK_SHRINK);
m_VBox2.pack_start(m_HBox_PageSize, Gtk::PACK_SHRINK);
m_VBox_Top.pack_start(m_Separator, Gtk::PACK_SHRINK);
m_VBox_Top.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_Button_Quit.set_can_default();
m_Button_Quit.grab_default();
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit));
m_Button_Quit.set_border_width(10);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_checkbutton_toggled()
{
m_VScale.set_draw_value(m_CheckButton.get_active());
m_HScale.set_draw_value(m_CheckButton.get_active());
}
void ExampleWindow::on_combo_position()
{
Gtk::TreeModel::iterator iter = m_ComboBox_Position.get_active();
if(!iter)
return;
Gtk::TreeModel::Row row = *iter;
if(!row)
return;
const Gtk::PositionType postype = row[m_Columns.m_col_position_type];
m_VScale.set_value_pos(postype);
m_HScale.set_value_pos(postype);
}
void ExampleWindow::on_adjustment1_value_changed()
{
const double val = m_adjustment_digits->get_value();
m_VScale.set_digits((int)val);
m_HScale.set_digits((int)val);
}
void ExampleWindow::on_adjustment2_value_changed()
{
const double val = m_adjustment_pagesize->get_value();
m_adjustment->set_page_size(val);
m_adjustment->set_page_increment(val);
// Note that we don't have to emit the "changed" signal
// because gtkmm does this for us.
}
void ExampleWindow::on_button_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect1>
</chapter>
<chapter id="chapter-misc-widgets">
<title>Widgets varios</title>
<sect1 id="sec-labels">
<title>Etiqueta</title>
<para>Las etiquetas son el método principal para poner texto no editable en ventanas, por ejemplo, para poner un título junto a un widget <classname>Entry</classname>. Puede especificar el texto en el constructor, o más tarde con los métodos <methodname>set_text()</methodname> o <methodname>set_markup()</methodname>.</para>
<para>El ancho de la etiqueta se ajusta automáticamente. Puede producir etiquetas con varias líneas poniendo saltos de línea («\n») en la cadena de la etiqueta.</para>
<para>El texto de la etiqueta se puede justificar usando el método <methodname>set_justify()</methodname>. El widget también es capaz de ajustar el texto, lo que se puede activar con <methodname>set_line_wrap()</methodname>.</para>
<para>Gtk::Label soporta formateado simple, por ejemplo, permitiéndole hacer que el texto se vea en negrita, coloreado, o más grande. Puede hacer esto proporcionándole una cadena a <methodname>set_markup()</methodname>, usando la <ulink url="http://developer.gnome.org/pango/unstable/PangoMarkupFormat.html">sintaxis de marcado de Pango</ulink>. Por ejemplo, <code> <b>texto en negrita</b> y <s>texto tachado</s> </code> .</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Label.html">Reference</ulink></para>
<sect2 id="label-example"><title>Ejemplo</title>
<para>Abajo se muestra un ejemplo corto que ilustra estas funciones. Este ejemplo hace uso del widget «Marco» para demostrar mejor los estilos de etiquetas. (El widget «Marco» se explica en la sección <link linkend="sec-frame">Marco</link>). Esto es posible gracias que el primer carácter de <literal>m_Label_Normal</literal> aparece subrayado cuando pulsa la tecla <keycap>Alt</keycap>.</para>
<figure id="figure-label">
<title>Etiqueta</title>
<screenshot>
<graphic format="PNG" fileref="figures/label.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/label?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Child widgets:
Gtk::Box m_HBox;
Gtk::Box m_VBox, m_VBox2;
Gtk::Frame m_Frame_Normal, m_Frame_Multi, m_Frame_Left, m_Frame_Right,
m_Frame_LineWrapped, m_Frame_FilledWrapped, m_Frame_Underlined;
Gtk::Label m_Label_Normal, m_Label_Multi, m_Label_Left, m_Label_Right,
m_Label_LineWrapped, m_Label_FilledWrapped, m_Label_Underlined;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
:
m_HBox(Gtk::ORIENTATION_HORIZONTAL, 5),
m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
m_VBox2(Gtk::ORIENTATION_VERTICAL, 5),
m_Frame_Normal("Normal Label"),
m_Frame_Multi("Multi-line Label"),
m_Frame_Left("Left Justified Label"),
m_Frame_Right("Right Justified Label"),
m_Frame_LineWrapped("Line wrapped label"),
m_Frame_FilledWrapped("Filled, wrapped label"),
m_Frame_Underlined("Underlined label"),
m_Label_Normal("_This is a Normal label", true),
m_Label_Multi("This is a Multi-line label.\nSecond line\nThird line"),
m_Label_Left("This is a Left-Justified\nMulti-line label.\nThird line"),
m_Label_Right("This is a Right-Justified\nMulti-line label.\nThird line"),
m_Label_Underlined("This label is underlined!\n"
"This one is underlined in quite a funky fashion")
{
set_title("Label");
set_border_width(5);
add(m_HBox);
m_HBox.pack_start(m_VBox, Gtk::PACK_SHRINK);
m_Frame_Normal.add(m_Label_Normal);
m_VBox.pack_start(m_Frame_Normal, Gtk::PACK_SHRINK);
m_Frame_Multi.add(m_Label_Multi);
m_VBox.pack_start(m_Frame_Multi, Gtk::PACK_SHRINK);
m_Label_Left.set_justify(Gtk::JUSTIFY_LEFT);
m_Frame_Left.add(m_Label_Left);
m_VBox.pack_start(m_Frame_Left, Gtk::PACK_SHRINK);
m_Label_Right.set_justify(Gtk::JUSTIFY_RIGHT);
m_Frame_Right.add(m_Label_Right);
m_VBox.pack_start(m_Frame_Right, Gtk::PACK_SHRINK);
m_HBox.pack_start(m_VBox2, Gtk::PACK_SHRINK);
m_Label_LineWrapped.set_text(
"This is an example of a line-wrapped label. It "
/* add a big space to the next line to test spacing */
"should not be taking up the entire "
"width allocated to it, but automatically "
"wraps the words to fit. "
"The time has come, for all good men, to come to "
"the aid of their party. "
"The sixth sheik's six sheep's sick.\n"
" It supports multiple paragraphs correctly, "
"and correctly adds "
"many extra spaces. ");
m_Label_LineWrapped.set_line_wrap();
m_Frame_LineWrapped.add(m_Label_LineWrapped);
m_VBox2.pack_start(m_Frame_LineWrapped, Gtk::PACK_SHRINK);
m_Label_FilledWrapped.set_text(
"This is an example of a line-wrapped, filled label. "
"It should be taking "
"up the entire width allocated to it. "
"Here is a sentence to prove "
"my point. Here is another sentence. "
"Here comes the sun, do de do de do.\n"
" This is a new paragraph.\n"
" This is another newer, longer, better "
"paragraph. It is coming to an end, "
"unfortunately.");
m_Label_FilledWrapped.set_justify(Gtk::JUSTIFY_FILL);
m_Label_FilledWrapped.set_line_wrap();
m_Frame_FilledWrapped.add(m_Label_FilledWrapped);
m_VBox2.pack_start(m_Frame_FilledWrapped, Gtk::PACK_SHRINK);
m_Label_Underlined.set_justify(Gtk::JUSTIFY_LEFT);
m_Label_Underlined.set_pattern (
"_________________________ _ _________ _ ______"
" __ _______ ___");
m_Frame_Underlined.add(m_Label_Underlined);
m_VBox2.pack_start(m_Frame_Underlined, Gtk::PACK_SHRINK);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-text-entry">
<title>Entry</title>
<sect2 id="sec-text-entry-simple">
<title>Uso simple</title>
<para>Los widgets de «entry» le permiten al usuario introducir texto. Puede cambiar el contenido con el método <methodname>set_text()</methodname>, y leer el contenido actual con el método <methodname>get_text()</methodname>.</para>
<para>Ocasionalmente querrá definir un widget <classname>Entry</classname> como sólo lectura. Esto se puede hacer pasándole <literal>false</literal> al método <methodname>set_editable()</methodname>.</para>
<para>Para introducir contraseñas, frases de paso, y otra información que no quiera que aparezca en la pantalla, llamar a <methodname>set_visibility</methodname> con <literal>false</literal> hará que el texto permanezca oculto.</para>
<para>Tal vez quiera que se le notifique cuando el usuario escribe en un widget de entrada de texto. <classname>Gtk::Entry</classname> proporciona dos señales, <literal>activate</literal> y <literal>changed</literal> para este propósito. <literal>activate</literal> se emite cuando el usuario pulsa la tecla Intro en un widget de entrada de texto; <literal>changed</literal> se emite cuando el texto en el widget cambia. Puede usarlas, por ejemplo, para validar o filtrar el texto que el usuario introduce. Mover el foco del teclado a otro widget también podría señalar que el usuario ha terminado de introducir texto. La señal <literal>focus_out_event</literal> que <classname>Gtk::Entry</classname> hereda de <classname>Gtk::Widget</classname> puede notificarle cuando esto sucede. La sección <link linkend="sec-comboboxentry">«ComboBox» con una entrada</link> contiene programas de ejemplo que usan estas señales.</para>
<para>Si le pasa <literal>true</literal> al método <methodname>set_activates_default()</methodname>, pulsar Intro en el <classname>Gtk::Entry</classname> activará el widget predeterminado para la ventana que contiene al <classname>Gtk::Entry</classname>. Esto es especialmente útil en cuadros de diálogo. El widget predeterminado es generalmente uno de los botones del diálogo, que, por ejemplo, cerrará el cuadro de diálogo. Para establecer un widget como predeterminado, use <methodname>Gtk::Widget::set_can_default()</methodname> y <methodname>Gtk::Widget::grab_default()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Entry.html">Reference</ulink></para>
<sect3 id="entry-example"><title>Ejemplo simple de «Entry»</title>
<para>Este ejemplo usa <classname>Gtk::Entry</classname>. También tiene dos <classname>CheckButton</classname>, con los que puede conmutar las opciones «editable» y «visible».</para>
<figure id="figure-entry-simple">
<title>Entry</title>
<screenshot>
<graphic format="PNG" fileref="figures/entry.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/simple?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_checkbox_editable_toggled();
void on_checkbox_visibility_toggled();
void on_button_close();
//Child widgets:
Gtk::Box m_HBox;
Gtk::Box m_VBox;
Gtk::Entry m_Entry;
Gtk::Button m_Button_Close;
Gtk::CheckButton m_CheckButton_Editable, m_CheckButton_Visible;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Close("Close"),
m_CheckButton_Editable("Editable"),
m_CheckButton_Visible("Visible")
{
set_size_request(200, 100);
set_title("Gtk::Entry");
add(m_VBox);
m_Entry.set_max_length(50);
m_Entry.set_text("hello");
m_Entry.set_text(m_Entry.get_text() + " world");
m_Entry.select_region(0, m_Entry.get_text_length());
m_VBox.pack_start(m_Entry);
// Note that add() can also be used instead of pack_xxx()
m_VBox.add(m_HBox);
m_HBox.pack_start(m_CheckButton_Editable);
m_CheckButton_Editable.signal_toggled().connect( sigc::mem_fun(*this,
&ExampleWindow::on_checkbox_editable_toggled) );
m_CheckButton_Editable.set_active(true);
m_HBox.pack_start(m_CheckButton_Visible);
m_CheckButton_Visible.signal_toggled().connect( sigc::mem_fun(*this,
&ExampleWindow::on_checkbox_visibility_toggled) );
m_CheckButton_Visible.set_active(true);
m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_close) );
m_VBox.pack_start(m_Button_Close);
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_checkbox_editable_toggled()
{
m_Entry.set_editable(m_CheckButton_Editable.get_active());
}
void ExampleWindow::on_checkbox_visibility_toggled()
{
m_Entry.set_visibility(m_CheckButton_Visible.get_active());
}
void ExampleWindow::on_button_close()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-text-entry-completion">
<title>Completado de «Entry»</title>
<para>Un widget <classname>Entry</classname> puede ofrecer una lista desplegable de opciones pre-existentes sobre la base de los primeros caracteres escritos por el usuario. Por ejemplo, un cuadro de diálogo de búsqueda podría sugerir el texto de búsquedas anteriores.</para>
<para>Para activar esta funcionalidad, cree un objeto <classname>EntryCompletion</classname> y proporcióneselo al widget <classname>Entry</classname> mediante el método <methodname>set_completion()</methodname>.</para>
<para>El <classname>EntryCompletion</classname> puede usar un <classname>TreeModel</classname> que contenga las entradas posibles, especificadas por <methodname>set_model()</methodname>. Luego llame a <methodname>set_text_column()</methodname> para especificar cuál de las columnas de su modelo debe usarse para las posibles entradas de texto.</para>
<para>Alternativamente, si una lista completa de entradas posibles fuera muy larga o demasiado incómoda para generar, puede especificar en su lugar un espacio para una retrollamada con <methodname>set_match_func()</methodname>. Esto también es útil si no desea usar el principio de la cadena.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1EntryCompletion.html">Reference</ulink></para>
<sect3 id="entry-completion-example"><title>Ejemplo de completado de «Entry»</title>
<para>Este ejemplo crea un <classname>Gtk::EntryCompletion</classname> y lo asocia a un widget <classname>Gtk::Entry</classname>. Se usan un <classname>Gtk::TreeModel</classname> de entradas posibles para el completado y algunas acciones adicionales.</para>
<figure id="figure-entry-completion">
<title>Completado de «Entry»</title>
<screenshot>
<graphic format="PNG" fileref="figures/entry_completion.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/completion?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_close();
void on_completion_action_activated(int index);
//See the comment in the implementation:
//bool on_completion_match(const Glib::ustring& key, const Gtk::TreeModel::const_iterator& iter);
//Tree model columns, for the EntryCompletion's filter model:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<unsigned int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_Columns;
typedef std::map<int, Glib::ustring> type_actions_map;
type_actions_map m_CompletionActions;
//Child widgets:
Gtk::Box m_HBox;
Gtk::Box m_VBox;
Gtk::Entry m_Entry;
Gtk::Label m_Label;
Gtk::Button m_Button_Close;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Label("Press a or b to see a list of possible completions and actions."),
m_Button_Close("Close")
{
//set_size_request(200, 100);
set_title("Gtk::EntryCompletion");
add(m_VBox);
m_VBox.pack_start(m_Entry, Gtk::PACK_SHRINK);
m_VBox.pack_start(m_Label, Gtk::PACK_EXPAND_WIDGET);
m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_close) );
m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
//Add an EntryCompletion:
Glib::RefPtr<Gtk::EntryCompletion> completion =
Gtk::EntryCompletion::create();
m_Entry.set_completion(completion);
//Create and fill the completion's filter model
Glib::RefPtr<Gtk::ListStore> refCompletionModel =
Gtk::ListStore::create(m_Columns);
completion->set_model(refCompletionModel);
// For more complex comparisons, use a filter match callback, like this.
// See the comment below for more details:
//completion->set_match_func( sigc::mem_fun(*this,
//&ExampleWindow::on_completion_match) );
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(refCompletionModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Alan Zebedee";
row = *(refCompletionModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Adrian Boo";
row = *(refCompletionModel->append());
row[m_Columns.m_col_id] = 3;
row[m_Columns.m_col_name] = "Bob McRoberts";
row = *(refCompletionModel->append());
row[m_Columns.m_col_id] = 4;
row[m_Columns.m_col_name] = "Bob McBob";
//Tell the completion what model column to use to
//- look for a match (when we use the default matching, instead of
// set_match_func().
//- display text in the entry when a match is found.
completion->set_text_column(m_Columns.m_col_name);
//Add actions to the completion:
//These are just extra items shown at the bottom of the list of possible
//completions.
//Remember them for later.
m_CompletionActions[0] = "Use Wizard";
m_CompletionActions[1] = "Browse for Filename";
for(type_actions_map::iterator iter = m_CompletionActions.begin();
iter != m_CompletionActions.end(); ++iter)
{
int position = iter->first;
Glib::ustring title = iter->second;
completion->insert_action_text(title, position);
}
completion->signal_action_activated().connect( sigc::mem_fun(*this,
&ExampleWindow::on_completion_action_activated) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_close()
{
hide();
}
/* You can do more complex matching with a handler like this.
* For instance, you could check for substrings inside the string instead of the start,
* or you could look for the key in extra model columns as well as the model column that will be displayed.
* The code here is not actually more complex - it's a reimplementation of the default behaviour.
*
bool ExampleWindow::on_completion_match(const Glib::ustring& key, const
Gtk::TreeModel::const_iterator& iter)
{
if(iter)
{
Gtk::TreeModel::Row row = *iter;
Glib::ustring::size_type key_length = key.size();
Glib::ustring filter_string = row[m_Columns.m_col_name];
Glib::ustring filter_string_start = filter_string.substr(0, key_length);
//The key is lower-case, even if the user input is not.
filter_string_start = filter_string_start.lowercase();
if(key == filter_string_start)
return true; //A match was found.
}
return false; //No match.
}
*/
void ExampleWindow::on_completion_action_activated(int index)
{
type_actions_map::iterator iter = m_CompletionActions.find(index);
if(iter != m_CompletionActions.end()) //If it's in the map
{
Glib::ustring title = iter->second;
std::cout << "Action selected: " << title << std::endl;
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-text-entry-icons">
<title>Iconos de «Entry»</title>
<para lang="en">An <classname>Entry</classname> widget can show an icon at the start or
end of the text area. The icon can be specifed by methods such as
<methodname>set_icon_from_pixbuf()</methodname> or
<methodname>set_icon_from_icon_name()</methodname>. An application can respond to the
user pressing the icon by handling the
<methodname>signal_icon_press</methodname> signal.</para>
<sect3 id="entry-icon-example"><title>Ejemplo de icono de «Entry»</title>
<para>Este ejemplo muestra un widget <classname>Gtk::Entry</classname> con un icono de búsqueda del almacén, e imprime texto en la terminal cuando se pulsa el icono.</para>
<figure id="figure-entry-icon">
<title>«Entry» con icono</title>
<screenshot>
<graphic format="PNG" fileref="figures/entry_icon.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/icon?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_icon_pressed(Gtk::EntryIconPosition icon_pos, const GdkEventButton* event);
void on_button_close();
//Child widgets:
Gtk::Box m_VBox;
Gtk::Entry m_Entry;
Gtk::Button m_Button_Close;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Close("Close")
{
set_title("Gtk::Entry");
add(m_VBox);
m_Entry.set_max_length(50);
m_Entry.set_text("Hello world");
m_VBox.pack_start(m_Entry, Gtk::PACK_SHRINK);
m_Entry.set_icon_from_icon_name("edit-find");
m_Entry.signal_icon_press().connect( sigc::mem_fun(*this, &ExampleWindow::on_icon_pressed) );
m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_close) );
m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_icon_pressed(Gtk::EntryIconPosition /* icon_pos */, const GdkEventButton* /* event */)
{
std::cout << "Icon pressed." << std::endl;
}
void ExampleWindow::on_button_close()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-text-entry-progress">
<title>«Entry» de progreso</title>
<para>Un widget <classname>Entry</classname> puede mostrar una barra de progreso dentro del área del texto, bajo el texto introducido. La barra de progreso se mostrará si se llama a los métodos <methodname>set_progress_fraction()</methodname> o <methodname>set_progress_pulse_step()</methodname>.</para>
<sect3 id="entry-progress-example"><title>Ejemplo de «Entry» de progreso</title>
<para>Este ejemplo muestra un widget <classname>Gtk::Entry</classname> con una barra de progreso.</para>
<figure id="figure-entry-progress">
<title>«Entry» con barra de progreso</title>
<screenshot>
<graphic format="PNG" fileref="figures/entry_progress.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/progress?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
bool on_timeout();
void on_button_close();
//Child widgets:
Gtk::Box m_VBox;
Gtk::Entry m_Entry;
Gtk::Button m_Button_Close;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Close("Close")
{
set_title("Gtk::Entry");
add(m_VBox);
m_Entry.set_max_length(50);
m_Entry.set_text("Hello world");
m_VBox.pack_start(m_Entry, Gtk::PACK_SHRINK);
//Change the progress fraction every 0.1 second:
Glib::signal_timeout().connect(
sigc::mem_fun(*this, &ExampleWindow::on_timeout),
100
);
m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_close) );
m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
bool ExampleWindow::on_timeout()
{
static double fraction = 0;
m_Entry.set_progress_fraction(fraction);
fraction += 0.01;
if(fraction > 1)
fraction = 0;
return true;
}
void ExampleWindow::on_button_close()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
</sect1>
<sect1 id="sec-spinbutton">
<title>SpinButton</title>
<para lang="en">
A <classname>SpinButton</classname> allows the user to select a value from a
range of numeric values. It has an <classname>Entry</classname> widget with increment and decrement buttons
at the side. Clicking the buttons causes the value to 'spin' up and down across
the range of possible values. The <classname>Entry</classname> widget may also
be used to enter a value directly.
</para>
<para>El valor puede tener un número ajustable de decimales, y el tamaño del paso es configurable. Los <classname>SpinButton</classname> también tienen una característica de «auto-repetición»: mantener pulsada una de las flechas puede, opcionalmente, causar que el valor cambie más rápidamente cuanto más tiempo se mantenga pulsada la flecha.</para>
<para lang="en">
<classname>SpinButton</classname>s use an <link linkend="chapter-adjustment">Adjustment</link> object to hold information about
the range of values. These Adjustment attributes are used by the Spin Button
like so:
<itemizedlist>
<listitem>
<para lang="en">
<literal>value</literal>: value for the Spin Button
</para>
</listitem>
<listitem>
<para lang="en">
<literal>lower</literal>: lower range value
</para>
</listitem>
<listitem>
<para lang="en">
<literal>upper</literal>: upper range value
</para>
</listitem>
<listitem>
<para lang="en">
<literal>step_increment</literal>: value to increment/decrement when pressing
mouse button 1 on a button
</para>
</listitem>
<listitem>
<para lang="en">
<literal>page_increment</literal>: value to increment/decrement when pressing
mouse button 2 on a button
</para>
</listitem>
<listitem>
<para lang="en">
<literal>page_size</literal>: unused
</para>
</listitem>
</itemizedlist>
</para>
<para>Además, el botón 3 del ratón se puede usar para saltar directamente a los valores <literal>upper</literal> o <literal>lower</literal>.</para>
<para>El <classname>SpinButton</classname> puede crear un <classname>Adjustment</classname> predeterminado, al que puede acceder mediante el método <methodname>get_adjustment()</methodname>, o puede especificar un <classname>Adjustment</classname> existente en el constructor.</para>
<sect2 id="spinbutton-methods"><title>Métodos</title>
<para>La cantidad de lugares decimales se puede alterar usando el método <methodname>set_digits()</methodname>.</para>
<para>Puede establecer el valor del «spinbutton» usando el método <methodname>set_value()</methodname>, y obtenerlo con <methodname>get_value()</methodname>.</para>
<para>El método <methodname>spin()</methodname> «gira» el <classname>SpinButton</classname>, como si se hubiera presionado una de sus flechas. Debe especificar un <classname>Gtk::SpinType</classname> para especificar la dirección de su posición nueva.</para>
<para>Para que el usuario no pueda introducir caracteres no numéricos al cuadro de entrada, pásele <literal>true</literal> al método <methodname>set_numeric()</methodname>.</para>
<para>Para que el <classname>SpinButton</classname> «salte» entre sus límites superior e inferior, use el método <methodname>set_wrap()</methodname>.</para>
<para>Para forzarlo a encajar en el <literal>step_increment</literal> más cercano, use <methodname>set_snap_to_ticks()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1SpinButton.html">Reference</ulink></para>
</sect2>
<sect2 id="spinbutton-example"><title>Ejemplo</title>
<para>Aquí hay un ejemplo de un <classname>SpinButton</classname> en acción:</para>
<figure id="figure-spinbutton">
<title>SpinButton</title>
<screenshot>
<graphic format="PNG" fileref="figures/spinbutton.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/spinbutton?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_checkbutton_snap();
void on_checkbutton_numeric();
void on_spinbutton_digits_changed();
void on_button_close();
enum enumValueFormats
{
VALUE_FORMAT_INT,
VALUE_FORMAT_FLOAT
};
void on_button_getvalue(enumValueFormats display);
//Child widgets:
Gtk::Frame m_Frame_NotAccelerated, m_Frame_Accelerated;
Gtk::Box m_HBox_NotAccelerated, m_HBox_Accelerated,
m_HBox_Buttons;
Gtk::Box m_VBox_Main, m_VBox, m_VBox_Day, m_VBox_Month, m_VBox_Year,
m_VBox_Accelerated, m_VBox_Value, m_VBox_Digits;
Gtk::Label m_Label_Day, m_Label_Month, m_Label_Year,
m_Label_Value, m_Label_Digits,
m_Label_ShowValue;
Glib::RefPtr<Gtk::Adjustment> m_adjustment_day, m_adjustment_month, m_adjustment_year,
m_adjustment_value, m_adjustment_digits;
Gtk::SpinButton m_SpinButton_Day, m_SpinButton_Month, m_SpinButton_Year,
m_SpinButton_Value, m_SpinButton_Digits;
Gtk::CheckButton m_CheckButton_Snap, m_CheckButton_Numeric;
Gtk::Button m_Button_Int, m_Button_Float, m_Button_Close;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
#include <cstdio>
ExampleWindow::ExampleWindow()
:
m_Frame_NotAccelerated("Not accelerated"),
m_Frame_Accelerated("Accelerated"),
m_VBox_Main(Gtk::ORIENTATION_VERTICAL, 5),
m_VBox(Gtk::ORIENTATION_VERTICAL),
m_VBox_Day(Gtk::ORIENTATION_VERTICAL),
m_VBox_Month(Gtk::ORIENTATION_VERTICAL),
m_VBox_Year(Gtk::ORIENTATION_VERTICAL),
m_VBox_Accelerated(Gtk::ORIENTATION_VERTICAL),
m_VBox_Value(Gtk::ORIENTATION_VERTICAL),
m_VBox_Digits(Gtk::ORIENTATION_VERTICAL),
m_Label_Day("Day: "),
m_Label_Month("Month: "),
m_Label_Year("Year: "),
m_Label_Value("Value: "),
m_Label_Digits("Digits: "),
m_adjustment_day( Gtk::Adjustment::create(1.0, 1.0, 31.0, 1.0, 5.0, 0.0) ),
m_adjustment_month( Gtk::Adjustment::create(1.0, 1.0, 12.0, 1.0, 5.0, 0.0) ),
m_adjustment_year( Gtk::Adjustment::create(2012.0, 1.0, 2200.0, 1.0, 100.0, 0.0) ),
m_adjustment_value( Gtk::Adjustment::create(0.0, -10000.0, 10000.0, 0.5, 100.0, 0.0) ),
m_adjustment_digits( Gtk::Adjustment::create(2.0, 1.0, 5.0, 1.0, 1.0, 0.0) ),
m_SpinButton_Day(m_adjustment_day),
m_SpinButton_Month(m_adjustment_month),
m_SpinButton_Year(m_adjustment_year),
m_SpinButton_Value(m_adjustment_value, 1.0, 2),
m_SpinButton_Digits(m_adjustment_digits),
m_CheckButton_Snap("Snap to 0.5-ticks"),
m_CheckButton_Numeric("Numeric only input mode"),
m_Button_Int("Value as Int"),
m_Button_Float("Value as Float"),
m_Button_Close("Close")
{
set_title("SpinButton");
m_VBox_Main.set_border_width(10);
add(m_VBox_Main);
m_VBox_Main.pack_start(m_Frame_NotAccelerated);
m_VBox.set_border_width(5);
m_Frame_NotAccelerated.add(m_VBox);
/* Day, month, year spinners */
m_VBox.pack_start(m_HBox_NotAccelerated, Gtk::PACK_EXPAND_WIDGET, 5);
m_Label_Day.set_alignment(Gtk::ALIGN_START);
m_VBox_Day.pack_start(m_Label_Day);
m_SpinButton_Day.set_wrap();
m_VBox_Day.pack_start(m_SpinButton_Day);
m_HBox_NotAccelerated.pack_start(m_VBox_Day, Gtk::PACK_EXPAND_WIDGET, 5);
m_Label_Month.set_alignment(Gtk::ALIGN_START);
m_VBox_Month.pack_start(m_Label_Month);
m_SpinButton_Month.set_wrap();
m_VBox_Month.pack_start(m_SpinButton_Month);
m_HBox_NotAccelerated.pack_start(m_VBox_Month, Gtk::PACK_EXPAND_WIDGET, 5);
m_Label_Year.set_alignment(Gtk::ALIGN_START);
m_VBox_Year.pack_start(m_Label_Year);
m_SpinButton_Year.set_wrap();
m_SpinButton_Year.set_size_request(55, -1);
m_VBox_Year.pack_start(m_SpinButton_Year);
m_HBox_NotAccelerated.pack_start(m_VBox_Year, Gtk::PACK_EXPAND_WIDGET, 5);
//Accelerated:
m_VBox_Main.pack_start(m_Frame_Accelerated);
m_VBox_Accelerated.set_border_width(5);
m_Frame_Accelerated.add(m_VBox_Accelerated);
m_VBox_Accelerated.pack_start(m_HBox_Accelerated, Gtk::PACK_EXPAND_WIDGET, 5);
m_HBox_Accelerated.pack_start(m_VBox_Value, Gtk::PACK_EXPAND_WIDGET, 5);
m_Label_Value.set_alignment(Gtk::ALIGN_START);
m_VBox_Value.pack_start(m_Label_Value);
m_SpinButton_Value.set_wrap();
m_SpinButton_Value.set_size_request(100, -1);
m_VBox_Value.pack_start(m_SpinButton_Value);
m_HBox_Accelerated.pack_start(m_VBox_Digits, Gtk::PACK_EXPAND_WIDGET, 5);
m_Label_Digits.set_alignment(Gtk::ALIGN_START);
m_VBox_Digits.pack_start(m_Label_Digits);
m_SpinButton_Digits.set_wrap();
m_adjustment_digits->signal_value_changed().connect( sigc::mem_fun(*this,
&ExampleWindow::on_spinbutton_digits_changed) );
m_VBox_Digits.pack_start(m_SpinButton_Digits);
//CheckButtons:
m_VBox_Accelerated.pack_start(m_CheckButton_Snap);
m_CheckButton_Snap.set_active();
m_CheckButton_Snap.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_checkbutton_snap) );
m_VBox_Accelerated.pack_start(m_CheckButton_Numeric);
m_CheckButton_Numeric.set_active();
m_CheckButton_Numeric.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_checkbutton_numeric) );
//Buttons:
m_VBox_Accelerated.pack_start (m_HBox_Buttons, Gtk::PACK_SHRINK, 5);
m_Button_Int.signal_clicked().connect( sigc::bind( sigc::mem_fun(*this,
&ExampleWindow::on_button_getvalue), VALUE_FORMAT_INT) );
m_HBox_Buttons.pack_start(m_Button_Int, Gtk::PACK_EXPAND_WIDGET, 5);
m_Button_Float.signal_clicked().connect( sigc::bind( sigc::mem_fun(*this,
&ExampleWindow::on_button_getvalue), VALUE_FORMAT_FLOAT) );
m_HBox_Buttons.pack_start(m_Button_Float, Gtk::PACK_EXPAND_WIDGET, 5);
m_VBox_Accelerated.pack_start(m_Label_ShowValue);
m_Label_ShowValue.set_text("0");
//Close button:
m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_close) );
m_VBox_Main.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_close()
{
hide();
}
void ExampleWindow::on_checkbutton_snap()
{
m_SpinButton_Value.set_snap_to_ticks( m_CheckButton_Snap.get_active() );
}
void ExampleWindow::on_checkbutton_numeric()
{
m_SpinButton_Value.set_numeric( m_CheckButton_Numeric.get_active() );
}
void ExampleWindow::on_spinbutton_digits_changed()
{
m_SpinButton_Value.set_digits( m_SpinButton_Digits.get_value_as_int() );
}
void ExampleWindow::on_button_getvalue(enumValueFormats display)
{
gchar buf[32];
if (display == VALUE_FORMAT_INT)
sprintf (buf, "%d", m_SpinButton_Value.get_value_as_int());
else
sprintf (buf, "%0.*f", m_SpinButton_Value.get_digits(),
m_SpinButton_Value.get_value());
m_Label_ShowValue.set_text(buf);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-progressbar">
<title>ProgressBar</title>
<para>Las barras de progreso se usan para mostrar el estado de una operación en curso. Por ejemplo, una <classname>ProgressBar</classname> puede mostrar cuánto se ha completado de una tarea.</para>
<para>Para cambiar el valor mostrado, use el método <methodname>set_fraction()</methodname>, pasándole un <type>double</type> entre 0.0 y 1.0 para proporcionarle el porcentaje nuevo.</para>
<para>Una <classname>ProgressBar</classname> es horizontal y de izquierda a derecha de manera predeterminada, pero se puede cambiar a una barra de progreso vertical mediante el uso del método <methodname>set_orientation()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ProgressBar.html">Reference</ulink></para>
<sect2 id="progressbar-activity-mode">
<title>Modo de actividad</title>
<para>Además de indicar la cantidad de progreso que se ha completado, la barra de progreso también puede usarse para indicar que ocurre actividad; esto se realiza poniendo la barra en <emphasis>modo de actividad</emphasis>. En este modo, la barra de progreso muestra un pequeño rectángulo que se mueve hacia adelante y atrás. El modo de actividad es útil en las situaciones en las que el progreso de una operación no se puede calcular como un rango de valores (por ejemplo, cuando se recibe un archivo de tamaño desconocido).</para>
<para>Para hacer esto, debe llamar al método <methodname>pulse()</methodname> a intervalos regulares. También puede elegir el tamaño del paso con el método <methodname>set_pulse_step()</methodname>.</para>
<para>La barra de progreso también puede mostrar una cadena de texto configurable en su canal, usando el método <methodname>set_text()</methodname>.</para>
</sect2>
<sect2 id="progressbar-example"><title>Ejemplo</title>
<figure id="figure-progressbar">
<title>ProgressBar</title>
<screenshot>
<graphic format="PNG" fileref="figures/progressbar.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/progressbar?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_checkbutton_text();
void on_checkbutton_activity();
void on_checkbutton_inverted();
virtual bool on_timeout();
void on_button_close();
//Child widgets:
Gtk::Box m_VBox;
Gtk::Alignment m_Alignment;
Gtk::Grid m_Grid;
Gtk::ProgressBar m_ProgressBar;
Gtk::Separator m_Separator;
Gtk::CheckButton m_CheckButton_Text, m_CheckButton_Activity, m_CheckButton_Inverted;
Gtk::Button m_Button_Close;
int m_connection_id_timeout;
bool m_bActivityMode;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
m_Alignment(0.5, 0.5, 0, 0),
m_CheckButton_Text("Show text"),
m_CheckButton_Activity("Activity mode"),
m_CheckButton_Inverted("Right to Left"),
m_Button_Close("Close"),
m_bActivityMode(false)
{
set_resizable();
set_title("Gtk::ProgressBar");
m_VBox.set_border_width(10);
add(m_VBox);
m_VBox.pack_start(m_Alignment, Gtk::PACK_SHRINK, 5);
m_Alignment.add(m_ProgressBar);
m_ProgressBar.set_text("some text");
m_ProgressBar.set_show_text(false);
//Add a timer callback to update the value of the progress bar:
m_connection_id_timeout = Glib::signal_timeout().connect(sigc::mem_fun(*this,
&ExampleWindow::on_timeout), 50 );
m_VBox.pack_start(m_Separator, Gtk::PACK_SHRINK);
m_VBox.pack_start(m_Grid);
m_Grid.set_row_homogeneous(true);
//Add a check button to select displaying of the trough text:
m_Grid.attach(m_CheckButton_Text, 0, 0, 1, 1);
m_CheckButton_Text.property_margin() = 5;
m_CheckButton_Text.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_checkbutton_text) );
//Add a check button to toggle activity mode:
m_Grid.attach(m_CheckButton_Activity, 0, 1, 1, 1);
m_CheckButton_Activity.property_margin() = 5;
m_CheckButton_Activity.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_checkbutton_activity) );
//Add a check button to select growth from left to right or from right to left:
m_Grid.attach(m_CheckButton_Inverted, 0, 2, 1, 1);
m_CheckButton_Inverted.property_margin() = 5;
m_CheckButton_Inverted.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_checkbutton_inverted) );
//Add a button to exit the program.
m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
m_Button_Close.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_close) );
m_Button_Close.set_can_default();
m_Button_Close.grab_default();
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_checkbutton_text()
{
const bool show_text = m_CheckButton_Text.get_active();
m_ProgressBar.set_show_text(show_text);
}
void ExampleWindow::on_checkbutton_activity()
{
m_bActivityMode = m_CheckButton_Activity.get_active();
if(m_bActivityMode)
m_ProgressBar.pulse();
else
m_ProgressBar.set_fraction(0.0);
}
void ExampleWindow::on_checkbutton_inverted()
{
const bool inverted = m_CheckButton_Inverted.get_active();
m_ProgressBar.set_inverted(inverted);
}
void ExampleWindow::on_button_close()
{
hide();
}
/* Update the value of the progress bar so that we get
* some movement */
bool ExampleWindow::on_timeout()
{
if(m_bActivityMode)
m_ProgressBar.pulse();
else
{
double new_val = m_ProgressBar.get_fraction() + 0.01;
if(new_val > 1.0)
new_val = 0.0;
//Set the new value:
m_ProgressBar.set_fraction(new_val);
}
//As this is a timeout function, return true so that it
//continues to get called
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-infobar">
<title>InfoBar</title>
<para>Una <classname>InfoBar</classname> puede mostrar pequeños elementos de información o hacer preguntas breves. A diferencia de un <classname>Dialog</classname>, aparece encima de la ventana actual en vez de en una ventana nueva. Su API es muy similar a la del <link linkend="chapter-dialogs">Gtk::Dialog</link>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1InfoBar.html">Reference</ulink></para>
<sect2 id="infobar-example"><title>Ejemplo</title>
<figure id="figure-infobar">
<title>InfoBar</title>
<screenshot>
<graphic format="PNG" fileref="figures/infobar.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/infobar?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_infobar_response(int response);
void on_button_quit();
void on_button_clear();
void on_textbuffer_changed();
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer;
Gtk::InfoBar m_InfoBar;
Gtk::Label m_Message_Label;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit, m_Button_Clear;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 6),
m_Button_Quit("_Quit", true),
m_Button_Clear("_Clear", true)
{
set_title("Gtk::InfoBar example");
set_border_width(6);
set_default_size(400, 200);
add(m_VBox);
// Add the message label to the InfoBar:
Gtk::Container* infoBarContainer =
dynamic_cast<Gtk::Container*>(m_InfoBar.get_content_area());
if (infoBarContainer)
infoBarContainer->add(m_Message_Label);
// Add an ok button to the InfoBar:
m_InfoBar.add_button("_OK", 0);
// Add the InfoBar to the vbox:
m_VBox.pack_start(m_InfoBar, Gtk::PACK_SHRINK);
// Create the buffer and set it for the TextView:
m_refTextBuffer = Gtk::TextBuffer::create();
m_TextView.set_buffer(m_refTextBuffer);
// Add the TreeView, inside a ScrolledWindow:
m_ScrolledWindow.add(m_TextView);
// Show the scrollbars only when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
// Add button box:
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Clear, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_spacing(6);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
// Connect signals:
m_InfoBar.signal_response().connect(sigc::mem_fun(*this,
&ExampleWindow::on_infobar_response) );
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
m_Button_Clear.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_clear) );
m_refTextBuffer->signal_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_textbuffer_changed) );
show_all();
// Keep the InfoBar hidden until a message needs to be shown:
m_InfoBar.hide();
// Make the clear button insensitive until text is typed in the buffer. When
// the button is sensitive and it is pressed, the InfoBar is displayed with a
// message.
m_Button_Clear.set_sensitive(false);
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_infobar_response(int)
{
// Clear the message and hide the info bar:
m_Message_Label.set_text("");
m_InfoBar.hide();
}
void ExampleWindow::on_button_quit()
{
hide();
}
void ExampleWindow::on_button_clear()
{
m_refTextBuffer->set_text("");
m_Message_Label.set_text("Cleared the text.");
m_InfoBar.set_message_type(Gtk::MESSAGE_INFO);
m_InfoBar.show();
}
void ExampleWindow::on_textbuffer_changed()
{
m_Button_Clear.set_sensitive(m_refTextBuffer->size() > 0);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-tooltips">
<title>Consejos</title>
<para>Los consejos son pequeñas ventanas de información que aparecen cuando deja su puntero sobre un widget por unos segundos. Use <methodname>set_tooltip_text()</methodname> para establecer una cadena nueva como consejo en cualquier <classname>Widget</classname>. Los <classname>Gtk::ToolItem</classname> no son <classname>Widget</classname>s, pero tienen el mismo método por convenio. <classname>Gtk::Tooltip</classname> es para un uso de los consejos más avanzado, como mostrar una imagen junto al texto.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Widget.html">Widget Reference</ulink></para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Tooltip.html">Tooltip Reference</ulink></para>
<sect2 id="tooltip-example"><title>Ejemplo</title>
<figure id="figure-tooltip">
<title>Consejo</title>
<screenshot>
<graphic format="PNG" fileref="figures/tooltip.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/tooltips?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Methods:
void prepare_textview();
void connect_signals();
//Signal handlers:
void on_markup_checkbutton_click();
bool on_textview_query_tooltip(int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip>& tooltip);
bool on_button_query_tooltip(int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip>& tooltip);
//Child widgets:
Gtk::Box m_vbox;
Gtk::CheckButton m_checkbutton;
Gtk::Label m_label;
Gtk::ScrolledWindow m_scrolled_window;
Gtk::TextView m_text_view;
Glib::RefPtr<Gtk::TextBuffer> m_ref_text_buffer;
Glib::RefPtr<Gtk::TextTag> m_ref_bold_tag;
Gtk::Button m_button;
Gtk::Window m_button_tooltip_window;
};
#endif // GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <vector>
const Glib::ustring app_title = "gtkmm tooltips example";
const Glib::ustring non_markedup_tip = "A tooltip without markup.";
const Glib::ustring markedup_tip = "<i>Markup</i> in a tooltip.";
ExampleWindow::ExampleWindow()
:
m_vbox(Gtk::ORIENTATION_VERTICAL, 3),
m_checkbutton("Click to alternate markup in tooltip"),
m_label("A label"),
m_button("Custom widget in tooltip window"),
m_button_tooltip_window(Gtk::WINDOW_POPUP)
{
//Set up window and the top-level container:
set_title(app_title);
set_border_width(10);
add(m_vbox);
//Check button with markup in tooltip:
m_checkbutton.set_tooltip_text(non_markedup_tip);
m_vbox.pack_start(m_checkbutton, Gtk::PACK_SHRINK);
//Label:
m_label.set_tooltip_text("Another tooltip");
m_vbox.pack_start(m_label, Gtk::PACK_SHRINK);
//Textview:
prepare_textview();
//Button:
// set_tooltip_window(), like set_tooltip_text(),
// will call set_has_tooltip() for us.
m_button.set_tooltip_window(m_button_tooltip_window);
m_vbox.pack_start(m_button, Gtk::PACK_SHRINK);
//Button's custom tooltip window:
m_button_tooltip_window.set_default_size(250, 30);
Gtk::Label* label =
Gtk::manage(new Gtk::Label("A label in a custom tooltip window"));
label->show();
m_button_tooltip_window.add(*label);
connect_signals();
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::prepare_textview()
{
Gtk::TextIter iter;
std::vector< Glib::RefPtr<Gtk::TextTag> > tags;
//Set up a scrolled window:
m_scrolled_window.add(m_text_view);
m_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_vbox.pack_start(m_scrolled_window);
//Create a text buffer with some text:
m_ref_text_buffer = Gtk::TextBuffer::create();
iter = m_ref_text_buffer->end();
m_ref_text_buffer->insert(iter, "Hover over the text ");
//Insert some text with a tag.
//In the tooltip signal handler below, we will show a tooltip
//when mouse pointer is above this tagged text.
m_ref_bold_tag = m_ref_text_buffer->create_tag("bold");
m_ref_bold_tag->set_property("weight", Pango::WEIGHT_BOLD);
tags.push_back(m_ref_bold_tag);
iter = m_ref_text_buffer->end();
m_ref_text_buffer->insert_with_tags(iter, "in bold", tags);
iter = m_ref_text_buffer->end();
m_ref_text_buffer->insert(iter, " to see its tooltip");
m_text_view.set_buffer(m_ref_text_buffer);
m_text_view.set_size_request(320, 50);
//When only connecting to the query-tooltip signal, and not using any
//of set_tooltip_text(), set_tooltip_markup() or set_tooltip_window(),
//we need to explicitly tell GTK+ that the widget has a tooltip which
//we'll show.
m_text_view.set_has_tooltip();
}
void ExampleWindow::connect_signals()
{
m_checkbutton.signal_clicked().connect(
sigc::mem_fun(*this, &ExampleWindow::on_markup_checkbutton_click));
m_text_view.signal_query_tooltip().connect(
sigc::mem_fun(*this, &ExampleWindow::on_textview_query_tooltip));
m_button.signal_query_tooltip().connect(
sigc::mem_fun(*this, &ExampleWindow::on_button_query_tooltip));
}
void ExampleWindow::on_markup_checkbutton_click()
{
if (m_checkbutton.get_active() == true)
{
m_checkbutton.set_tooltip_markup(markedup_tip);
}
else
{
m_checkbutton.set_tooltip_markup(non_markedup_tip);
}
}
bool ExampleWindow::on_textview_query_tooltip(int x, int y, bool keyboard_tooltip, const Glib::RefPtr<Gtk::Tooltip>& tooltip)
{
Gtk::TextIter iter;
if (keyboard_tooltip)
{
int offset = m_ref_text_buffer->property_cursor_position().get_value();
iter = m_ref_text_buffer->get_iter_at_offset(offset);
}
else
{
int mouse_x, mouse_y, trailing;
m_text_view.window_to_buffer_coords(Gtk::TEXT_WINDOW_TEXT,
x, y, mouse_x, mouse_y);
m_text_view.get_iter_at_position(iter, trailing, mouse_x, mouse_y);
}
//Show a tooltip if the cursor or mouse pointer is over the text
//with the specific tag:
if (iter.has_tag(m_ref_bold_tag))
{
tooltip->set_markup("<b>Information</b> attached to a text tag");
tooltip->set_icon_from_icon_name("dialog-information", Gtk::ICON_SIZE_MENU);
}
else
{
return false;
}
return true;
}
bool ExampleWindow::on_button_query_tooltip(int, int, bool, const Glib::RefPtr<Gtk::Tooltip>&)
{
//We already have a custom window ready, just return true to show it:
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-container-widgets">
<title>Widgets contenedores</title>
<para>Todos los widgets contenedores derivan de <classname>Gtk::Container</classname>, no siempre directamente. Algunos widgets contenedores, como <classname>Gtk::Grid</classname> pueden contener varios widgets hijos, por lo que típicamente tienen interfaces más complejas. Otros, como <classname>Gtk::Frame</classname> contienen sólo un widget hijo.</para>
<sect1 id="sec-single-item-containers">
<title>Contenedor de un sólo elemento</title>
<para>Los contenedores de un sólo elemento derivan de <classname>Gtk::Bin</classname>, que proporciona los métodos <methodname>add()</methodname> y <methodname>remove()</methodname> para el widget hijo. Tenga en cuenta que <classname>Gtk::Button</classname> y <classname>Gtk::Window</classname> son, técnicamente, contenedores de un sólo elemento, pero ya se ha hablado de ellos anteriormente.</para>
<para>También se habla del widget <classname>Gtk::Paned</classname>, que le permite dividir una ventana en dos «paneles» separados. El widget, en realidad, contiene dos widgets hijos, pero el número es fijo, por lo que parece apropiado.</para>
<sect2 id="sec-frame">
<title>Marco</title>
<para>Los cuadros pueden encerrar un grupo de widgets dentro de una caja, con un título opcional. Por ejemplo, tal vez quiera poner un grupo de <classname>RadioButton</classname> o <classname>CheckButton</classname> en un <classname>Frame</classname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Frame.html">Reference</ulink></para>
<sect3 id="frame-example"><title>Ejemplo</title>
<figure id="figure-frame">
<title>Marco</title>
<screenshot>
<graphic format="PNG" fileref="figures/frame.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/frame?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Child widgets:
Gtk::Frame m_Frame;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
{
/* Set some window properties */
set_title("Frame Example");
set_size_request(300, 300);
/* Sets the border width of the window. */
set_border_width(10);
add(m_Frame);
/* Set the frames label */
m_Frame.set_label("Gtk::Frame Widget");
/* Align the label at the right of the frame */
//m_Frame.set_label_align(Gtk::ALIGN_END, Gtk::ALIGN_START);
/* Set the style of the frame */
m_Frame.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-paned">
<title>Con paneles</title>
<para>Se pueden usar paneles para dividir un widget en dos mitades, separadas por un divisor móvil. Las dos mitades (paneles) pueden orientarse tanto horizontal (lado a lado) como verticalmente (uno encima de otro).</para>
<para>A diferencia de los otros widgets en esta sección, los paneles no contienen un widget hijo, sino dos, uno en cada panel. Por lo tanto, debe usar los métodos <methodname>add1()</methodname> y <methodname>add2()</methodname> en vez de <methodname>add()</methodname>.</para>
<para>Puede ajustar la posición del divisor usando el método <methodname>set_position()</methodname>, y probablemente lo necesite.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Paned.html">Reference</ulink></para>
<sect3 id="paned-example"><title>Ejemplo</title>
<figure id="figure-paned">
<title>Con paneles</title>
<screenshot>
<graphic format="PNG" fileref="figures/paned.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/paned?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include "messageslist.h"
#include "messagetext.h"
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Child widgets:
Gtk::Paned m_VPaned;
MessagesList m_MessagesList;
MessageText m_MessageText;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>messagetext.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MESSAGETEXT_H
#define GTKMM_EXAMPLE_MESSAGETEXT_H
#include <gtkmm.h>
class MessageText : public Gtk::ScrolledWindow
{
public:
MessageText();
virtual ~MessageText();
void insert_text();
protected:
Gtk::TextView m_TextView;
};
#endif //GTKMM_EXAMPLE_MESSAGETEXT_H
</programlisting>
<para lang="en">File: <filename>messageslist.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MESSAGESLIST_H
#define GTKMM_EXAMPLE_MESSAGESLIST_H
#include <gtkmm.h>
class MessagesList: public Gtk::ScrolledWindow
{
public:
MessagesList();
virtual ~MessagesList();
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_text); }
Gtk::TreeModelColumn<Glib::ustring> m_col_text;
};
ModelColumns m_Columns;
protected:
Glib::RefPtr<Gtk::ListStore> m_refListStore; //The Tree Model.
Gtk::TreeView m_TreeView; //The Tree View.
};
#endif //GTKMM_EXAMPLE_MESSAGESLIST_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VPaned(Gtk::ORIENTATION_VERTICAL)
{
set_title ("Paned Windows");
set_border_width(10);
set_default_size(450, 400);
/* Add a vpaned widget to our toplevel window */
add(m_VPaned);
/* Now add the contents of the two halves of the window */
m_VPaned.add1(m_MessagesList);
m_VPaned.add2(m_MessageText);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>messageslist.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "messageslist.h"
#include <sstream>
MessagesList::MessagesList()
{
/* Create a new scrolled window, with scrollbars only if needed */
set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
add(m_TreeView);
/* create list store */
m_refListStore = Gtk::ListStore::create(m_Columns);
m_TreeView.set_model(m_refListStore);
/* Add some messages to the window */
for(int i = 0; i < 10; ++i)
{
std::ostringstream text;
text << "message #" << i;
Gtk::TreeModel::Row row = *(m_refListStore->append());
row[m_Columns.m_col_text] = text.str();
}
//Add the Model's column to the View's columns:
m_TreeView.append_column("Messages", m_Columns.m_col_text);
show_all_children();
}
MessagesList::~MessagesList()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>messagetext.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "messagetext.h"
MessageText::MessageText()
{
set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
add(m_TextView);
insert_text();
show_all_children();
}
MessageText::~MessageText()
{
}
void MessageText::insert_text()
{
Glib::RefPtr<Gtk::TextBuffer> refTextBuffer = m_TextView.get_buffer();
Gtk::TextBuffer::iterator iter = refTextBuffer->get_iter_at_offset(0);
refTextBuffer->insert(iter,
"From: pathfinder@nasa.gov\n"
"To: mom@nasa.gov\n"
"Subject: Made it!\n"
"\n"
"We just got in this morning. The weather has been\n"
"great - clear but cold, and there are lots of fun sights.\n"
"Sojourner says hi. See you soon.\n"
" -Path\n");
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-scrolledwindow">
<title>ScrolledWindow</title>
<para>Los widgets <classname>ScrolledWindow</classname> crean un área desplazable. Puede insertar cualquier tipo de widget en una ventana <classname>ScrolledWindow</classname>, y será accesible sin importar su tamaño mediante el uso de barras de desplazamiento. Tenga en cuenta que <classname>ScrolledWindow</classname> no es un <classname>Gtk::Window</classname>, a pesar del nombre ligeramente confuso.</para>
<para>Las ventanas desplazables tienen <emphasis>políticas de desplazamiento</emphasis> que determinan si se muestran las <classname>Scrollbar</classname> o no. Las políticas se pueden establecer mediante el método <methodname>set_policy()</methodname>. La política puede ser <literal>Gtk::POLICY_AUTOMATIC</literal> o <literal>Gtk::POLICY_ALWAYS</literal>. <literal>Gtk::POLICY_AUTOMATIC</literal> hace que la ventana desplazable muestre la barra de desplazamiento sólo si el widget contenido es más grande que el área visible. <literal>Gtk::POLICY_ALWAYS</literal> hace que la barra de desplazamiento se muestre siempre.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ScrolledWindow.html">Reference</ulink></para>
<sect3 id="scrolledwindow-example"><title>Ejemplo</title>
<para>Aquí hay un ejemplo simple que incluye 100 botones conmutadores en una ventana ScrolledWindow. Intente redimensionar la ventana para ver reaccionar a las barras de desplazamiento.</para>
<figure id="figure-scrolledwindow">
<title>ScrolledWindow</title>
<screenshot>
<graphic format="PNG" fileref="figures/scrolledwindow.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/scrolledwindow?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Dialog
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_dialog_response(int response_id);
//Child widgets:
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::Grid m_Grid;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
{
set_title("Gtk::ScrolledWindow example");
set_border_width(0);
set_size_request(300, 300);
m_ScrolledWindow.set_border_width(10);
/* the policy is one of Gtk::POLICY AUTOMATIC, or Gtk::POLICY_ALWAYS.
* Gtk::POLICY_AUTOMATIC will automatically decide whether you need
* scrollbars, whereas Gtk::POLICY_ALWAYS will always leave the scrollbars
* there. The first one is the horizontal scrollbar, the second,
* the vertical. */
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);
get_content_area()->pack_start(m_ScrolledWindow);
/* set the spacing to 10 on x and 10 on y */
m_Grid.set_row_spacing(10);
m_Grid.set_column_spacing(10);
/* pack the grid into the scrolled window */
m_ScrolledWindow.add(m_Grid);
/* this simply creates a grid of toggle buttons
* to demonstrate the scrolled window. */
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
char buffer[32];
sprintf(buffer, "button (%d,%d)\n", i, j);
Gtk::Button* pButton = Gtk::manage(new Gtk::ToggleButton(buffer));
m_Grid.attach(*pButton, i, j, 1, 1);
}
}
/* Add a "close" button to the bottom of the dialog */
add_button("_Close", Gtk::RESPONSE_CLOSE);
signal_response().connect(sigc::mem_fun(*this, &ExampleWindow::on_dialog_response));
/* This makes it so the button is the default.
* Simply hitting the "Enter" key will cause this button to activate. */
set_default_response(Gtk::RESPONSE_CLOSE);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_dialog_response(int response_id)
{
switch (response_id)
{
case Gtk::RESPONSE_CLOSE:
case Gtk::RESPONSE_DELETE_EVENT:
hide();
break;
default:
std::cout << "Unexpected response_id=" << response_id << std::endl;
break;
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-aspectframe">
<title>AspectFrame</title>
<para>El widget <classname>AspectFrame</classname> se ve como un widget <classname>Frame</classname>, pero fuerza la <emphasis>relación de aspecto</emphasis> (la razón entre la altura y el ancho) del widget hijo, añadiendo espacio adicional de ser necesario. Por ejemplo, esto le permitiría mostrar una fotografía sin permitirle al usuario distorsionarla horizontal o verticalmente cuando la redimensione.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AspectFrame.html">Reference</ulink></para>
<sect3 id="aspectframe-example">
<title>Ejemplo</title>
<para>El siguiente programa usa un <classname>Gtk::AspectFrame</classname> para presentar un área de dibujo cuya relación de aspecto siempre es 2:1, sin importar cómo el usuario redimensiona la ventana superior.</para>
<figure id="figure-aspectframe">
<title>AspectFrame</title>
<screenshot>
<graphic format="PNG" fileref="figures/aspectframe.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/aspectframe?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Child widgets:
Gtk::AspectFrame m_AspectFrame;
Gtk::DrawingArea m_DrawingArea;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_AspectFrame("2x1", /* label */
Gtk::ALIGN_CENTER, /* center x */
Gtk::ALIGN_CENTER, /* center y */
2.0, /* xsize/ysize = 2 */
false /* ignore child's aspect */)
{
set_title("Aspect Frame");
set_border_width(10);
// Add a child widget to the aspect frame */
// Ask for a 200x200 window, but the AspectFrame will give us a 200x100
// window since we are forcing a 2x1 aspect ratio */
m_DrawingArea.set_size_request(200, 200);
m_AspectFrame.add(m_DrawingArea);
// Add the aspect frame to our toplevel window:
add(m_AspectFrame);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-alignment">
<title>Alignment</title>
<para>El widget <classname>Alignment</classname> le permite poner un widget en una posición y tamaño relativos al tamaño del widget <classname>Alignment</classname> en sí. Por ejemplo, puede usarse para centrar un widget.</para>
<para>Debe especificar las características del <classname>Alignment</classname> al constructor, o al método <methodname>set()</methodname>. En particular, no notará ningún efecto a menos que especifique un número distinto a 1.0 para los parámetros <literal>xscale</literal> e <literal>yscale</literal>, porque 1.0 simplemente significa que el widget se expandirá hasta cubrir todo el espacio disponible.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Alignment.html">Reference</ulink></para>
<sect3 id="alignment-example">
<title>Ejemplo</title>
<para>Este ejemplo alinea a la derecha un botón en una ventana mediante el uso de un widget <classname>Alignment</classname>.</para>
<figure id="figure-alignment">
<title>Alignment</title>
<screenshot>
<graphic format="PNG" fileref="figures/alignment.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/alignment?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_clicked();
//Child widgets:
Gtk::Alignment m_Alignment;
Gtk::Button m_Button;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_Alignment(Gtk::ALIGN_END, Gtk::ALIGN_CENTER, 0.0, 0.0),
m_Button("Close")
{
set_title("Gtk::Alignement");
set_border_width(10);
set_default_size(200, 50);
add(m_Alignment);
m_Alignment.add(m_Button);
m_Button.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_clicked) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_clicked()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
<para>Consulte la sección <link linkend="sec-progressbar">ProgressBar</link> para ver otro ejemplo que usa un <classname>Alignment</classname>.</para>
</sect3>
</sect2>
</sect1>
<sect1 id="sec-multi-item-containers">
<title>Widgets de elementos múltiples</title>
<para>Los widgets de elementos múltiples heredan de <classname>Gtk::Container</classname>; al igual que con <classname>Gtk::Bin</classname>, use los métodos <methodname>add()</methodname> y <methodname>remove()</methodname> para añadir y eliminar widgets contenedores. A diferencia de <methodname>Gtk::Bin::remove()</methodname>, sin embargo, el método <methodname>remove()</methodname> para <classname>Gtk::Container</classname> toma un argumento, especificando qué widget eliminar.</para>
<sect2 id="container-packing">
<title>Empaquetado</title>
<para>Probablemente ya haya notado que las ventanas de <application>gtkmm</application> parecen «elásticas»: normalmente pueden estirarse de muchas maneras diferentes. Esto es así por el sistema de <emphasis>empaquetado de widgets</emphasis>.</para>
<para>Muchos conjuntos de herramientas de la IGU le requieren ubicar precisamente widgets en una ventana, utilizando posicionamiento absoluto, a menudo usando un editor visual. Esto lleva a muchos problemas:</para>
<itemizedlist>
<listitem>
<para>Los widgets no se reordenar cuando la ventana se redimensiona. Algunos se esconden cuando las ventanas se hacen más pequeñas, y aparece un montón de espacio sin utilizar cuando la ventana se agranda.</para>
</listitem>
<listitem>
<para>Es imposible predecir la cantidad de espacio necesaria para texto después de que se ha traducido a otros idiomas, o se ha mostrado en otra tipografía. En Unix, también es imposible anticipar los efectos de cada tema y gestor de ventanas.</para>
</listitem>
<listitem>
<para>Cambiar la disposición de una ventana «al vuelo» para, por ejemplo, hacer que algunos widgets adicionales aparezcan, es complejo. Requiere un cálculo tedioso de la posición de cada widget.</para>
</listitem>
</itemizedlist>
<para lang="en">
<application>gtkmm</application> uses the packing system to solve these problems. Rather than specifying the position and size of each widget in the window,
you can arrange your widgets in rows, columns,
and/or grids. <application>gtkmm</application> can size your window automatically, based on the
sizes of the widgets it contains. And the sizes of the widgets are, in turn, determined by the amount of text they contain, or the minimum and maximum sizes that you specify, and/or how you have requested that the available space should be shared between sets of widgets.
You can perfect your layout by
specifying padding distance and centering values for each of your widgets. <application>gtkmm</application> then uses
all this information to resize and reposition everything sensibly and smoothly when the user manipulates the window. </para>
<para><application>gtkmm</application> ordena los widgets jerárquicamente, usando <emphasis>contenedores</emphasis>. Un widget contenedor contiene a otros widgets. La mayoría de los widgets de <application>gtkmm</application> son contenedores. Las ventanas, las pestañas de los cuadernos y los botones son todos widgets contenedores. Hay dos formas de contenedores: de un sólo hijo, que descienden todos de <classname>Gtk::Bin</classname>, y de múltiples hijos, que descienden de <classname>Gtk::Container</classname>. La mayoría de los widgets en <application>gtkmm</application> descienden de <classname>Gtk::Bin</classname>, incluyendo <classname>Gtk::Window</classname>.</para>
<para>Sí, es correcto: una ventana sólo puede contener un widget. Entonces, ¿cómo puede usar una ventana para algo útil? Poniendo un contenedor de múltiples hijos en la ventana. Los widgets contenedores más útiles son <classname>Gtk::Grid</classname> y <classname>Gtk::Box</classname>.</para>
<itemizedlist>
<listitem>
<para><classname>Gtk::Grid</classname> ordena sus widgets hijos en filas y columnas. Use <methodname>attach()</methodname>, <methodname>attach_next_to()</methodname> y <methodname>add()</methodname> para insertar widgets hijos.</para>
</listitem>
<listitem>
<para><classname>Gtk::Box</classname> ordena a sus widgets hijos vertical u horizontalmente. Use <methodname>pack_start()</methodname> y <methodname>pack_end()</methodname> para insertar widgets hijos.</para>
</listitem>
</itemizedlist>
<para>Hay muchos más contenedores, de los que también se hablará.</para>
<para>Si nunca ha usado un kit de herramientas de empaquetado antes, puede llevar algo de tiempo acostumbrarse a él. Probablemente encuentre, sin embargo, que no necesita editores de formularios visuales tanto como con otros kits de herramientas.</para>
</sect2>
<sect2 id="sec-helloworld2">
<title>Un «Hola mundo» mejorado</title>
<para>Eche un vistazo a un <literal>helloworld</literal> ligeramente mejorado, mostrando lo que ha aprendido.</para>
<figure id="figure-helloworld2">
<title>Hola mundo 2</title>
<screenshot>
<graphic format="PNG" fileref="figures/helloworld2.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/helloworld2?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>helloworld.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H
#define GTKMM_EXAMPLE_HELLOWORLD_H
#include <gtkmm/box.h>
#include <gtkmm/button.h>
#include <gtkmm/window.h>
class HelloWorld : public Gtk::Window
{
public:
HelloWorld();
virtual ~HelloWorld();
protected:
// Signal handlers:
// Our new improved on_button_clicked(). (see below)
void on_button_clicked(Glib::ustring data);
// Child widgets:
Gtk::Box m_box1;
Gtk::Button m_button1, m_button2;
};
#endif // GTKMM_EXAMPLE_HELLOWORLD_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include <gtkmm/application.h>
int main (int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
HelloWorld helloworld;
//Shows the window and returns when it is closed.
return app->run(helloworld);
}
</programlisting>
<para lang="en">File: <filename>helloworld.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include <iostream>
HelloWorld::HelloWorld()
: m_button1("Button 1"),
m_button2("Button 2")
{
// This just sets the title of our new window.
set_title("Hello Buttons!");
// sets the border width of the window.
set_border_width(10);
// put the box into the main window.
add(m_box1);
// Now when the button is clicked, we call the "on_button_clicked" function
// with a pointer to "button 1" as it's argument
m_button1.signal_clicked().connect(sigc::bind<Glib::ustring>(
sigc::mem_fun(*this, &HelloWorld::on_button_clicked), "button 1"));
// instead of gtk_container_add, we pack this button into the invisible
// box, which has been packed into the window.
// note that the pack_start default arguments are Gtk::EXPAND | Gtk::FILL, 0
m_box1.pack_start(m_button1);
// always remember this step, this tells GTK that our preparation
// for this button is complete, and it can be displayed now.
m_button1.show();
// call the same signal handler with a different argument,
// passing a pointer to "button 2" instead.
m_button2.signal_clicked().connect(sigc::bind<-1, Glib::ustring>(
sigc::mem_fun(*this, &HelloWorld::on_button_clicked), "button 2"));
m_box1.pack_start(m_button2);
// Show the widgets.
// They will not really be shown until this Window is shown.
m_button2.show();
m_box1.show();
}
HelloWorld::~HelloWorld()
{
}
// Our new improved signal handler. The data passed to this method is
// printed to stdout.
void HelloWorld::on_button_clicked(Glib::ustring data)
{
std::cout << "Hello World - " << data << " was pressed" << std::endl;
}
</programlisting>
<!-- end inserted example code -->
<para>Después de haber construido y ejecutado este programa, pruebe a redimensionar la ventana para observar su comportamiento. Además, pruebe modificar las opciones a <methodname>pack_start()</methodname> mientras lee la sección <link linkend="sec-boxes">Cajas</link>.</para>
</sect2>
<sect2 id="sec-boxes">
<title>Cajas</title>
<para>La mayor parte del empaquetado usa cajas como en el ejemplo anterior. Éstas son contenedores invisibles en los que podemos empaquetar a nuestros widgets. Cuando se empaquetan los widgets en una caja horizontal, los objetos se insertan horizontalmente de izquierda a derecha o de derecha a izquierda dependiendo de si se usó <methodname>pack_start()</methodname> o <methodname>pack_end()</methodname>. En una caja vertical, los widgets se empaquetan de arriba a abajo o viceversa. Puede usar cualquier combinación de cajas dentro o al lado de otras cajas para crear el efecto deseado.</para>
<sect3 id="boxes-adding-widgets"><title>Añadir widgets</title>
<sect4 id="per-child-packing-options"><title>Opciones de empaquetado por hijo</title>
<para>Los métodos <methodname>pack_start()</methodname> y <methodname>pack_end()</methodname> ponen widgets dentro de estos contenedores. El método <methodname>pack_start()</methodname> empezará arriba, y seguirá hacia abajo en una <classname>Box</classname> de orientación vertical, o empaquetará de izquierda a derecha en una <classname>Box</classname> de orientación horizontal. <methodname>pack_end()</methodname> hará lo contrario, empaquetando de abajo hacia arriba o de derecha a izquierda. Usar estos métodos le permite justificar a derecha o izquierda a sus widgets. Se usará <methodname>pack_start()</methodname> en la mayoría de los ejemplos.</para>
<para>Hay muchas opciones que determinan cómo se empaquetan los widgets, y esto puede resultar confuso al principio. Si tiene dificultades, entonces a veces es una buena idea jugar con el diseñador de IGU <application>glade</application> para ver qué es posible. Incluso, tal vez decida usar la API de <application>Gtk::Builder</application> para cargar su IGU en tiempo de ejecución.</para>
<para>Básicamente, hay cinco estilos diferentes, como se muestra en esta imagen.</para>
<figure id="figure-box-packing1">
<title>Caja de empaquetado 1</title>
<screenshot>
<graphic format="PNG" fileref="figures/box_packing1.png"/>
</screenshot>
</figure>
<para>Cada línea contiene una <classname>Box</classname> horizontal con varios botones. Cada uno de los botones en una línea está empaquetado en la <classname>Box</classname>, con los mismos argumentos pasados al método <methodname>pack_start()</methodname>.</para>
<para>Esta es la declaración del método <methodname>pack_start()</methodname>.</para>
<programlisting>void pack_start(Gtk::Widget& child,
Gtk::PackOptions options = Gtk::PACK_EXPAND_WIDGET,
guint padding = 0);</programlisting>
<para>El primer argumento es el widget que está empaquetando. En el ejemplo estos son todos los <classname>Button</classname>.</para>
<para lang="en">
The <parameter>options</parameter> argument can take one of these three options:
<itemizedlist>
<listitem><para lang="en"><literal>Gtk::PACK_SHRINK</literal>: Space is contracted to the child widget size. The widget will take up just-enough space and never expand.</para></listitem>
<listitem><para lang="en"><literal>Gtk::PACK_EXPAND_PADDING</literal>: Extra space is filled with padding. The widgets will be spaced out evenly, but their sizes won't change - there will be empty space between the widgets instead. </para></listitem>
<listitem><para lang="en"><literal>Gtk::PACK_EXPAND_WIDGET</literal>: Extra space is taken up by increasing the child widget size, without changing the amount of space between widgets.</para></listitem>
</itemizedlist>
</para>
<para>El argumento <parameter>padding</parameter> especifica el ancho de un área adicional en el borde para dejar alrededor del widget empaquetado.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Box.html">Reference</ulink></para>
</sect4>
<sect4 id="per-container-packing-options"><title>Opciones de empaquetado por contenedor</title>
<para lang="en">
Here's the constructor for the <classname>Box</classname> widget,
and methods that set per-container packing options:
<programlisting lang="en">Gtk::Box(Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL, int spacing = 0);
void set_spacing(int spacing);
void set_homogeneous(bool homogeneous = true);</programlisting>
Passing <literal>true</literal> to <methodname>set_homogeneous()</methodname> will
cause all of the contained widgets to be the same size.
<parameter>spacing</parameter> is a (minimum) number of pixels to leave between
each widget.
</para>
<para>¿Cuál es la diferencia entre el espaciado (establecido cuando se crea la caja) y el relleno (establecido cuando se empaquetan los elementos)? El espaciado se añade entre objetos, y el relleno a cada lado del widget. La siguiente figura debería aclararlo:</para>
<figure id="figure-box-packing2">
<title>Caja de empaquetado 2</title>
<screenshot>
<graphic format="PNG" fileref="figures/box_packing2.png"/>
</screenshot>
</figure>
</sect4>
</sect3>
<sect3 id="boxes-command-line-options">
<title>Gtk::Application y opciones de línea de comandos</title>
<para>El siguiente programa de ejemplo requiere una opción de línea de comandos. El código fuente muestra dos maneras de manejarla, en combinación con <classname>Gtk::Application</classname>.</para>
<itemizedlist>
<listitem><para>Maneje las opciones en <function>main()</function> y ocúltelas de <classname>Gtk::Application</classname> estableciendo <literal>argc = 1</literal> en la llamada a <methodname>Gtk::Application::create()</methodname>.</para></listitem>
<listitem><para>Pásele todas las opciones de línea de comandos a <methodname>Gtk::Application::create()</methodname> y añada la opción <literal>Gio::APPLICATION_HANDLES_COMMAND_LINE</literal>. Conecte un manejador de señales a la señal <literal>command_line</literal>, y maneje las opciones de línea de comandos en él.</para>
<para>Debe establecer el parámetro opcional <literal>after = false</literal> en la llamada a <literal>signal_command_line().connect()</literal>, porque su manejador de señales debe llamarse antes que el manejador predeterminado. También debe llamar a <methodname>Gio::Application::activate()</methodname> en este, a menos que quiere que su aplicación se cierre sin mostrar su ventana principal. (<classname>Gio::Application</classname> es una clase base de <classname>Gtk::Application</classname>).</para></listitem>
</itemizedlist>
</sect3>
<sect3 id="box-packing-example">
<title>Ejemplo</title>
<para>Aquí está el código fuente del ejemplo que produjo las capturas de pantalla anteriores. Cuando ejecute este ejemplo, proporcione un número entre 1 y 3 como opción de línea de comandos, para ver las diferentes opciones de empaquetado en acción.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/box?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow(int which);
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit_clicked();
//Child widgets:
Gtk::Button m_button;
Gtk::Box m_box1;
Gtk::Box m_boxQuit;
Gtk::Button m_buttonQuit;
Gtk::Label m_Label1, m_Label2;
Gtk::Separator m_separator1, m_separator2;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>packbox.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_PACKBOX_H
#define GTKMM_EXAMPLE_PACKBOX_H
#include <gtkmm.h>
class PackBox : public Gtk::Box
{
public:
PackBox(bool homogeneous, int spacing, Gtk::PackOptions options, int padding = 0);
virtual ~PackBox();
protected:
Gtk::Button m_button1, m_button2, m_button3;
Gtk::Button* m_pbutton4;
};
#endif //GTKMM_EXAMPLE_PACKBOX_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
#include "packbox.h"
ExampleWindow::ExampleWindow(int which)
: m_box1(Gtk::ORIENTATION_VERTICAL),
m_buttonQuit("Quit")
{
set_title("Gtk::Box example");
PackBox *pPackBox1, *pPackBox2, *pPackBox3, *pPackBox4, *pPackBox5;
switch(which)
{
case 1:
{
m_Label1.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); set_homogeneous(false);");
// Align the label to the left side. We'll discuss this function and
// others in the section on Widget Attributes.
m_Label1.set_alignment(Gtk::ALIGN_START, Gtk::ALIGN_START);
// Pack the label into the vertical box (vbox box1). Remember that
// widgets added to a vbox will be packed one on top of the other in
// order.
m_box1.pack_start(m_Label1, Gtk::PACK_SHRINK);
// Create a PackBox - homogeneous = false, spacing = 0,
// options = Gtk::PACK_SHRINK, padding = 0
pPackBox1 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_SHRINK));
m_box1.pack_start(*pPackBox1, Gtk::PACK_SHRINK);
// Create a PackBox - homogeneous = false, spacing = 0,
// options = Gtk::PACK_EXPAND_PADDING, padding = 0
pPackBox2 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_EXPAND_PADDING));
m_box1.pack_start(*pPackBox2, Gtk::PACK_SHRINK);
// Create a PackBox - homogeneous = false, spacing = 0,
// options = Gtk::PACK_EXPAND_WIDGET, padding = 0
pPackBox3 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_EXPAND_WIDGET));
m_box1.pack_start(*pPackBox3, Gtk::PACK_SHRINK);
// pack the separator into the vbox. Remember each of these
// widgets are being packed into a vbox, so they'll be stacked
// vertically.
m_box1.pack_start(m_separator1, Gtk::PACK_SHRINK, 5);
// create another new label, and show it.
m_Label2.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); set_homogeneous(true);");
m_Label2.set_alignment(Gtk::ALIGN_START, Gtk::ALIGN_START);
m_box1.pack_start(m_Label2, Gtk::PACK_SHRINK);
// Args are: homogeneous, spacing, options, padding
pPackBox4 = Gtk::manage(new PackBox(true, 0, Gtk::PACK_EXPAND_PADDING));
m_box1.pack_start(*pPackBox4, Gtk::PACK_SHRINK);
// Args are: homogeneous, spacing, options, padding
pPackBox5 = Gtk::manage(new PackBox(true, 0, Gtk::PACK_EXPAND_WIDGET));
m_box1.pack_start(*pPackBox5, Gtk::PACK_SHRINK);
m_box1.pack_start(m_separator2, Gtk::PACK_SHRINK, 5);
break;
}
case 2:
{
m_Label1.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 10); set_homogeneous(false);");
m_Label1.set_alignment(Gtk::ALIGN_START, Gtk::ALIGN_START);
m_box1.pack_start(m_Label1, Gtk::PACK_SHRINK);
pPackBox1 = Gtk::manage(new PackBox(false, 10, Gtk::PACK_EXPAND_PADDING));
m_box1.pack_start(*pPackBox1, Gtk::PACK_SHRINK);
pPackBox2 = Gtk::manage(new PackBox(false, 10, Gtk::PACK_EXPAND_WIDGET));
m_box1.pack_start(*pPackBox2, Gtk::PACK_SHRINK);
m_box1.pack_start(m_separator1, Gtk::PACK_SHRINK, 5);
m_Label2.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); set_homogeneous(false);");
m_Label2.set_alignment(Gtk::ALIGN_START, Gtk::ALIGN_START);
m_box1.pack_start(m_Label2, Gtk::PACK_SHRINK);
pPackBox3 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_SHRINK, 10));
m_box1.pack_start(*pPackBox3, Gtk::PACK_SHRINK);
pPackBox4 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_EXPAND_WIDGET, 10));
m_box1.pack_start(*pPackBox4, Gtk::PACK_SHRINK);
m_box1.pack_start(m_separator2, Gtk::PACK_SHRINK, 5);
break;
}
case 3:
{
// This demonstrates the ability to use Gtk::Box::pack_end() to
// right justify widgets. First, we create a new box as before.
pPackBox1 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_SHRINK));
// create the label that will be put at the end.
m_Label1.set_text("end");
// pack it using pack_end(), so it is put on the right side
// of the PackBox.
pPackBox1->pack_end(m_Label1, Gtk::PACK_SHRINK);
m_box1.pack_start(*pPackBox1, Gtk::PACK_SHRINK);
// this explicitly sets the separator to 500 pixels wide by 5 pixels
// high. This is so the hbox we created will also be 500 pixels wide,
// and the "end" label will be separated from the other labels in the
// hbox. Otherwise, all the widgets in the hbox would be packed as
// close together as possible.
m_separator1.set_size_request(500, 5);
// pack the separator into the vbox.
m_box1.pack_start(m_separator1, Gtk::PACK_SHRINK, 5);
break;
}
default:
{
std::cerr << "Unexpected command-line option." << std::endl;
break;
}
}
// Connect the signal to hide the window:
m_buttonQuit.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_quit_clicked) );
// pack the button into the quitbox.
// The last 2 arguments to Box::pack_start are: options, padding.
m_boxQuit.pack_start(m_buttonQuit, Gtk::PACK_EXPAND_PADDING);
m_box1.pack_start(m_boxQuit, Gtk::PACK_SHRINK);
// pack the vbox (box1) which now contains all our widgets, into the
// main window.
add(m_box1);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit_clicked()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>packbox.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "packbox.h"
PackBox::PackBox(bool homogeneous, int spacing, Gtk::PackOptions options,
int padding)
: Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, spacing),
m_button1("box.pack_start("),
m_button2("button,"),
m_button3((options == Gtk::PACK_SHRINK) ? "Gtk::PACK_SHRINK" :
((options == Gtk::PACK_EXPAND_PADDING) ?
"Gtk::PACK_EXPAND_PADDING" : "Gtk::PACK_EXPAND_WIDGET"))
{
set_homogeneous(homogeneous);
pack_start(m_button1, options, padding);
pack_start(m_button2, options, padding);
pack_start(m_button3, options, padding);
m_pbutton4 = new Gtk::Button(Glib::ustring::format(padding) + ");");
pack_start(*m_pbutton4, options, padding);
}
PackBox::~PackBox()
{
delete m_pbutton4;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
#include <iostream>
#include <cstdlib>
#define GTK_APPLICATION_RECEIVES_COMMAND_LINE_ARGUMENTS 0
#if GTK_APPLICATION_RECEIVES_COMMAND_LINE_ARGUMENTS
namespace
{
int on_command_line(const Glib::RefPtr<Gio::ApplicationCommandLine>& command_line,
Glib::RefPtr<Gtk::Application>& app)
{
int argc = 0;
char** argv = command_line->get_arguments(argc);
for (int i = 0; i < argc; ++i)
std::cout << "argv[" << i << "] = " << argv[i] << std::endl;
app->activate(); // Without activate() the window won't be shown.
return EXIT_SUCCESS;
}
} // anonymous namespace
#endif
int main(int argc, char *argv[])
{
if (argc != 2)
{
std::cerr << "Usage: example <num>, where <num> is 1, 2, or 3." << std::endl;
return EXIT_FAILURE;
}
#if GTK_APPLICATION_RECEIVES_COMMAND_LINE_ARGUMENTS
// The command line arguments must be checked before Gtk::Application::run()
// is called. The Gio::APPLICATION_HANDLES_COMMAND_LINE flag and the
// on_command_line() signal handler are not necessary. This program is simpler
// without them, and with argc = 1 in the call to Gtk::Application::create().
// They are included to show a program with Gio::APPLICATION_HANDLES_COMMAND_LINE.
// Gio::APPLICATION_NON_UNIQUE makes it possible to run several instances of
// this application simultaneously.
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv,
"org.gtkmm.example", Gio::APPLICATION_HANDLES_COMMAND_LINE | Gio::APPLICATION_NON_UNIQUE);
// Note after = false.
// Only one signal handler is invoked. This signal handler must run before
// the default signal handler, or else it won't run at all.
app->signal_command_line().connect(sigc::bind(sigc::ptr_fun(&on_command_line), app), false);
#else
// Gio::APPLICATION_NON_UNIQUE makes it possible to run several instances of
// this application simultaneously.
int argc1 = 1; // Don't give the command line arguments to Gtk::Application.
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc1, argv,
"org.gtkmm.example", Gio::APPLICATION_NON_UNIQUE);
#endif
ExampleWindow window(std::atoi(argv[1]));
return app->run(window); //Shows the window and returns when it is closed.
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-buttonbox">
<title>Cajas de Botones</title>
<para>Las cajas de botones son una manera conveniente de ordenar rápidamente un grupo de botones. Su orientación puede ser tanto horizontal como vertical.</para>
<para>Las <classname>ButtonBox</classname> ayudan a hacer que las aplicaciones aparezcan consistentes porque usan opciones estándar, como espaciado entre botones y empaquetado.</para>
<para>Los botones se añaden a una <classname>ButtonBox</classname> con el método <methodname>add()</methodname>.</para>
<para>Las cajas de botones soportan varios estilos de disposición. Puede obtener y modificar el estilo usando <methodname>get_layout()</methodname> y <methodname>set_layout()</methodname>. </para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ButtonBox.html">Reference</ulink></para>
<sect3 id="buttonbox-example">
<title>Ejemplo</title>
<figure id="figure-buttonbox">
<title>ButtonBox</title>
<screenshot>
<graphic format="PNG" fileref="figures/buttonbox.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttonbox?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_clicked();
//Child widgets:
Gtk::Box m_VBox_Main, m_VBox;
Gtk::Box m_HBox;
Gtk::Frame m_Frame_Horizontal, m_Frame_Vertical;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplebuttonbox.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_BUTTONBOX_H
#define GTKMM_EXAMPLE_BUTTONBOX_H
#include <gtkmm.h>
class ExampleButtonBox : public Gtk::Frame
{
public:
ExampleButtonBox(bool horizontal,
const Glib::ustring& title,
gint spacing,
Gtk::ButtonBoxStyle layout);
protected:
Gtk::Button m_Button_OK, m_Button_Cancel, m_Button_Help;
};
#endif //GTKMM_EXAMPLE_BUTTONBOX_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include "examplebuttonbox.h"
ExampleWindow::ExampleWindow()
: m_VBox_Main(Gtk::ORIENTATION_VERTICAL),
m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Frame_Horizontal("Horizontal Button Boxes"),
m_Frame_Vertical("Vertical Button Boxes")
{
set_title("Gtk::ButtonBox");
add(m_VBox_Main);
m_VBox_Main.pack_start(m_Frame_Horizontal, Gtk::PACK_EXPAND_WIDGET, 10);
//The horizontal ButtonBoxes:
m_VBox.set_border_width(10);
m_Frame_Horizontal.add(m_VBox);
m_VBox.pack_start(*Gtk::manage(
new ExampleButtonBox(true, "Spread (spacing 40)", 40,
Gtk::BUTTONBOX_SPREAD)),
Gtk::PACK_EXPAND_WIDGET);
m_VBox.pack_start(*Gtk::manage(
new ExampleButtonBox(true, "Edge (spacing 30)", 30,
Gtk::BUTTONBOX_EDGE)),
Gtk::PACK_EXPAND_WIDGET, 5);
m_VBox.pack_start(*Gtk::manage(
new ExampleButtonBox(true, "Start (spacing 20)", 20,
Gtk::BUTTONBOX_START)),
Gtk::PACK_EXPAND_WIDGET, 5);
m_VBox.pack_start(*Gtk::manage(
new ExampleButtonBox(true, "end (spacing 10)", 10,
Gtk::BUTTONBOX_END)),
Gtk::PACK_EXPAND_WIDGET, 5);
//The vertical ButtonBoxes:
m_VBox_Main.pack_start(m_Frame_Vertical, Gtk::PACK_EXPAND_WIDGET, 10);
m_HBox.set_border_width(10);
m_Frame_Vertical.add(m_HBox);
m_HBox.pack_start(*Gtk::manage(
new ExampleButtonBox(false, "Spread (spacing 5)", 5,
Gtk::BUTTONBOX_SPREAD)),
Gtk::PACK_EXPAND_WIDGET);
m_HBox.pack_start(*Gtk::manage(
new ExampleButtonBox(false, "Edge (spacing 30)", 30,
Gtk::BUTTONBOX_EDGE)),
Gtk::PACK_EXPAND_WIDGET, 5);
m_HBox.pack_start(*Gtk::manage(
new ExampleButtonBox(false, "Start (spacing 20)", 20,
Gtk::BUTTONBOX_START)),
Gtk::PACK_EXPAND_WIDGET, 5);
m_HBox.pack_start(*Gtk::manage(new ExampleButtonBox(false, "End (spacing 10)",
10, Gtk::BUTTONBOX_END)),
Gtk::PACK_EXPAND_WIDGET, 5);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_clicked()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>examplebuttonbox.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplebuttonbox.h"
ExampleButtonBox::ExampleButtonBox(bool horizontal,
const Glib::ustring& title,
gint spacing,
Gtk::ButtonBoxStyle layout)
: Gtk::Frame(title),
m_Button_OK("OK"),
m_Button_Cancel("Cancel"),
m_Button_Help("Help")
{
Gtk::ButtonBox* bbox = 0;
if(horizontal)
bbox = Gtk::manage( new Gtk::ButtonBox(Gtk::ORIENTATION_HORIZONTAL) );
else
bbox = Gtk::manage( new Gtk::ButtonBox(Gtk::ORIENTATION_VERTICAL) );
bbox->set_border_width(5);
add(*bbox);
/* Set the appearance of the Button Box */
bbox->set_layout(layout);
bbox->set_spacing(spacing);
bbox->add(m_Button_OK);
bbox->add(m_Button_Cancel);
bbox->add(m_Button_Help);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-grid">
<title>Grid</title>
<para>Un <classname>Grid</classname> establece dinámicamente widgets hijos en filas y columnas. No es necesario especificar las dimensiones de la red en el constructor.</para>
<para>Los widgets hijos pueden abarcar múltiples filas o columnas, usando <methodname>attach()</methodname>, o añadirse a un widget existente dentro de la cuadrícula con <methodname>attach_next_to()</methodname>. Se puede establecer que las filas o columnas individuales de la cuadrícula tengan una altura o ancho uniforme con <methodname>set_row_homogeneous()</methodname> y <methodname>set_column_homogeneous()</methodname>.</para>
<para>Puede establecer las propiedades <emphasis>margin</emphasis> y <emphasis>expand</emphasis> de los <classname>Widget</classname> hijos para controlar su espaciado y comportamiento cuando se redimensiona la cuadrícula.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Grid.html">Reference</ulink></para>
<sect3 id="grid-example"><title>Ejemplo</title>
<para>Este ejemplo crea una ventana con tres botones en una cuadrícula. Los dos primeros botones están en la fila superior, de izquierda a derecha. Se ha añadido un tercer botón bajo el primer botón, en una nueva fila más abajo, abarcando dos columnas.</para>
<figure id="figure-grid">
<title>Grid</title>
<screenshot>
<graphic format="PNG" fileref="figures/grid.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/grid?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
private:
// Signal handlers:
void on_button_quit();
void on_button_numbered(const Glib::ustring& data);
// Child widgets:
Gtk::Grid m_grid;
Gtk::Button m_button_1, m_button_2, m_button_quit;
};
#endif /* GTKMM_EXAMPLEWINDOW_H */
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_button_1("button 1"),
m_button_2("button 2"),
m_button_quit("Quit")
{
set_title("Gtk::Grid");
set_border_width(12);
add(m_grid);
m_grid.add(m_button_1);
m_grid.add(m_button_2);
m_grid.attach_next_to(m_button_quit, m_button_1, Gtk::POS_BOTTOM, 2, 1);
m_button_1.signal_clicked().connect(
sigc::bind<Glib::ustring>( sigc::mem_fun(*this,
&ExampleWindow::on_button_numbered), "button 1") );
m_button_2.signal_clicked().connect(
sigc::bind<Glib::ustring>( sigc::mem_fun(*this,
&ExampleWindow::on_button_numbered), "button 2") );
m_button_quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
void
ExampleWindow::on_button_numbered(const Glib::ustring& data)
{
std::cout << data << " was pressed" << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
// Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-table">
<title>Tabla</title>
<para><classname>Gtk::Table</classname> permite poner widgets en una cuadrícula, de manera similar a <classname>Gtk::Grid</classname>.</para>
<para><classname>Gtk::Table</classname> se marcó como obsoleto en <application>gtkmm</application> 3.4 y no se debe usar en el código nuevo. Use <classname>Gtk::Grid</classname> en su lugar.</para>
</sect2>
<sect2 id="sec-notebook">
<title>Cuaderno</title>
<para>Un <classname>Notebook</classname> tiene un conjunto de <literal>páginas</literal> apiladas, cada una de ellas contiene widgets. Las <literal>pestañas</literal> etiquetadas permiten al usuario seleccionar las páginas. Los <classname>Notebook</classname> permiten colocar varios conjuntos de widgets en un espacio reducido, mostrando sólo una página a la vez. Por ejemplo, se utilizan a menudo en los diálogos de preferencias.</para>
<para>Use los métodos <methodname>append_page()</methodname>, <methodname>prepend_page()</methodname> e <methodname>insert_page()</methodname> para añadir páginas con pestañas al <literal>Notebook</literal>, proporcionándoles el widget hijo y el nombre de la pestaña.</para>
<para>Para descubrir la página visible actual, use el método <methodname>get_current_page()</methodname>. Esto devuelve el número de página. Después llame a <methodname>get_nth_page()</methodname> con ese número le dará un puntero al widget hijo en sí.</para>
<para>Para cambiar la página seleccionada mediante programación, use el método <methodname>set_current_page()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Notebook.html">Reference</ulink></para>
<sect3 id="notebook-example"><title>Ejemplo</title>
<figure id="figure-notebook">
<title>Cuaderno</title>
<screenshot>
<graphic format="PNG" fileref="figures/notebook.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/notebook/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
void on_notebook_switch_page(Gtk::Widget* page, guint page_num);
//Child widgets:
Gtk::Box m_VBox;
Gtk::Notebook m_Notebook;
Gtk::Label m_Label1, m_Label2;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Label1("Contents of tab 1"),
m_Label2("Contents of tab 2"),
m_Button_Quit("Quit")
{
set_title("Gtk::Notebook example");
set_border_width(10);
set_default_size(400, 200);
add(m_VBox);
//Add the Notebook, with the button underneath:
m_Notebook.set_border_width(10);
m_VBox.pack_start(m_Notebook);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
//Add the Notebook pages:
m_Notebook.append_page(m_Label1, "First");
m_Notebook.append_page(m_Label2, "Second");
m_Notebook.signal_switch_page().connect(sigc::mem_fun(*this,
&ExampleWindow::on_notebook_switch_page) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
void ExampleWindow::on_notebook_switch_page(Gtk::Widget* /* page */, guint page_num)
{
std::cout << "Switched to tab with index " << page_num << std::endl;
//You can also use m_Notebook.get_current_page() to get this index.
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
<sect2 id="sec-assistant">
<title>Asistente</title>
<para>Un <classname>Assistant</classname> divide una operación compleja en pasos. Cada paso es una página, conteniendo una cabecera, un widget hijo, y un área de acción. El área de acción del asistente tiene botones de navegación que se actualizan automáticamente dependiendo del tipo de la página, establecido con <methodname>set_page_type()</methodname>.</para>
<para>Use los métodos <methodname>append_page()</methodname>, <methodname>prepend_page</methodname> e <methodname>insert_page()</methodname> para añadirle páginas al <classname>Assistant</classname>, proporcionándole el widget hijo por cada página.</para>
<para>Para determinar la página actualmente visible, use el método <methodname>get_current_page()</methodname> y pásele el resultado a <methodname>get_nth_page()</methodname>, que le devuelve un puntero al widget en sí. Para cambiar mediante programación la página actual, use el método <methodname>set_current_page()</methodname>.</para>
<para>Para establecer el título de una página, use el método <methodname>set_page_title()</methodname>. Las imágenes de cabecera y de lado de una página se pueden establecer con los métodos <methodname>set_page_header_image()</methodname> y <methodname>set_page_side_image()</methodname>.</para>
<para>Para añadir widgets al área de acción, use el método <methodname>add_action_widget()</methodname>. Serán empaquetados junto a los botones predeterminados. Use el método <methodname>remove_action_widget()</methodname> para borrar los widgets.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Assistant.html">Reference</ulink></para>
<sect3 id="assistant-example"><title>Ejemplo</title>
<figure id="figure-assistant">
<title>Asistente</title>
<screenshot>
<graphic format="PNG" fileref="figures/assistant.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/assistant/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include "exampleassistant.h"
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
private:
// Signal handlers:
void on_button_clicked();
void on_assistant_apply();
// Child widgets:
Gtk::Grid m_grid;
Gtk::Button m_button;
Gtk::Label m_label1, m_label2;
Gtk::CheckButton m_check;
Gtk::Entry m_entry;
ExampleAssistant m_assistant;
};
#endif /* GTKMM_EXAMPLEWINDOW_H */
</programlisting>
<para lang="en">File: <filename>exampleassistant.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEASSISTANT_H
#define GTKMM_EXAMPLEASSISTANT_H
#include <gtkmm.h>
class ExampleAssistant : public Gtk::Assistant
{
public:
ExampleAssistant();
virtual ~ExampleAssistant();
void get_result(bool& check_state, Glib::ustring& entry_text);
private:
// Signal handlers:
void on_assistant_apply();
void on_assistant_cancel();
void on_assistant_close();
void on_assistant_prepare(Gtk::Widget* widget);
void on_entry_changed();
// Member functions:
void print_status();
// Child widgets:
Gtk::Box m_box;
Gtk::Label m_label1, m_label2;
Gtk::CheckButton m_check;
Gtk::Entry m_entry;
};
#endif /* GTKMM_EXAMPLEASSISTANT_H */
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include "exampleassistant.h"
ExampleWindow::ExampleWindow()
: m_button("Show the assistant"),
m_label1("State of assistant checkbutton:"),
m_label2("Contents of assistant entry:")
{
set_title("Gtk::Assistant example");
set_border_width(12);
m_grid.set_row_homogeneous(true);
m_grid.attach(m_button, 0, 0, 2, 1);
m_button.set_hexpand(true);
m_button.set_valign(Gtk::ALIGN_CENTER);
m_grid.attach(m_label1, 0, 1, 1, 1);
m_label1.set_alignment(0.0, 0.5);
m_grid.attach(m_label2, 0, 2, 1, 1);
m_label2.set_alignment(0.0, 0.5);
m_grid.attach(m_check, 1, 1, 1, 1);
m_check.set_halign(Gtk::ALIGN_START);
m_grid.attach(m_entry, 1, 2, 1, 1);
m_entry.set_hexpand(true);
add(m_grid);
m_button.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_clicked));
m_assistant.signal_apply().connect(sigc::mem_fun(*this,
&ExampleWindow::on_assistant_apply));
m_check.set_sensitive(false);
m_entry.set_sensitive(false);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_assistant_apply()
{
bool check_state;
Glib::ustring entry_text;
m_assistant.get_result(check_state, entry_text);
m_check.set_active(check_state);
m_entry.set_text(entry_text);
}
void ExampleWindow::on_button_clicked()
{
m_assistant.show();
}
</programlisting>
<para lang="en">File: <filename>exampleassistant.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "exampleassistant.h"
ExampleAssistant::ExampleAssistant()
: m_box(Gtk::ORIENTATION_HORIZONTAL, 12),
m_label1("Type text to allow the assistant to continue:"),
m_label2("Confirmation page"),
m_check("Optional extra information")
{
set_title("Gtk::Assistant example");
set_border_width(12);
set_default_size(400, 300);
m_box.pack_start(m_label1);
m_box.pack_start(m_entry);
append_page(m_box);
append_page(m_check);
append_page(m_label2);
set_page_title(*get_nth_page(0), "Page 1");
set_page_title(*get_nth_page(1), "Page 2");
set_page_title(*get_nth_page(2), "Confirmation");
set_page_complete(m_check, true);
set_page_complete(m_label2, true);
set_page_type(m_box, Gtk::ASSISTANT_PAGE_INTRO);
set_page_type(m_label2, Gtk::ASSISTANT_PAGE_CONFIRM);
signal_apply().connect(sigc::mem_fun(*this,
&ExampleAssistant::on_assistant_apply));
signal_cancel().connect(sigc::mem_fun(*this,
&ExampleAssistant::on_assistant_cancel));
signal_close().connect(sigc::mem_fun(*this,
&ExampleAssistant::on_assistant_close));
signal_prepare().connect(sigc::mem_fun(*this,
&ExampleAssistant::on_assistant_prepare));
m_entry.signal_changed().connect(sigc::mem_fun(*this,
&ExampleAssistant::on_entry_changed));
show_all_children();
}
ExampleAssistant::~ExampleAssistant()
{
}
void ExampleAssistant::get_result(bool& check_state, Glib::ustring& entry_text)
{
check_state = m_check.get_active();
entry_text = m_entry.get_text();
}
void ExampleAssistant::on_assistant_apply()
{
std::cout << "Apply was clicked";
print_status();
}
void ExampleAssistant::on_assistant_cancel()
{
std::cout << "Cancel was clicked";
print_status();
hide();
}
void ExampleAssistant::on_assistant_close()
{
std::cout << "Assistant was closed";
print_status();
hide();
}
void ExampleAssistant::on_assistant_prepare(Gtk::Widget* /* widget */)
{
set_title(Glib::ustring::compose("Gtk::Assistant example (Page %1 of %2)",
get_current_page() + 1, get_n_pages()));
}
void ExampleAssistant::on_entry_changed()
{
// The page is only complete if the entry contains text.
if(m_entry.get_text_length())
set_page_complete(m_box, true);
else
set_page_complete(m_box, false);
}
void ExampleAssistant::print_status()
{
std::cout << ", entry contents: \"" << m_entry.get_text()
<< "\", checkbutton status: " << m_check.get_active() << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
// Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>
</sect2>
</sect1>
</chapter>
<chapter id="chapter-treeview">
<title>El widget TreeView</title>
<para>El widget <classname>Gtk::TreeView</classname> puede contener listas o árboles de datos, en columnas.</para>
<sect1 id="sec-treeview-model">
<title>El modelo</title>
<para>Cada <classname>Gtk::TreeView</classname> tiene un <classname>Gtk::Model</classname> asociado que contiene los datos mostrados por el <classname>TreeView</classname> Varios <classname>Gtk::TreeView</classname> puede usar el mismo <classname>Gtk::TreeModel</classname>. Por ejemplo, esto le permite mostrar y editar los mismos datos de 2 formas diferentes al mismo tiempo. O las 2 vistas pueden mostrar diferentes columnas de los mismos modelos de datos, de la misma manera que dos consultas SQL (o «vistas») pueden mostrar diferentes campos de la misma tabla de la base de datos.</para>
<para>A pesar de que, teóricamente, puede implementar su propio modelo, normalmente usará las clases de los modelos <classname>ListStore</classname> o <classname>TreeStore</classname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeModel.html">Reference</ulink></para>
<sect2 id="treeview-model-liststore">
<title>ListStore, para filas</title>
<para>El <classname>ListStore</classname> contiene filas simples de datos, y ninguna fila tiene hijos.</para>
<figure id="figure-treeview-liststore-model">
<title>TreeView - ListStore</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_list.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ListStore.html">Reference</ulink></para>
</sect2>
<sect2 id="treeview-model-treestore">
<title>TreeStore, para una jerarquía</title>
<para>El <classname>TreeStore</classname> contiene filas de datos, y cada fila puede tener filas hijas.</para>
<figure id="figure-treeview-treestore-model">
<title>TreeView - TreeStore</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_tree.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeStore.html">Reference</ulink></para>
</sect2>
<sect2 id="treeview-model-columns">
<title>Columnas del modelo</title>
<para>La clase <classname>TreeModelColumnRecord</classname> se usa para rastrear a las columnas y sus tipos de datos. Añádale instancias <classname>TreeModelColumn</classname> al <classname>ColumnRecord</classname> y luego use esas <classname>TreeModelColumn</classname> cuando establezca u obtenga los datos en las filas del modelo. Probablemente encuentre conveniente derivar un <classname>TreeModelColumnRecord</classname> que tenga a sus instancias <classname>TreeModelColumn</classname> como datos miembro.</para>
<programlisting>class ModelColumns : public Gtk::TreeModelColumnRecord
{
public:
ModelColumns()
{ add(m_col_text); add(m_col_number); }
Gtk::TreeModelColumn<Glib::ustring> m_col_text;
Gtk::TreeModelColumn<int> m_col_number;
};
ModelColumns m_Columns;</programlisting>
<para>Especifique el <classname>ColumnRecord</classname> cuando cree el modelo, así:</para>
<programlisting>Glib::RefPtr<Gtk::ListStore> refListStore =
Gtk::ListStore::create(m_Columns);</programlisting>
<para>Tenga en cuenta que la instancia (como m_Columns aquí) normalmente no debe ser estática, porque a menudo se necesita instanciarla después de haber instanciado a glibmm.</para>
</sect2>
<sect2 id="treeview-adding-rows">
<title>Añadir filas</title>
<para>Añadir filas al modelo con los métodos <methodname>append()</methodname>, <methodname>prepend()</methodname>, o <methodname>insert()</methodname>.</para>
<programlisting>Gtk::TreeModel::iterator iter = m_refListStore->append();</programlisting>
<para>Puede desreferenciar al iterador para obtener la fila:</para>
<programlisting>Gtk::TreeModel::Row row = *iter;</programlisting>
<sect3 id="treeview-adding-child-rows"><title>Añadiendo filas secundarias</title>
<para>Los modelos <classname>Gtk::TreeStore</classname> pueden tener elementos hijos. Añádalos con los métodos <methodname>append()</methodname>, <methodname>prepend()</methodname>, o <methodname>insert()</methodname>, así:</para>
<programlisting>Gtk::TreeModel::iterator iter_child =
m_refTreeStore->append(row.children());</programlisting>
</sect3>
</sect2>
<sect2 id="treeview-setting-values">
<title>Configurar los valores</title>
<para>Puede usar la sobrecarga de <methodname>operator[]</methodname> para establecer los datos de una columna particular en la fila, especificando la <classname>TreeModelColumn</classname> que se usó para crear el modelo.</para>
<programlisting>row[m_Columns.m_col_text] = "sometext";</programlisting>
</sect2>
<sect2 id="treeview-getting-values">
<title>Obtener los valores</title>
<para>Puede usar la sobrecarga <methodname>operator[]</methodname> para obtener los datos de una columna particular en una fila, especificando la <classname>TreeModelColumn</classname> que se usó para crear el modelo.</para>
<programlisting>Glib::ustring strText = row[m_Columns.m_col_text];
int number = row[m_Columns.m_col_number];</programlisting>
<para>El compilador le hará saber si usa un tipo inapropiado. Por ejemplo, esto generaría un error de compilación:</para>
<programlisting>//compiler error - no conversion from ustring to int.
int number = row[m_Columns.m_col_text];</programlisting>
</sect2>
<sect2 id="treeview-hidden-columns">
<title>Columnas «ocultas»</title>
<para>Puede querer asociar datos adicionales a cada fila. Si es así, sólo añádalos como una columa del modelo, pero no se los añada a la vista.</para>
</sect2>
</sect1>
<sect1 id="sec-treeview">
<title>La vista</title>
<para>La vista es el widget en sí (<classname>Gtk::TreeView</classname>) que muestra los datos del modelo (<classname>Gtk::TreeModel</classname>) y le permite al usuario interactuar con él. La vista puede mostrar todas las columnas del modelo, o sólo algunas, y puede mostrarlas de varias maneras.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeView.html">Reference</ulink></para>
<sect2 id="sec-treeview-using-a-model">
<title>Usar un modelo</title>
<para>Puede especificar un <classname>Gtk::TreeModel</classname> cuando construye la <classname>Gtk::TreeView</classname>, o puede usar el método <methodname>set_model()</methodname>, así:</para>
<programlisting>m_TreeView.set_model(m_refListStore);</programlisting>
</sect2>
<sect2 id="treeview-adding-view-columns">
<title>Añadir columnas a la vista</title>
<para>Puede usar el método <methodname>append_column()</methodname> para decirle a la vista que debe mostrar ciertas columnas del modelo, en cierto orden, con un cierto título de columna.</para>
<programlisting>m_TreeView.append_column("Messages", m_Columns.m_col_text);</programlisting>
<para>Cuando use esta simple sobrecarga <methodname>append_column()</methodname>, el <classname>TreeView</classname> mostrará los datos del modelo con un <classname>CellRenderer</classname> apropiado. Por ejemplo, las cadenas y los números se muestran en un simple widget <classname>Gtk::Entry</classname>, y los booleanos en un <classname>Gtk::CheckButton</classname>. Esto es normalmente lo que necesita. Para otros tipos de columnas, debe conectar un retorno de llamada que convierta su tipo en una cadena representativa, con <methodname>TreeViewColumn::set_cell_data_func()</methodname>; o derivar un <classname>CellRenderer</classname> personalizado. Tenga en cuenta que no se soporta el tipo «(unsigned) short» de manera predeterminada: puede usar como tipo de columna «(unsigned) int» o «(unsigned) long» en su lugar.</para>
</sect2>
<sect2 id="treeview-multiple-model-columns-per-view-column">
<title>Más de una columna del modelo por columna de la vista</title>
<para>Para reproducir más de una columna del modelo en una columna de vista, necesita crear el widget <classname>TreeView::Column</classname> manualmente, y usar <methodname>pack_start()</methodname> para añadirle las columnas del modelo.</para>
<para lang="en">
Then use <methodname>append_column()</methodname> to add the view Column to the
View. Notice that <methodname>Gtk::TreeView::append_column()</methodname> is overridden
to accept either a prebuilt <classname>Gtk::TreeView::Column</classname> widget, or
just the <classname>TreeModelColumn</classname> from which it generates an
appropriate <classname>Gtk::TreeView::Column</classname> widget.
</para>
<para>Aquí hay algo de código de ejemplo de <filename>gtkmm/demos/gtk-demo/example_icontheme.cc</filename>, que tiene un icono pixbuf y un nombre de texto en la misma columna:</para>
<programlisting>Gtk::TreeView::Column* pColumn =
Gtk::manage(new Gtk::TreeView::Column("Icon Name"));
// m_columns.icon and m_columns.iconname are columns in the model.
// pColumn is the column in the TreeView:
pColumn->pack_start(m_columns.icon, /* expand= */ false);
pColumn->pack_start(m_columns.iconname);
m_TreeView.append_column(*pColumn);</programlisting>
</sect2>
<sect2 id="treeview-cellrenderer-details">
<title>Especificar los detalles del CellRenderer</title>
<para lang="en">
The default <classname>CellRenderers</classname> and their default behaviour
will normally suffice, but you might occasionally need finer control. For
instance, this example code from
<filename>gtkmm/demos/gtk-demo/example_treeview_treestore.cc</filename>, appends a
<classname>Gtk::CellRenderer</classname> widget and instructs it to render the
data from various model columns through various aspects of its appearance.
</para>
<programlisting>int cols_count = m_TreeView.append_column_editable("Alex", m_columns.alex);
Gtk::TreeViewColumn* pColumn = m_TreeView.get_column(cols_count-1);
if(pColumn)
{
Gtk::CellRendererToggle* pRenderer =
static_cast<Gtk::CellRendererToggle*>(pColumn->get_first_cell());
pColumn->add_attribute(pRenderer->property_visible(), m_columns.visible);
pColumn->add_attribute(pRenderer->property_activatable(), m_columns.world);</programlisting>
<para>También puede conectarle señales a un <classname>CellRenderer</classname> para detectar las acciones del usuario. Por ejemplo:</para>
<programlisting>Gtk::CellRendererToggle* pRenderer =
Gtk::manage( new Gtk::CellRendererToggle() );
pRenderer->signal_toggled().connect(
sigc::bind( sigc::mem_fun(*this,
&Example_TreeView_TreeStore::on_cell_toggled), m_columns.dave)
);</programlisting>
</sect2>
<sect2 id="treeview-editable-cells">
<title>Celdas editables</title>
<sect3 id="treeview-editable-cells-automatic">
<title>Celdas editables guardadas automáticamente.</title>
<para lang="en">
Cells in a <classname>TreeView</classname> can be edited in-place by the user.
To allow this, use the <classname>Gtk::TreeView</classname>
<methodname>insert_column_editable()</methodname> and
<methodname>append_column_editable()</methodname> methods instead of
<methodname>insert_column()</methodname> and <methodname>append_column()</methodname>.
When these cells are edited the new values will be stored immediately in the
Model. Note that these methods are templates which can only be instantiated for
simple column types such as <classname>Glib::ustring</classname>, int, and
long.
</para>
</sect3>
<sect3 id="treeview-editable-cells-custom">
<title>Implementación de la lógica personalizada para celdas editables.</title>
<para>Sin embargo, tal vez no quiera que se almacenen los valores nuevos inmediatamente. Por ejemplo, tal vez quiera restringir la entrada a ciertos caracteres o rangos de valores.</para>
<para lang="en">
To achieve this, you should use the normal <classname>Gtk::TreeView</classname>
<methodname>insert_column()</methodname> and <methodname>append_column()</methodname>
methods, then use <methodname>get_column_cell_renderer()</methodname> to get the
<classname>Gtk::CellRenderer</classname> used by that column.
</para>
<para>Entonces, convierta ese <classname>Gtk::CellRenderer*</classname> al <classname>CellRenderer</classname> específico que espera, para que pueda usar la API específica.</para>
<para>Por ejemplo, para un CellRendererText, establecería la propiedad <emphasis>editable</emphasis> de la celda a «true», así:</para>
<programlisting>cell.property_editable() = true;</programlisting>
<para>Para un CellRendererToggle, establecería la propiedad <emphasis>activable</emphasis> en su lugar.</para>
<para>Entonces, puede conectar la señal «edited» apropiada. Por ejemplo, conectarlo a <methodname>Gtk::CellRendererText::signal_edited()</methodname>, o a <methodname>Gtk::CellRendererToggle::signal_toggled()</methodname>. Si la columna contiene más de un <classname>CellRenderer</classname>, entonces tendrá que usar <methodname>Gtk::TreeView::get_column()</methodname> y luego llamar a <methodname>get_cell_renderers()</methodname> en esa columna de la vista.</para>
<para>En su manejador de señales, debe examinar el valor nuevo y luego almacenarlo en el modelo, si eso es lo apropiado para su aplicación.</para>
</sect3>
</sect2>
</sect1>
<sect1 id="sec-iterating-over-model-rows">
<title>Iterar sobre las filas del modelo</title>
<para><classname>Gtk::TreeModel</classname> proporciona un contenedor de sus hijos al estilo de las bibliotecas C++ estándar, a través del método <methodname>children()</methodname>. Puede usar los incrementos del iterador familiares de los métodos <methodname>begin()</methodname> y <methodname>end()</methodname>.</para>
<programlisting>typedef Gtk::TreeModel::Children type_children; //minimise code length.
type_children children = refModel->children();
for(type_children::iterator iter = children.begin();
iter != children.end(); ++iter)
{
Gtk::TreeModel::Row row = *iter;
//Do something with the row - see above for set/get.
}</programlisting>
<sect2 id="treeview-row-children">
<title>Fila hija</title>
<para lang="en">
When using a <classname>Gtk::TreeStore</classname>, the rows can have child
rows, which can have their own children in turn. Use
<methodname>Gtk::TreeModel::Row::children()</methodname> to get the container of child <classname>Row</classname>s:
<programlisting lang="en">Gtk::TreeModel::Children children = row.children();</programlisting>
</para>
</sect2>
</sect1>
<sect1 id="sec-treeview-selection">
<title>La selección</title>
<para>Para descubrir qué filas ha seleccionado el usuario, obtenga el objeto <classname>Gtk::TreeView::Selection</classname> del <classname>TreeView</classname>, así:</para>
<programlisting>Glib::RefPtr<Gtk::TreeSelection> refTreeSelection =
m_TreeView.get_selection();</programlisting>
<sect2 id="treeview-selection-mode">
<title>Selección única o múltiple</title>
<para lang="en">
By default, only single rows can be selected, but you can allow
multiple selection by setting the mode, like so:
<programlisting lang="en">refTreeSelection->set_mode(Gtk::SELECTION_MULTIPLE);</programlisting>
</para>
</sect2>
<sect2 id="treeview-selected-rows">
<title>Las filas seleccionadas</title>
<para>Para la selección simple, puede simplemente llamar <methodname>get_selected()</methodname>, así:</para>
<programlisting>TreeModel::iterator iter = refTreeSelection->get_selected();
if(iter) //If anything is selected
{
TreeModel::Row row = *iter;
//Do something with the row.
}</programlisting>
<para>Para la selección múltiple, debe definir un retorno llamada, y pasárselo a <methodname>selected_foreach()</methodname>, <methodname>selected_foreach_path()</methodname>, o <methodname>selected_foreach_iter()</methodname>, así:</para>
<programlisting>refTreeSelection->selected_foreach_iter(
sigc::mem_fun(*this, &TheClass::selected_row_callback) );
void TheClass::selected_row_callback(
const Gtk::TreeModel::iterator& iter)
{
TreeModel::Row row = *iter;
//Do something with the row.
}</programlisting>
</sect2>
<sect2 id="treeview-selection-changed-signal">
<title>La señal «changed»</title>
<para>Para responder a la pulsación del usuario en una fila o un rango de filas, conéctese a la señal así:</para>
<programlisting>refTreeSelection->signal_changed().connect(
sigc::mem_fun(*this, &Example_IconTheme::on_selection_changed)
);</programlisting>
</sect2>
<sect2 id="treeview-selection-preventing">
<title>Evitar la selección de la fila</title>
<para>Tal vez, el usuario no deba ser capaz de seleccionar todos los elementos en su lista o árbol. Por ejemplo, en gtk-demo, puede seleccionar una demostración para ver su código fuente, pero no tiene ningún sentido seleccionar una categoría de demostraciones.</para>
<para>Para controlar qué filas pueden seleccionarse, use el método <methodname>set_select_function()</methodname>, proporcionándole un retorno de llamada <classname>sigc::slot</classname>. Por ejemplo:</para>
<programlisting>m_refTreeSelection->set_select_function( sigc::mem_fun(*this,
&DemoWindow::select_function) );</programlisting>
<para>Y luego</para>
<programlisting>bool DemoWindow::select_function(
const Glib::RefPtr<Gtk::TreeModel>& model,
const Gtk::TreeModel::Path& path, bool)
{
const Gtk::TreeModel::iterator iter = model->get_iter(path);
return iter->children().empty(); // only allow leaf nodes to be selected
}</programlisting>
</sect2>
<sect2 id="treeview-selection-changing">
<title>Cambiar la selección</title>
<para>Para cambiar la selección, especifique un <classname>Gtk::TreeModel::iterator</classname> o un <classname>Gtk::TreeModel::Row</classname>, así:</para>
<programlisting>Gtk::TreeModel::Row row = m_refModel->children()[5]; //The fifth row.
if(row)
refTreeSelection->select(row);</programlisting>
<para>o</para>
<programlisting>Gtk::TreeModel::iterator iter = m_refModel->children().begin()
if(iter)
refTreeSelection->select(iter);</programlisting>
</sect2>
</sect1>
<sect1 id="sec-treeview-sort">
<title>Ordenar</title>
<para>Los modelos de árbol estándar (<classname>TreeStore</classname> y <classname>ListStore</classname>) derivan de <classname>TreeSortable</classname>, por lo que ofrecen funciones de ordenación. Por ejemplo, llame a <methodname>set_sort_column()</methodname> para ordenar el modelo por la columna especificada. O, proporcione una función de retorno de llamada a <methodname>set_sort_func()</methodname> para implementar un algoritmo de ordenación más complejo.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeSortable.html">TreeSortable Reference</ulink></para>
<sect2 id="treeview-sort-headers">
<title>Ordenación al pulsar en columnas</title>
<para lang="en">
So that a user can click on a <classname>TreeView</classname>'s column header to sort the <classname>TreeView</classname>'s contents, call <methodname>Gtk::TreeView::Column::set_sort_column()</methodname>, supplying the model column on which model should be sorted when the header is clicked. For instance:
</para>
<programlisting>Gtk::TreeView::Column* pColumn = treeview.get_column(0);
if(pColumn)
pColumn->set_sort_column(m_columns.m_col_id);</programlisting>
</sect2>
<sect2 id="treeview-sort-independent-views">
<title>Vistas ordenadas independientemente del mismo modelo</title>
<para>El <classname>TreeView</classname> ya le permite mostrar al mismo <classname>TreeModel</classname> en dos widgets <classname>TreeView</classname>. Si necesita que uno de estos «TreeView» ordene el modelo de manera diferente al otro, entonces use un <classname>TreeModelSort</classname> en lugar de solo, por ejemplo, <methodname>Gtk::TreeViewModel::set_sort_column()</methodname>. <classname>TreeModelSort</classname> es un modelo que contiene a otro modelo, presentando una versión ordenada de ese modelo. Por ejemplo, puede añadir una versión ordenada de un modelo a un <classname>TreeView</classname> así:</para>
<programlisting>Glib::RefPtr<Gtk::TreeModelSort> sorted_model =
Gtk::TreeModelSort::create(model);
sorted_model->set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);</programlisting>
<para>Tenga en cuenta, sin embargo, que el «TreeView» le proporcionará iteradores al modelo ordenado. Debe convertirlos a iteradores del modelo hijo subyacente para llevar a cabo acciones en ese modelo. Por ejemplo:</para>
<programlisting>void ExampleWindow::on_button_delete()
{
Glib::RefPtr<Gtk::TreeSelection> refTreeSelection =
m_treeview.get_selection();
if(refTreeSelection)
{
Gtk::TreeModel::iterator sorted_iter =
m_refTreeSelection->get_selected();
if(sorted_iter)
{
Gtk::TreeModel::iterator iter =
m_refModelSort->convert_iter_to_child_iter(sorted_iter);
m_refModel->erase(iter);
}
}
}</programlisting>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeModelSort.html">TreeModelSort Reference</ulink></para>
</sect2>
</sect1>
<sect1 id="sec-treeview-draganddrop">
<title>Arrastrar y soltar</title>
<para><classname>Gtk::TreeView</classname> ya implementa un simple «arrastrar y soltar» cuando se usa con los modelos <classname>Gtk::ListStore</classname> o <classname>Gtk::TreeStore</classname>. Si es necesario, también le permite implementar un comportamiento más complejo cuando se arrastran y sueltan los elementos, usando la API de <link linkend="chapter-draganddrop">Arrastrar y soltar</link> normal.</para>
<sect2 id="treeview-reorderable-rows">
<title>Filas reordenables</title>
<para>Si llama a <methodname>Gtk::TreeView::set:reorderable</methodname>, entonces se podrán mover los elementos de su «TreeView» dentro del «TreeView» en sí. Esto se demuestra en el ejemplo <classname>TreeStore</classname>.</para>
<para>Sin embargo, esto no le permite ningún control acerca de qué elementos pueden arrastrarse, ni dónde pueden soltarse. Si necesita ese control adicional, puede crear un <literal>Gtk::TreeModel</literal> derivado de <literal>Gtk::TreeStore</literal> o <literal>Gtk::ListStore</literal> y sobrecargar los métodos virtuales <literal>Gtk::TreeDragSource::row_draggable()</literal> y <literal>Gdk::TreeDragDest::row_drop_possible()</literal>. Puede examinar los <literal>Gtk::TreeModel::Path</literal> proporcionados y permitir o no arrastrar y soltar devolviendo <literal>true</literal> o <literal>false</literal>.</para>
<para>Esto se demuestra en el ejemplo «drag_and_drop».</para>
</sect2>
</sect1>
<sect1 id="sec-treeview-contextmenu">
<title>Menú contextual emergente</title>
<para>Mucha gente necesita implementar menús contextuales del botón derecho para los <classname>TreeView</classname>, por lo que se explicará cómo hacerlo para ahorrarle tiempo. Excepto uno o dos puntos, es muy parecido a un menú contextual normal, tal como se describe en el <link linkend="sec-menus-popup">capítulo acerca de menús</link>.</para>
<sect2 id="treeview-button-press-event">
<title>Manejar <literal>button_press_event</literal></title>
<para lang="en">
To detect a click of the right mouse button, you need to handle the
<literal>button_press_event</literal> signal, and check exactly which button
was pressed. Because the <classname>TreeView</classname> normally handles this
signal completely, you need to either override the default signal handler in a
derived <classname>TreeView</classname> class, or use
<methodname>connect_notify()</methodname> instead of <methodname>connect()</methodname>.
You probably also want to call the default handler before doing anything else,
so that the right-click will cause the row to be selected first.
</para>
<para>Esto queda demostrado en el ejemplo del menú emergente personalizado.</para>
</sect2>
</sect1>
<sect1 id="sec-treeview-examples"><title>Ejemplos</title>
<sect2 id="liststore-example"><title>ListStore</title>
<para>Este ejemplo tiene un widget <classname>Gtk::TreeView</classname>, con un modelo <classname>Gtk::ListStore</classname>.</para>
<figure id="figure-treeview-liststore">
<title>TreeView - ListStore</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_list.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/list/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); add(m_col_number); add(m_col_percentage);}
Gtk::TreeModelColumn<unsigned int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<short> m_col_number;
Gtk::TreeModelColumn<int> m_col_percentage;
};
ModelColumns m_Columns;
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TreeView m_TreeView;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("Quit")
{
set_title("Gtk::TreeView (ListStore) example");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
//Create the Tree model:
m_refTreeModel = Gtk::ListStore::create(m_Columns);
m_TreeView.set_model(m_refTreeModel);
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Billy Bob";
row[m_Columns.m_col_number] = 10;
row[m_Columns.m_col_percentage] = 15;
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Joey Jojo";
row[m_Columns.m_col_number] = 20;
row[m_Columns.m_col_percentage] = 40;
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 3;
row[m_Columns.m_col_name] = "Rob McRoberts";
row[m_Columns.m_col_number] = 30;
row[m_Columns.m_col_percentage] = 70;
//Add the TreeView's view columns:
//This number will be shown with the default numeric formatting.
m_TreeView.append_column("ID", m_Columns.m_col_id);
m_TreeView.append_column("Name", m_Columns.m_col_name);
m_TreeView.append_column_numeric("Formatted number", m_Columns.m_col_number,
"%010d" /* 10 digits, using leading zeroes. */);
//Display a progress bar instead of a decimal number:
Gtk::CellRendererProgress* cell = Gtk::manage(new Gtk::CellRendererProgress);
int cols_count = m_TreeView.append_column("Some percentage", *cell);
Gtk::TreeViewColumn* pColumn = m_TreeView.get_column(cols_count - 1);
if(pColumn)
{
pColumn->add_attribute(cell->property_value(), m_Columns.m_col_percentage);
}
//Make all the columns reorderable:
//This is not necessary, but it's nice to show the feature.
//You can use TreeView::set_column_drag_function() to more
//finely control column drag and drop.
for(guint i = 0; i < 2; i++)
{
Gtk::TreeView::Column* pColumn = m_TreeView.get_column(i);
pColumn->set_reorderable();
}
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="treestore-example"><title>TreeStore</title>
<para>Este ejemplo es muy similar al ejemplo del <classname>ListStore</classname>, pero usa el modelo <classname>Gtk::TreeStore</classname> en su lugar, y le añade hijos a las filas.</para>
<figure id="figure-treeview-treestore">
<title>TreeView - TreeStore</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_tree.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/tree/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
void on_treeview_row_activated(const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* column);
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_Columns;
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TreeView m_TreeView;
Glib::RefPtr<Gtk::TreeStore> m_refTreeModel;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("Quit")
{
set_title("Gtk::TreeView (TreeStore) example");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
//Create the Tree model:
m_refTreeModel = Gtk::TreeStore::create(m_Columns);
m_TreeView.set_model(m_refTreeModel);
//All the items to be reordered with drag-and-drop:
m_TreeView.set_reorderable();
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Billy Bob";
Gtk::TreeModel::Row childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 11;
childrow[m_Columns.m_col_name] = "Billy Bob Junior";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 12;
childrow[m_Columns.m_col_name] = "Sue Bob";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Joey Jojo";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 3;
row[m_Columns.m_col_name] = "Rob McRoberts";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 31;
childrow[m_Columns.m_col_name] = "Xavier McRoberts";
//Add the TreeView's view columns:
m_TreeView.append_column("ID", m_Columns.m_col_id);
m_TreeView.append_column("Name", m_Columns.m_col_name);
//Connect signal:
m_TreeView.signal_row_activated().connect(sigc::mem_fun(*this,
&ExampleWindow::on_treeview_row_activated) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
void ExampleWindow::on_treeview_row_activated(const Gtk::TreeModel::Path& path,
Gtk::TreeViewColumn* /* column */)
{
Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
if(iter)
{
Gtk::TreeModel::Row row = *iter;
std::cout << "Row activated: ID=" << row[m_Columns.m_col_id] << ", Name="
<< row[m_Columns.m_col_name] << std::endl;
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="sec-editable-cells-example"><title>Celdas editables</title>
<para>Este ejemplo es idéntico al del <classname>ListStore</classname>, pero usa <methodname>TreeView::append_column_editable()</methodname> en lugar de <methodname>TreeView::append_column()</methodname>.</para>
<figure id="figure-treeview-editablecells">
<title>TreeView: celdas editables</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_editablecells.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/editable_cells/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
void treeviewcolumn_validated_on_cell_data(Gtk::CellRenderer* renderer, const Gtk::TreeModel::iterator& iter);
void cellrenderer_validated_on_editing_started(Gtk::CellEditable* cell_editable, const Glib::ustring& path);
void cellrenderer_validated_on_edited(const Glib::ustring& path_string, const Glib::ustring& new_text);
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); add(m_col_foo); add(m_col_number); add(m_col_number_validated); }
Gtk::TreeModelColumn<unsigned int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<bool> m_col_foo;
Gtk::TreeModelColumn<int> m_col_number;
Gtk::TreeModelColumn<int> m_col_number_validated;
};
ModelColumns m_Columns;
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TreeView m_TreeView;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
//For the validated column:
//You could also use a CellRendererSpin or a CellRendererProgress:
Gtk::CellRendererText m_cellrenderer_validated;
Gtk::TreeView::Column m_treeviewcolumn_validated;
bool m_validate_retry;
Glib::ustring m_invalid_text_for_retry;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include "examplewindow.h"
using std::sprintf;
using std::strtol;
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("Quit"),
m_validate_retry(false)
{
set_title("Gtk::TreeView Editable Cells example");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
//Create the Tree model:
m_refTreeModel = Gtk::ListStore::create(m_Columns);
m_TreeView.set_model(m_refTreeModel);
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Billy Bob";
row[m_Columns.m_col_foo] = true;
row[m_Columns.m_col_number] = 10;
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Joey Jojo";
row[m_Columns.m_col_foo] = true;
row[m_Columns.m_col_number] = 20;
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 3;
row[m_Columns.m_col_name] = "Rob McRoberts";
row[m_Columns.m_col_foo] = false;
row[m_Columns.m_col_number] = 30;
//Add the TreeView's view columns:
//We use the *_editable convenience methods for most of these,
//because the default functionality is enough:
m_TreeView.append_column_editable("ID", m_Columns.m_col_id);
m_TreeView.append_column_editable("Name", m_Columns.m_col_name);
m_TreeView.append_column_editable("foo", m_Columns.m_col_foo);
m_TreeView.append_column_numeric_editable("foo", m_Columns.m_col_number,
"%010d");
//For this column, we create the CellRenderer ourselves, and connect our own
//signal handlers, so that we can validate the data that the user enters, and
//control how it is displayed.
m_treeviewcolumn_validated.set_title("validated (<10)");
m_treeviewcolumn_validated.pack_start(m_cellrenderer_validated);
m_TreeView.append_column(m_treeviewcolumn_validated);
//Tell the view column how to render the model values:
m_treeviewcolumn_validated.set_cell_data_func(m_cellrenderer_validated,
sigc::mem_fun(*this,
&ExampleWindow::treeviewcolumn_validated_on_cell_data) );
//Make the CellRenderer editable, and handle its editing signals:
m_cellrenderer_validated.property_editable() = true;
m_cellrenderer_validated.signal_editing_started().connect(
sigc::mem_fun(*this,
&ExampleWindow::cellrenderer_validated_on_editing_started) );
m_cellrenderer_validated.signal_edited().connect( sigc::mem_fun(*this,
&ExampleWindow::cellrenderer_validated_on_edited) );
//If this was a CellRendererSpin then you would have to set the adjustment:
//m_cellrenderer_validated.property_adjustment() = m_spin_adjustment;
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
void ExampleWindow::treeviewcolumn_validated_on_cell_data(
Gtk::CellRenderer* /* renderer */,
const Gtk::TreeModel::iterator& iter)
{
//Get the value from the model and show it appropriately in the view:
if(iter)
{
Gtk::TreeModel::Row row = *iter;
int model_value = row[m_Columns.m_col_number_validated];
//This is just an example.
//In this case, it would be easier to use append_column_editable() or
//append_column_numeric_editable()
char buffer[32];
sprintf(buffer, "%d", model_value);
Glib::ustring view_text = buffer;
m_cellrenderer_validated.property_text() = view_text;
}
}
void ExampleWindow::cellrenderer_validated_on_editing_started(
Gtk::CellEditable* cell_editable, const Glib::ustring& /* path */)
{
//Start editing with previously-entered (but invalid) text,
//if we are allowing the user to correct some invalid data.
if(m_validate_retry)
{
//This is the CellEditable inside the CellRenderer.
Gtk::CellEditable* celleditable_validated = cell_editable;
//It's usually an Entry, at least for a CellRendererText:
Gtk::Entry* pEntry = dynamic_cast<Gtk::Entry*>(celleditable_validated);
if(pEntry)
{
pEntry->set_text(m_invalid_text_for_retry);
m_validate_retry = false;
m_invalid_text_for_retry.clear();
}
}
}
void ExampleWindow::cellrenderer_validated_on_edited(
const Glib::ustring& path_string,
const Glib::ustring& new_text)
{
Gtk::TreePath path(path_string);
//Convert the inputed text to an integer, as needed by our model column:
char* pchEnd = 0;
int new_value = strtol(new_text.c_str(), &pchEnd, 10);
if(new_value > 10)
{
//Prevent entry of numbers higher than 10.
//Tell the user:
Gtk::MessageDialog dialog(*this,
"The number must be less than 10. Please try again.",
false, Gtk::MESSAGE_ERROR);
dialog.run();
//Start editing again, with the bad text, so that the user can correct it.
//A real application should probably allow the user to revert to the
//previous text.
//Set the text to be used in the start_editing signal handler:
m_invalid_text_for_retry = new_text;
m_validate_retry = true;
//Start editing again:
m_TreeView.set_cursor(path, m_treeviewcolumn_validated,
m_cellrenderer_validated, true /* start_editing */);
}
else
{
//Get the row from the path:
Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
if(iter)
{
Gtk::TreeModel::Row row = *iter;
//Put the new value in the model:
row[m_Columns.m_col_number_validated] = new_value;
}
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="treeview-dnd-example"><title>Arrastrar y soltar</title>
<para>Este ejemplo es muy parecido al ejemplo del <classname>TreeStore</classname>, pero tiene dos columnas adicionales que indican si la fila se puede arrastrar, y si puede recibir filas arrastradas y soltadas. Usa un <classname>Gtk::TreeStore</classname> derivado, que sobrecarga las funciones virtuales como se describe en la sección <link linkend="sec-treeview-draganddrop">TreeView: arrastrar y soltar</link>.</para>
<figure id="figure-treeview-draganddrop">
<title>TreeView: arrastrar y soltar</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_draganddrop.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/drag_and_drop/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
#include "treemodel_dnd.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TreeView m_TreeView;
Glib::RefPtr<TreeModel_Dnd> m_refTreeModel;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>treemodel_dnd.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_TREEMODEL_DND_H
#define GTKMM_EXAMPLE_TREEMODEL_DND_H
#include <gtkmm.h>
class TreeModel_Dnd : public Gtk::TreeStore
{
protected:
TreeModel_Dnd();
public:
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); add(m_col_draggable); add(m_col_receivesdrags); }
Gtk::TreeModelColumn<int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
Gtk::TreeModelColumn<bool> m_col_draggable;
Gtk::TreeModelColumn<bool> m_col_receivesdrags;
};
ModelColumns m_Columns;
static Glib::RefPtr<TreeModel_Dnd> create();
protected:
//Overridden virtual functions:
virtual bool row_draggable_vfunc(const Gtk::TreeModel::Path& path) const;
virtual bool row_drop_possible_vfunc(const Gtk::TreeModel::Path& dest, const Gtk::SelectionData& selection_data) const;
};
#endif //GTKMM_EXAMPLE_TREEMODEL_DND_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("_Quit", true)
{
set_title("Gtk::TreeView (Drag and Drop) example");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
//Create the Tree model:
//Use our derived model, which overrides some Gtk::TreeDragDest and
//Gtk::TreeDragSource virtual functions:
//The columns are declared in the overridden TreeModel.
m_refTreeModel = TreeModel_Dnd::create();
m_TreeView.set_model(m_refTreeModel);
//Enable Drag-and-Drop of TreeView rows:
//See also the derived TreeModel's *_vfunc overrides.
m_TreeView.enable_model_drag_source();
m_TreeView.enable_model_drag_dest();
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_refTreeModel->m_Columns.m_col_id] = 1;
row[m_refTreeModel->m_Columns.m_col_name] = "Billy Bob";
row[m_refTreeModel->m_Columns.m_col_draggable] = true;
row[m_refTreeModel->m_Columns.m_col_receivesdrags] = true;
Gtk::TreeModel::Row childrow = *(m_refTreeModel->append(row.children()));
childrow[m_refTreeModel->m_Columns.m_col_id] = 11;
childrow[m_refTreeModel->m_Columns.m_col_name] = "Billy Bob Junior";
childrow[m_refTreeModel->m_Columns.m_col_draggable] = true;
childrow[m_refTreeModel->m_Columns.m_col_receivesdrags] = true;
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_refTreeModel->m_Columns.m_col_id] = 12;
childrow[m_refTreeModel->m_Columns.m_col_name] = "Sue Bob";
childrow[m_refTreeModel->m_Columns.m_col_draggable] = true;
childrow[m_refTreeModel->m_Columns.m_col_receivesdrags] = true;
row = *(m_refTreeModel->append());
row[m_refTreeModel->m_Columns.m_col_id] = 2;
row[m_refTreeModel->m_Columns.m_col_name] = "Joey Jojo";
row[m_refTreeModel->m_Columns.m_col_draggable] = true;
row[m_refTreeModel->m_Columns.m_col_receivesdrags] = true;
row = *(m_refTreeModel->append());
row[m_refTreeModel->m_Columns.m_col_id] = 3;
row[m_refTreeModel->m_Columns.m_col_name] = "Rob McRoberts";
row[m_refTreeModel->m_Columns.m_col_draggable] = true;
row[m_refTreeModel->m_Columns.m_col_receivesdrags] = true;
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_refTreeModel->m_Columns.m_col_id] = 31;
childrow[m_refTreeModel->m_Columns.m_col_name] = "Xavier McRoberts";
childrow[m_refTreeModel->m_Columns.m_col_draggable] = true;
childrow[m_refTreeModel->m_Columns.m_col_receivesdrags] = true;
//Add the TreeView's view columns:
m_TreeView.append_column("ID", m_refTreeModel->m_Columns.m_col_id);
m_TreeView.append_column("Name", m_refTreeModel->m_Columns.m_col_name);
m_TreeView.append_column_editable("Draggable",
m_refTreeModel->m_Columns.m_col_draggable);
m_TreeView.append_column_editable("Receives Drags",
m_refTreeModel->m_Columns.m_col_receivesdrags);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>treemodel_dnd.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "treemodel_dnd.h"
#include <iostream>
TreeModel_Dnd::TreeModel_Dnd()
{
//We can't just call Gtk::TreeModel(m_Columns) in the initializer list
//because m_Columns does not exist when the base class constructor runs.
//And we can't have a static m_Columns instance, because that would be
//instantiated before the gtkmm type system.
//So, we use this method, which should only be used just after creation:
set_column_types(m_Columns);
}
Glib::RefPtr<TreeModel_Dnd> TreeModel_Dnd::create()
{
return Glib::RefPtr<TreeModel_Dnd>( new TreeModel_Dnd() );
}
bool
TreeModel_Dnd::row_draggable_vfunc(const Gtk::TreeModel::Path& path) const
{
// Make the value of the "draggable" column determine whether this row can
// be dragged:
//TODO: Add a const version of get_iter to TreeModel:
TreeModel_Dnd* unconstThis = const_cast<TreeModel_Dnd*>(this);
const_iterator iter = unconstThis->get_iter(path);
//const_iterator iter = get_iter(path);
if(iter)
{
Row row = *iter;
bool is_draggable = row[m_Columns.m_col_draggable];
return is_draggable;
}
return Gtk::TreeStore::row_draggable_vfunc(path);
}
bool
TreeModel_Dnd::row_drop_possible_vfunc(const Gtk::TreeModel::Path& dest,
const Gtk::SelectionData& selection_data) const
{
//Make the value of the "receives drags" column determine whether a row can be
//dragged into it:
//dest is the path that the row would have after it has been dropped:
//But in this case we are more interested in the parent row:
Gtk::TreeModel::Path dest_parent = dest;
bool dest_is_not_top_level = dest_parent.up();
if(!dest_is_not_top_level || dest_parent.empty())
{
//The user wants to move something to the top-level.
//Let's always allow that.
}
else
{
//Get an iterator for the row at this path:
//We must unconst this. This should not be necessary with a future version
//of gtkmm.
//TODO: Add a const version of get_iter to TreeModel:
TreeModel_Dnd* unconstThis = const_cast<TreeModel_Dnd*>(this);
const_iterator iter_dest_parent = unconstThis->get_iter(dest_parent);
//const_iterator iter_dest_parent = get_iter(dest);
if(iter_dest_parent)
{
Row row = *iter_dest_parent;
bool receives_drags = row[m_Columns.m_col_receivesdrags];
return receives_drags;
}
}
//You could also examine the row being dragged (via selection_data)
//if you must look at both rows to see whether a drop should be allowed.
//You could use
//TODO: Add const version of get_from_selection_data(): Glib::RefPtr<const
//Gtk::TreeModel> refThis = Glib::RefPtr<const Gtk::TreeModel>(this);
//
//Glib::RefPtr<Gtk::TreeModel> refThis =
//Glib::RefPtr<Gtk::TreeModel>(const_cast<TreeModel_Dnd*>(this));
//refThis->reference(); //, true /* take_copy */)
//Gtk::TreeModel::Path path_dragged_row;
//Gtk::TreeModel::Path::get_from_selection_data(selection_data, refThis,
//path_dragged_row);
return Gtk::TreeStore::row_drop_possible_vfunc(dest, selection_data);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="treeview-popup-menu-example"><title>Menú contextual emergente</title>
<para>Este ejemplo es muy parecido al ejemplo del <classname>ListStore</classname>, pero deriva un <classname>TreeView</classname> personalizado para sobrecargar al <literal>button_press_event</literal>, y también encapsular al código del modelo de árbol en la clase derivada. Consulte la sección <link linkend="sec-treeview-contextmenu">TreeView: menú contextual emergente</link>.</para>
<figure id="figure-treeview-popup">
<title>TreeView: menú de contexto emergente</title>
<screenshot>
<graphic format="PNG" fileref="figures/treeview_popup.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/popup/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
#include "treeview_withpopup.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
TreeView_WithPopup m_TreeView;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>treeview_withpopup.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_TREEVIEW_WITHPOPUP_H
#define GTKMM_EXAMPLE_TREEVIEW_WITHPOPUP_H
#include <gtkmm.h>
class TreeView_WithPopup : public Gtk::TreeView
{
public:
TreeView_WithPopup();
virtual ~TreeView_WithPopup();
protected:
// Override Signal handler:
// Alternatively, use signal_button_press_event().connect_notify()
virtual bool on_button_press_event(GdkEventButton *ev);
//Signal handler for popup menu items:
void on_menu_file_popup_generic();
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<unsigned int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_Columns;
//The Tree model:
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
Gtk::Menu m_Menu_Popup;
};
#endif //GTKMM_EXAMPLE_TREEVIEW_WITHPOPUP_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("Quit")
{
set_title("Gtk::TreeView (ListStore) example");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TreeView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>treeview_withpopup.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "treeview_withpopup.h"
#include <iostream>
TreeView_WithPopup::TreeView_WithPopup()
{
//Create the Tree model:
m_refTreeModel = Gtk::ListStore::create(m_Columns);
set_model(m_refTreeModel);
//Fill the TreeView's model
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "right-click on this";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "or this";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 3;
row[m_Columns.m_col_name] = "or this, for a popup context menu";
//Add the TreeView's view columns:
append_column("ID", m_Columns.m_col_id);
append_column("Name", m_Columns.m_col_name);
//Fill popup menu:
Gtk::MenuItem* item = Gtk::manage(new Gtk::MenuItem("_Edit", true));
item->signal_activate().connect(
sigc::mem_fun(*this, &TreeView_WithPopup::on_menu_file_popup_generic) );
m_Menu_Popup.append(*item);
item = Gtk::manage(new Gtk::MenuItem("_Process", true));
item->signal_activate().connect(
sigc::mem_fun(*this, &TreeView_WithPopup::on_menu_file_popup_generic) );
m_Menu_Popup.append(*item);
item = Gtk::manage(new Gtk::MenuItem("_Remove", true));
item->signal_activate().connect(
sigc::mem_fun(*this, &TreeView_WithPopup::on_menu_file_popup_generic) );
m_Menu_Popup.append(*item);
m_Menu_Popup.accelerate(*this);
m_Menu_Popup.show_all(); //Show all menu items when the menu pops up
#ifndef GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
signal_button_press_event()
.connect(sigc::mem_fun(*this, &TreeView_WithPopup::on_button_press_event), false);
#endif
}
TreeView_WithPopup::~TreeView_WithPopup()
{
}
bool TreeView_WithPopup::on_button_press_event(GdkEventButton* event)
{
bool return_value = false;
//Call base class, to allow normal handling,
//such as allowing the row to be selected by the right-click:
return_value = TreeView::on_button_press_event(event);
//Then do our custom stuff:
if( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) )
{
m_Menu_Popup.popup(event->button, event->time);
}
return return_value;
}
void TreeView_WithPopup::on_menu_file_popup_generic()
{
std::cout << "A popup menu item was selected." << std::endl;
Glib::RefPtr<Gtk::TreeView::Selection> refSelection = get_selection();
if(refSelection)
{
Gtk::TreeModel::iterator iter = refSelection->get_selected();
if(iter)
{
int id = (*iter)[m_Columns.m_col_id];
std::cout << " Selected ID=" << id << std::endl;
}
}
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-combobox">
<title>Cajas combinadas</title>
<para>Los widgets <classname>ComboBox</classname> ofrecen una lista (o árbol) de opciones en un menú desplegable. Si es apropiado, puede mostrar información adicional acerca de cada elemento, como texto, una imagen, una casilla de verificación, o una barra de progreso. Generalmente, el widget <classname>ComboBox</classname> sólo le permite elegir al usuario entre las opciones disponibles, pero opcionalmente puede tener un <classname>Entry</classname>, permitiéndole al usuario introducir texto arbitrario si ninguna de las opciones disponibles es apropiada.</para>
<para>Un <classname>TreeModel</classname> proporciona la lista, y las columnas de este modelo se añaden a la vista del «ComboBox» con el método <methodname>ComboBox::pack_start()</methodname>. Esto proporciona flexibilidad y seguridad de tipos en tiempo de compilación, pero la clase <classname>ComboBoxText</classname> proporciona una especialización más simple basada en texto en caso de que no se requiera la flexibilidad.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ComboBox.html">Reference</ulink></para>
<sect1 id="sec-combobox-model">
<title>El modelo</title>
<para>El modelo de una «ComboBox» puede definirse y llenarse exactamente como un <classname>TreeView</classname>. Por ejemplo, puede derivar una clase «ComboBox» con una columna de números enteros y otra de texto, así:</para>
<programlisting>ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_columns;</programlisting>
<para>Después de añadirle las filas a este modelo, deberá proporcionárselo al <classname>ComboBox</classname> con el método <methodname>set_model()</methodname>. Luego, use los métodos <methodname>pack_start()</methodname> o <methodname>pack_end()</methodname> para especificar qué columnas se mostrarán en el «ComboBox». Al igual que con el «TreeView», podrá usar el «CellRenderer» predeterminado pasándole la <classname>TreeModelColumn</classname> a los métodos de empaquetado, o puede instanciar un <classname>CellRenderer</classname> específico y definir un mapeado particular con <methodname>add_attribute()</methodname> o <methodname>set_cell_data_func()</methodname>. Tenga en cuenta que estos métodos están en la clase base <classname>CellLayout</classname>.</para>
</sect1>
<sect1 id="sec-combobox-get">
<title>El elemento elegido</title>
<para lang="en">To discover what item, if any, the user has chosen from the ComboBox, call <methodname>ComboBox::get_active()</methodname>. This returns a <classname>TreeModel::iterator</classname> that you can dereference to a <classname>Row</classname> in order to read the values in your columns. For instance, you might read an integer ID value from the model, even though you have chosen only to show the human-readable description in the ComboBox. For instance:
</para>
<programlisting>Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
Gtk::TreeModel::Row row = *iter;
//Get the data for the selected row, using our knowledge
//of the tree model:
int id = row[m_Columns.m_col_id];
set_something_id_chosen(id); //Your own function.
}
else
set_nothing_chosen(); //Your own function.</programlisting>
</sect1>
<sect1 id="sec-combobox-changes">
<title>Responder a los cambios</title>
<para>Tal vez necesite reaccionar a cada cambio de la selección en el «ComboBox», por ejemplo, para actualizar otros widgets. Para hacer esto, debe manejar la señal <literal>changed</literal>. Por ejemplo:</para>
<programlisting>m_combo.signal_changed().connect( sigc::mem_fun(*this,
&ExampleWindow::on_combo_changed) );</programlisting>
</sect1>
<sect1 id="combobox-example-full"><title>Ejemplo completo</title>
<figure id="figure-combobox-complex">
<title>ComboBox</title>
<screenshot>
<graphic format="PNG" fileref="figures/combobox_complex.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/complex?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm/window.h>
#include <gtkmm/comboboxtext.h>
#include <gtkmm/liststore.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_combo_changed();
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<int> m_col_id;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_Columns;
//Child widgets:
Gtk::ComboBox m_Combo;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
{
set_title("ComboBox example");
//Create the Tree model:
//m_refTreeModel = Gtk::TreeStore::create(m_Columns);
m_refTreeModel = Gtk::ListStore::create(m_Columns);
m_Combo.set_model(m_refTreeModel);
//Fill the ComboBox's Tree Model:
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 1;
row[m_Columns.m_col_name] = "Billy Bob";
m_Combo.set_active(row);
/*
Gtk::TreeModel::Row childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 11;
childrow[m_Columns.m_col_name] = "Billy Bob Junior";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 12;
childrow[m_Columns.m_col_name] = "Sue Bob";
*/
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 2;
row[m_Columns.m_col_name] = "Joey Jojo";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = 3;
row[m_Columns.m_col_name] = "Rob McRoberts";
/*
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 31;
childrow[m_Columns.m_col_name] = "Xavier McRoberts";
*/
//Add the model columns to the Combo (which is a kind of view),
//rendering them in the default way:
m_Combo.pack_start(m_Columns.m_col_id);
m_Combo.pack_start(m_Columns.m_col_name);
//Add the ComboBox to the window.
add(m_Combo);
//Connect signal handler:
m_Combo.signal_changed().connect( sigc::mem_fun(*this, &ExampleWindow::on_combo_changed) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_combo_changed()
{
Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
Gtk::TreeModel::Row row = *iter;
if(row)
{
//Get the data for the selected row, using our knowledge of the tree
//model:
int id = row[m_Columns.m_col_id];
Glib::ustring name = row[m_Columns.m_col_name];
std::cout << " ID=" << id << ", name=" << name << std::endl;
}
}
else
std::cout << "invalid iter" << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect1>
<sect1 id="combobox-example-simple"><title>Ejemplo de texto simple</title>
<figure id="figure-combobox-text">
<title>ComboBoxText</title>
<screenshot>
<graphic format="PNG" fileref="figures/combobox_text.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/text?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm/window.h>
#include <gtkmm/comboboxtext.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_combo_changed();
//Child widgets:
Gtk::ComboBoxText m_Combo;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
{
set_title("ComboBoxText example");
//Fill the combo:
m_Combo.append("something");
m_Combo.append("something else");
m_Combo.append("something or other");
m_Combo.set_active(1);
add(m_Combo);
//Connect signal handler:
m_Combo.signal_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_combo_changed) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_combo_changed()
{
Glib::ustring text = m_Combo.get_active_text();
if(!(text.empty()))
std::cout << "Combo changed: " << text << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect1>
<sect1 id="sec-comboboxentry">
<title>«ComboBox» con una entrada</title>
<para>Un <classname>ComboBox</classname> puede contener un widget <classname>Entry</classname> para la entrada de texto arbitrario, mediante la especificación de <literal>true</literal> al parámetro <literal>has_entry</literal> del constructor.</para>
<sect2 id="sec-comboboxentry-text-column">
<title>La columna de texto</title>
<para lang="en">So that the <classname>Entry</classname> can interact with the drop-down list of choices, you must specify which of your model columns is the text column, with <methodname>set_entry_text_column()</methodname>. For instance:
<programlisting lang="en">m_combo.set_entry_text_column(m_columns.m_col_name);</programlisting>
</para>
<para>Cuando seleccione una opción de la lista desplegable, el valor de esta columna se pondrá en el widget <classname>Entry</classname>.</para>
</sect2>
<sect2 id="sec-comboboxentry-model">
<title>La entrada</title>
<para>Dado que el usuario puede introducir texto arbitrario, una fila del modelo activa es suficiente para indicar qué texto ha introducido el usuario. Por lo tanto, debe obtener el widget <classname>Entry</classname> con el método <methodname>ComboBoxEntry::get_entry()</methodname> y llamar a <methodname>get_text()</methodname> sobre él.</para>
</sect2>
<sect2 id="sec-comboboxentry-changes">
<title>Responder a los cambios</title>
<para lang="en">
When the user enters arbitrary text, it may not be enough to connect to the
<literal>changed</literal> signal, which is emitted for every typed character.
It is not emitted when the user presses the Enter key. Pressing the Enter key or
moving the keyboard focus to another widget may signal that the user has finished
entering text. To be notified of these events, connect to the
<classname>Entry</classname>'s <literal>activate</literal> and
<literal>focus_out_event</literal> signals, like so
<programlisting lang="en">Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
// The Entry shall receive focus-out events.
entry->add_events(Gdk::FOCUS_CHANGE_MASK);
// Alternatively you can connect to m_Combo.signal_changed().
entry->signal_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_entry_changed) );
entry->signal_activate().connect(sigc::mem_fun(*this,
&ExampleWindow::on_entry_activate) );
entry->signal_focus_out_event().connect(sigc::mem_fun(*this,
&ExampleWindow::on_entry_focus_out_event) );
}</programlisting>
The <literal>changed</literal> signals of <classname>ComboBox</classname> and
<classname>Entry</classname> are both emitted for every change. It doesn't matter
which one you connect to. But only <classname>Entry</classname>'s
<literal>focus_out_event</literal> signal is useful here.
</para>
<para>Los eventos de X se describen con mayor detalle en la sección <link linkend="sec-xeventsignals">Señales de eventos de X</link> en el apéndice.</para>
</sect2>
<sect2 id="comboboxentry-example-full"><title>Ejemplo completo</title>
<figure id="figure-comboboxentry-complex">
<title>«ComboBox» con una entrada</title>
<screenshot>
<graphic format="PNG" fileref="figures/comboboxentry_complex.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/entry_complex?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm/window.h>
#include <gtkmm/combobox.h>
#include <gtkmm/liststore.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_entry_changed();
void on_entry_activate();
bool on_entry_focus_out_event(GdkEventFocus* event);
//Signal connection:
sigc::connection m_ConnectionFocusOut;
//Tree model columns:
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns()
{ add(m_col_id); add(m_col_name); }
Gtk::TreeModelColumn<Glib::ustring> m_col_id; //The data to choose - this must be text.
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumns m_Columns;
//Child widgets:
Gtk::ComboBox m_Combo;
Glib::RefPtr<Gtk::ListStore> m_refTreeModel;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_Combo(true /* has_entry */)
{
set_title("ComboBox example");
//Create the Tree model:
//m_refTreeModel = Gtk::TreeStore::create(m_Columns);
m_refTreeModel = Gtk::ListStore::create(m_Columns);
m_Combo.set_model(m_refTreeModel);
//Fill the ComboBox's Tree Model:
Gtk::TreeModel::Row row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = "1";
row[m_Columns.m_col_name] = "Billy Bob";
/*
Gtk::TreeModel::Row childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 11;
childrow[m_Columns.m_col_name] = "Billy Bob Junior";
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 12;
childrow[m_Columns.m_col_name] = "Sue Bob";
*/
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = "2";
row[m_Columns.m_col_name] = "Joey Jojo";
row = *(m_refTreeModel->append());
row[m_Columns.m_col_id] = "3";
row[m_Columns.m_col_name] = "Rob McRoberts";
/*
childrow = *(m_refTreeModel->append(row.children()));
childrow[m_Columns.m_col_id] = 31;
childrow[m_Columns.m_col_name] = "Xavier McRoberts";
*/
//Add the model columns to the Combo (which is a kind of view),
//rendering them in the default way:
//This is automatically rendered when we use set_entry_text_column().
//m_Combo.pack_start(m_Columns.m_col_id);
m_Combo.pack_start(m_Columns.m_col_name);
m_Combo.set_entry_text_column(m_Columns.m_col_id);
m_Combo.set_active(1);
//Add the ComboBox to the window.
add(m_Combo);
//Connect signal handlers:
Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
// The Entry shall receive focus-out events.
entry->add_events(Gdk::FOCUS_CHANGE_MASK);
// Alternatively you can connect to m_Combo.signal_changed().
entry->signal_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_entry_changed) );
entry->signal_activate().connect(sigc::mem_fun(*this,
&ExampleWindow::on_entry_activate) );
m_ConnectionFocusOut = entry->signal_focus_out_event().
connect(sigc::mem_fun(*this, &ExampleWindow::on_entry_focus_out_event) );
}
else
std::cout << "No Entry ???" << std::endl;
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
// The focus_out signal may be emitted while m_Combo is being destructed.
// The signal handler can generate critical messages, if it's called when
// m_Combo has been partly destructed.
m_ConnectionFocusOut.disconnect();
}
void ExampleWindow::on_entry_changed()
{
Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
std::cout << "on_entry_changed(): Row=" << m_Combo.get_active_row_number()
<< ", ID=" << entry->get_text() << std::endl;
}
}
void ExampleWindow::on_entry_activate()
{
Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
std::cout << "on_entry_activate(): Row=" << m_Combo.get_active_row_number()
<< ", ID=" << entry->get_text() << std::endl;
}
}
bool ExampleWindow::on_entry_focus_out_event(GdkEventFocus* /* event */)
{
Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
std::cout << "on_entry_focus_out_event(): Row=" << m_Combo.get_active_row_number()
<< ", ID=" << entry->get_text() << std::endl;
return true;
}
return false;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="comboboxentry-example-simple"><title>Ejemplo de texto simple</title>
<figure id="figure-comboboxentry-text">
<title>«ComboBoxText» con una entrada</title>
<screenshot>
<graphic format="PNG" fileref="figures/comboboxentry_text.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/entry_text?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm/window.h>
#include <gtkmm/comboboxtext.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_combo_changed();
void on_entry_activate();
bool on_entry_focus_out_event(GdkEventFocus* event);
//Signal connection:
sigc::connection m_ConnectionFocusOut;
//Child widgets:
Gtk::ComboBoxText m_Combo;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_Combo(true /* has_entry */)
{
set_title("ComboBoxText example");
//Fill the combo:
m_Combo.append("something");
m_Combo.append("something else");
m_Combo.append("something or other");
m_Combo.set_active(0);
add(m_Combo);
//Connect signal handlers:
Gtk::Entry* entry = m_Combo.get_entry();
// Alternatively you can connect to entry->signal_changed().
m_Combo.signal_changed().connect(sigc::mem_fun(*this,
&ExampleWindow::on_combo_changed) );
if (entry)
{
// The Entry shall receive focus-out events.
entry->add_events(Gdk::FOCUS_CHANGE_MASK);
entry->signal_activate().connect(sigc::mem_fun(*this,
&ExampleWindow::on_entry_activate) );
m_ConnectionFocusOut = entry->signal_focus_out_event().
connect(sigc::mem_fun(*this, &ExampleWindow::on_entry_focus_out_event) );
}
else
std::cout << "No Entry ???" << std::endl;
m_Combo.property_has_frame() = false;
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
// The focus_out signal may be emitted while m_Combo is being destructed.
// The signal handler can generate critical messages, if it's called when
// m_Combo has been partly destructed.
m_ConnectionFocusOut.disconnect();
}
void ExampleWindow::on_combo_changed()
{
std::cout << "on_combo_changed(): Row=" << m_Combo.get_active_row_number()
<< ", Text=" << m_Combo.get_active_text() << std::endl;
}
void ExampleWindow::on_entry_activate()
{
std::cout << "on_entry_activate(): Row=" << m_Combo.get_active_row_number()
<< ", Text=" << m_Combo.get_active_text() << std::endl;
}
bool ExampleWindow::on_entry_focus_out_event(GdkEventFocus* /* event */)
{
std::cout << "on_entry_focus_out_event(): Row=" << m_Combo.get_active_row_number()
<< ", Text=" << m_Combo.get_active_text() << std::endl;
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-textview">
<title>TextView</title>
<para>El widget <classname>TextView</classname> puede usarse para mostrar y editar grandes cantidades de texto formateado. Al igual que el <classname>TreeView</classname>, tiene un diseño modelo/vista. En este caso, el <classname>TextBuffer</classname> es el modelo.</para>
<sect1 id="sec-textview-buffer">
<title>El búfer</title>
<para><classname>Gtk::TextBuffer</classname> es el modelo que contiene los datos del <classname>Gtk::TextView</classname>, al igual que el <classname>Gtk::TreeModel</classname> usado por <classname>Gtk::TreeView</classname>. Esto permite a dos o más <classname>Gtk::TreeView</classname> compartir el mismo <classname>TextBuffer</classname>, y permite mostrar esos búferes de texto de una manera ligeramente diferente. O bien, puede mantener varios <classname>Gtk::TextBuffer</classname> y elegir mostrar cada uno en distintas ocasiones en el mismo widget <classname>GtK::TextView</classname>.</para>
<para>El <classname>TextView</classname> crea su propio <classname>TextBuffer</classname> predeterminado, al que puede acceder mediante el método <methodname>get_buffer()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextBuffer.html">Reference</ulink></para>
<sect2 id="textview-iterators">
<title>Iteradores</title>
<para>
</para>
</sect2>
<sect2 id="textview-formatting">
<title>Etiquetas y formateado</title>
<sect3 id="textview-formatting-tags">
<title>Etiquetas</title>
<para>Para especificar que algún texto en el búfer deba tener un formato especial, defina una etiqueta que contenta esa información de formato, y luego aplíquela a la región de texto. Por ejemplo, para definir la etiqueta y sus propiedades:</para>
<programlisting>Glib::RefPtr<Gtk::TextBuffer::Tag> refTagMatch =
Gtk::TextBuffer::Tag::create();
refTagMatch->property_background() = "orange";</programlisting>
<para>Puede especificar un nombre para la clase <classname>Tag</classname> cuando use el método <methodname>create()</methodname>, pero no es necesario.</para>
<para>La clase <classname>Tag</classname> tiene muchas otras propiedades.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTag.html">Reference</ulink></para>
</sect3>
<sect3 id="textview-formatting-tagtable">
<title>TagTable</title>
<para>Cada <classname>Gtk::TextBuffer</classname> usa una <classname>Gtk::TextBuffer::TagTable</classname>, que contiene las <classname>Tag</classname> para ese búfer. Dos o más <classname>TextBuffer</classname> pueden compartir la misma <classname>TagTable</classname>. Cuando cree las <classname>Tag</classname>, añádalas a la <classname>TagTable</classname>. Por ejemplo:</para>
<programlisting>Glib::RefPtr<Gtk::TextBuffer::TagTable> refTagTable =
Gtk::TextBuffer::TagTable::create();
refTagTable->add(refTagMatch);
//Hopefully a future version of <application>gtkmm</application> will have a set_tag_table() method,
//for use after creation of the buffer.
Glib::RefPtr<Gtk::TextBuffer> refBuffer =
Gtk::TextBuffer::create(refTagTable);</programlisting>
<para>También puede usar <methodname>get_tag_table()</methodname> para obtener, y tal vez modificar, la <classname>TagTable</classname> predeterminada del <classname>TextBuffer</classname> en lugar de crear una explícitamente.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTagTable.html">Reference</ulink></para>
</sect3>
<sect3 id="textview-formatting-applying-tags">
<title>Aplicar etiquetas</title>
<para>Si ha creado una <classname>Tag</classname> y la ha añadido a la <classname>TagTable</classname>, podrá aplicarle esa etiqueta a parte del <classname>TextBuffer</classname>, para que una parte del texto se muestre con ese formato. Puede definir el inicio y el fin del rango de texto especificando <classname>Gtk::TextBuffer::iterator</classname>. Por ejemplo:</para>
<programlisting>refBuffer->apply_tag(refTagMatch, iterRangeStart, iterRangeStop);</programlisting>
<para lang="en">
Or you could specify the tag when first inserting the text:
<programlisting lang="en">refBuffer->insert_with_tag(iter, "Some text", refTagMatch);</programlisting>
</para>
<para>Puede aplicar más de una <classname>Tag</classname> al mismo texto, usando <methodname>apply_tag()</methodname> más de una vez, o usando <methodname>insert_with_tags()</methodname>. Las <classname>Tag</classname> podrían especificar valores diferentes para las mismas propiedades, pero puede resolver estos conflictos usando <methodname>Tag::set_priority()</methodname>.</para>
</sect3>
</sect2>
<sect2 id="textview-marks">
<title>Marcas</title>
<para>Generalmente se invalidan los iteradores del <classname>TextBuffer</classname> cuando el texto cambia, pero puede usar una <classname>Gtk::TextBuffer::Mark</classname> para recordar una posición en estas situaciones. Por ejemplo,</para>
<programlisting>Glib::RefPtr<Gtk::TextBuffer::Mark> refMark =
refBuffer->create_mark(iter);</programlisting>
<para>Puede entonces usar el método <methodname>get_iter()</methodname> más tarde para crear un iterador para la posición nueva de la <classname>Mark</classname>.</para>
<para>Hay dos clases <classname>Mark</classname> incorporadas: <literal>insert</literal> y <literal>select_bound</literal>, a las que puede acceder con los métodos <methodname>get_insert()</methodname> and <methodname>get_selection_bound()</methodname> de <classname>TextBuffer</classname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextMark.html">Reference</ulink></para>
</sect2>
<sect2 id="textview-view">
<title>La vista</title>
<para>Como se mencionó anteriormente, cada <classname>TextView</classname> tiene un <classname>TextBuffer</classname>, y uno o más <classname>TextView</classname> pueden compartir el mismo <classname>TextBuffer</classname>.</para>
<para>Al igual que con el <classname>TreeView</classname>, probablemente deba poner su <classname>TextView</classname> dentro de una <classname>ScrolledWindow</classname> para permitirle al usuario ver y mover toda el área de texto con barras de desplazamiento.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextView.html">Reference</ulink></para>
<sect3 id="textview-default-formatting">
<title>Formato predeterminado</title>
<para>Los <classname>TextView</classname> tienen varios métodos que le permiten cambiar la presentación del búfer de esta vista particular. Algunos de estos pueden anularse por los <classname>Gtk::TextTag</classname> en el búfer, si especifican las mismas cosas. Por ejemplo, <methodname>set_left_margin()</methodname>, <methodname>set_right_margin()</methodname>, <methodname>set_indent()</methodname>, etc.</para>
</sect3>
<sect3 id="textview-scrolling">
<title>Desplazamiento</title>
<para><classname>Gtk::TextView</classname> tiene varios métodos <methodname>scroll_to_*()</methodname>. Estos le permiten asegurarse de que una parte particular del búfer de texto es visible. Por ejemplo, la característica «Encontrar» de su aplicación podría usar <methodname>Gtk::TextView::scroll_to_iter()</methodname> para mostrar el texto encontrado.</para>
</sect3>
</sect2>
</sect1>
<sect1 id="sec-widgets-and-childanchors">
<title>Widgets y ChildAnchors</title>
<para>Puede empotrar widgets, como <classname>Gtk::Button</classname> en el texto. Cada widget hijo necesitará un <classname>ChildAnchor</classname>. Los «ChildAnchor» están asociados a los <classname>iterators</classname>. Por ejemplo, para crear un «ChildAnchor» en una posición particular, use <methodname>Gtk::TextBuffer::create_child_anchor()</methodname>:</para>
<programlisting>Glib::RefPtr<Gtk::TextChildAnchor> refAnchor =
refBuffer->create_child_anchor(iter);</programlisting>
<para>Luego, para añadir un widget en esa posición, use <methodname>Gtk::TextView::add_child_at_anchor()</methodname>:</para>
<programlisting>m_TextView.add_child_at_anchor(m_Button, refAnchor);</programlisting>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextChildAnchor.html">Reference</ulink></para>
</sect1>
<sect1 id="sec-textview-examples"><title>Ejemplos</title>
<sect2 id="textview-example-simple"><title>Ejemplo simple</title>
<figure id="figure-textview">
<title>TextView</title>
<screenshot>
<graphic format="PNG" fileref="figures/textview.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/textview/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
void fill_buffers();
//Signal handlers:
void on_button_quit();
void on_button_buffer1();
void on_button_buffer2();
//Child widgets:
Gtk::Box m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer1, m_refTextBuffer2;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit, m_Button_Buffer1, m_Button_Buffer2;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("_Quit", true),
m_Button_Buffer1("Use buffer 1"),
m_Button_Buffer2("Use buffer 2")
{
set_title("Gtk::TextView example");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TextView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
//Add buttons:
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Buffer1, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Buffer2, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_spacing(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
//Connect signals:
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
m_Button_Buffer1.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_buffer1) );
m_Button_Buffer2.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_buffer2) );
fill_buffers();
on_button_buffer1();
show_all_children();
}
void ExampleWindow::fill_buffers()
{
m_refTextBuffer1 = Gtk::TextBuffer::create();
m_refTextBuffer1->set_text("This is the text from TextBuffer #1.");
m_refTextBuffer2 = Gtk::TextBuffer::create();
m_refTextBuffer2->set_text(
"This is some alternative text, from TextBuffer #2.");
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
void ExampleWindow::on_button_buffer1()
{
m_TextView.set_buffer(m_refTextBuffer1);
}
void ExampleWindow::on_button_buffer2()
{
m_TextView.set_buffer(m_refTextBuffer2);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-menus-and-toolbars">
<title>Menús y barras de herramientas</title>
<para>Hay API específicas para los menús y las barras de herramientas, pero usualmente debe tratarlas juntas, usando el <classname>UIManager</classname> para definir <classname>Action</classname> que puede ordenar en menús y barras de herramientas. De esta forma, puede manejar la activación de la acción en lugar de responder a los elementos del menú y las barras de herramientas separadamente. Y puede activar o desactivar tanto el elemento del menú como el de la barra de herramientas a través de la acción.</para>
<para>Esto implica el uso de las clases <classname>Gtk::ActionGroup</classname>, <classname>Gtk::Action</classname>, y <classname>UIManager</classname>, todas las cuales deben instanciarse a través de sus métodos <methodname>create()</methodname>, que devuelven <classname>RefPtr</classname>.</para>
<sect1 id="sec-actions">
<title>Acciones</title>
<para>Primero cree las <classname>Action</classname>s y añádaselas a un <classname>ActionGroup</classname>, con <methodname>ActionGroup::add()</methodname>.</para>
<para>Los argumentos de <methodname>Action::create()</methodname> especifican el nombre de la acción y cómo aparecerá en los menús y las barras de herramientas.</para>
<para>También puede especificar un manejador de señales cuando llame a <methodname>ActionGroup::add()</methodname>. Se llamará a este manejador de señales cuando se active la acción a través de un elemento del menú o un botón de la barra de herramientas.</para>
<para>Tenga en cuenta que debe especificar acciones para submenús así como para elementos del menú.</para>
<para>Por ejemplo:</para>
<programlisting>m_refActionGroup = Gtk::ActionGroup::create();
m_refActionGroup->add( Gtk::Action::create("MenuFile", "_File") );
m_refActionGroup->add( Gtk::Action::create("New", "_New"),
sigc::mem_fun(*this, &ExampleWindow::on_action_file_new) );
m_refActionGroup->add( Gtk::Action::create("ExportData", "Export Data"),
sigc::mem_fun(*this, &ExampleWindow::on_action_file_open) );
m_refActionGroup->add( Gtk::Action::create("Quit", "_Quit"),
sigc::mem_fun(*this, &ExampleWindow::on_action_file_quit) );</programlisting>
<para lang="en">Note that this is where we specify the names of the actions as they will be seen by users in menus and toolbars. Therefore, this is where you should make strings translatable, by putting them inside the _() macro.</para>
</sect1>
<sect1 id="sec-uimanager">
<title>UIManager</title>
<para>A continuación debe crear un <classname>UIManager</classname> y añadirle el <classname>ActionGroup</classname> con <classname>insert_action_group()</classname>. En este punto, también es una buena idea decirle a la ventana madre que responda a los atajos del teclado especificados, usando <methodname>add_accel_group()</methodname>.</para>
<para>Por ejemplo,</para>
<programlisting>Glib::RefPtr<Gtk::UIManager> m_refUIManager =
Gtk::UIManager::create();
m_refUIManager->insert_action_group(m_refActionGroup);
add_accel_group(m_refUIManager->get_accel_group());</programlisting>
<para>Luego, puede definir la distribución visible real de los menús y las barras de herramientas, y añadírsela al <classname>UIManager</classname>. Esta «cadena de IU» usa un formato XML, en el que debe mencionar los nombre de las acciones que ya ha creado. Por ejemplo:</para>
<programlisting>Glib::ustring ui_info =
"<ui>"
" <menubar name='MenuBar'>"
" <menu action='MenuFile'>"
" <menuitem action='New'/>"
" <menuitem action='Open'/>"
" <separator/>"
" <menuitem action='Quit'/>"
" </menu>"
" <menu action='MenuEdit'>"
" <menuitem action='Cut'/>"
" <menuitem action='Copy'/>"
" <menuitem action='Paste'/>"
" </menu>"
" </menubar>"
" <toolbar name='ToolBar'>"
" <toolitem action='Open'/>"
" <toolitem action='Quit'/>"
" </toolbar>"
"</ui>";
m_refUIManager->add_ui_from_string(ui_info);</programlisting>
<para>Recuerde que estos nombres son sólo identificadores que se usaron cuando se crearon las acciones. No son el texto que el usuario verá en los menús y barras de herramientas. Se han proporcionado esos nombres legibles por el humano cuando se crearon las acciones.</para>
<para>Para instanciar una <classname>Gtk::MenuBar</classname> o una <classname>Gtk::Toolbar</classname>, a la que en realidad puede mostrar, debe usar el método <methodname>UIManager::get_widget()</methodname>, y luego añadirle el widget a un contenedor. Por ejemplo:</para>
<programlisting>Gtk::Widget* pMenubar = m_refUIManager->get_widget("/MenuBar");
pBox->add(*pMenuBar, Gtk::PACK_SHRINK);</programlisting>
</sect1>
<sect1 id="sec-menus-popup"><title>Menús emergentes</title>
<para>Normalmente, simplemente se añaden los <classname>Menus</classname> a la ventana, pero también pueden mostrarse temporalmente como resultado de una pulsación del botón del ratón. Por ejemplo, se puede mostrar un menú contextual cuando el usuario pulsa el botón derecho de su ratón.</para>
<para>La distribución de la IU para un menú emergente debe usar el nodo <literal>popup</literal>. Por ejemplo:</para>
<programlisting>Glib::ustring ui_info =
"<ui>"
" <popup name='PopupMenu'>"
" <menuitem action='ContextEdit'/>"
" <menuitem action='ContextProcess'/>"
" <menuitem action='ContextRemove'/>"
" </popup>"
"</ui>";
m_refUIManager->add_ui_from_string(ui_info);</programlisting>
<para>Para mostrar el menú contextual, use el método <methodname>popup()</methodname> del <classname>Gtk::Menu</classname>, proporcionándole el identificador del botón y el tiempo de activación, como los proporciona la señal <literal>button_press_event</literal> que, de todos modos, deberá manejar. Por ejemplo:</para>
<programlisting>bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
if( (event->type == GDK_BUTTON_PRESS) &&
(event->button == 3) )
{
m_Menu_Popup->popup(event->button, event->time);
return true; //It has been handled.
}
else
return false;
}</programlisting>
</sect1>
<sect1 id="sec-menus-examples">
<title>Ejemplos</title>
<sect2 id="menu-example-main"><title>Ejemplo de menú principal</title>
<figure id="figure-menus-mainmenu">
<title>Menú principal</title>
<screenshot>
<graphic format="PNG" fileref="figures/main_menu.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/menus/main_menu/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_menu_file_new_generic();
void on_menu_file_quit();
void on_menu_others();
void on_menu_choices(const Glib::ustring& parameter);
void on_menu_choices_other(int parameter);
void on_menu_toggle();
//Child widgets:
Gtk::Box m_Box;
Glib::RefPtr<Gtk::Builder> m_refBuilder;
//Two sets of choices:
Glib::RefPtr<Gio::SimpleAction> m_refChoice, m_refChoiceOther;
Glib::RefPtr<Gio::SimpleAction> m_refToggle;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_Box(Gtk::ORIENTATION_VERTICAL)
{
set_title("main menu example");
set_default_size(200, 200);
add(m_Box); // put a MenuBar at the top of the box and other stuff below it.
//Create actions for menus and toolbars:
Glib::RefPtr<Gio::SimpleActionGroup> refActionGroup =
Gio::SimpleActionGroup::create();
//File|New sub menu:
refActionGroup->add_action("newstandard",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new_generic));
refActionGroup->add_action("newfoo",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new_generic));
refActionGroup->add_action("newgoo",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new_generic));
//File menu:
refActionGroup->add_action("quit",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_quit));
//Edit menu:
refActionGroup->add_action("copy",
sigc::mem_fun(*this, &ExampleWindow::on_menu_others));
refActionGroup->add_action("paste",
sigc::mem_fun(*this, &ExampleWindow::on_menu_others));
refActionGroup->add_action("something",
sigc::mem_fun(*this, &ExampleWindow::on_menu_others));
//Choices menus, to demonstrate Radio items,
//using our convenience methods for string and int radio values:
m_refChoice = refActionGroup->add_action_radio_string("choice",
sigc::mem_fun(*this, &ExampleWindow::on_menu_choices),
"a");
m_refChoiceOther = refActionGroup->add_action_radio_integer("choiceother",
sigc::mem_fun(*this, &ExampleWindow::on_menu_choices_other),
1);
m_refToggle = refActionGroup->add_action_bool("sometoggle",
sigc::mem_fun(*this, &ExampleWindow::on_menu_toggle),
false);
//Help menu:
refActionGroup->add_action("about",
sigc::mem_fun(*this, &ExampleWindow::on_menu_others) );
insert_action_group("example", refActionGroup);
m_refBuilder = Gtk::Builder::create();
//TODO: add_accel_group(m_refBuilder->get_accel_group());
//Layout the actions in a menubar and toolbar:
Glib::ustring ui_info =
"<interface>"
" <menu id='menu-example'>"
" <submenu>"
" <attribute name='label' translatable='yes'>_File</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>New _Standard</attribute>"
" <attribute name='action'>example.newstandard</attribute>"
" <attribute name='accel'>&lt;Primary&gt;n</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>New _Foo</attribute>"
" <attribute name='action'>example.newfoo</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>New _Goo</attribute>"
" <attribute name='action'>example.newgoo</attribute>"
" </item>"
" </section>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_Quit</attribute>"
" <attribute name='action'>example.quit</attribute>"
" <attribute name='accel'>&lt;Primary&gt;q</attribute>"
" </item>"
" </section>"
" </submenu>"
" <submenu>"
" <attribute name='label' translatable='yes'>_Edit</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_Copy</attribute>"
" <attribute name='action'>example.copy</attribute>"
" <attribute name='accel'>&lt;Primary&gt;c</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>_Paste</attribute>"
" <attribute name='action'>example.paste</attribute>"
" <attribute name='accel'>&lt;Primary&gt;v</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>_Something</attribute>"
" <attribute name='action'>example.something</attribute>"
" </item>"
" </section>"
" </submenu>"
" <submenu>"
" <attribute name='label' translatable='yes'>_Choices</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Choice _A</attribute>"
" <attribute name='action'>example.choice</attribute>"
" <attribute name='target'>a</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Choice _B</attribute>"
" <attribute name='action'>example.choice</attribute>"
" <attribute name='target'>b</attribute>"
" </item>"
" </section>"
" </submenu>"
" <submenu>"
" <attribute name='label' translatable='yes'>_Other Choices</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Choice 1</attribute>"
" <attribute name='action'>example.choiceother</attribute>"
" <attribute name='target' type='i'>1</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Choice 2</attribute>"
" <attribute name='action'>example.choiceother</attribute>"
" <attribute name='target' type='i'>2</attribute>"
" </item>"
" </section>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Some Toggle</attribute>"
" <attribute name='action'>example.sometoggle</attribute>"
" </item>"
" </section>"
" </submenu>"
" <submenu>"
" <attribute name='label' translatable='yes'>_Help</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_About</attribute>"
" <attribute name='action'>example.about</attribute>"
" </item>"
" </section>"
" </submenu>"
" </menu>"
"</interface>";
try
{
m_refBuilder->add_from_string(ui_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building menus failed: " << ex.what();
}
//Get the menubar and add it to a container widget:
Glib::RefPtr<Glib::Object> object =
m_refBuilder->get_object("menu-example");
Glib::RefPtr<Gio::Menu> gmenu =
Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
if(!gmenu)
g_warning("GMenu not found");
//Menubar:
Gtk::MenuBar* pMenubar = Gtk::manage(new Gtk::MenuBar(gmenu));
m_Box.pack_start(*pMenubar, Gtk::PACK_SHRINK);
//Create the toolbar and add it to a container widget:
Gtk::Toolbar* toolbar = Gtk::manage(new Gtk::Toolbar());
Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("document-new");
//We can't do this until we can break the ToolButton ABI: button->set_detailed_action_name("example.new");
gtk_actionable_set_detailed_action_name (GTK_ACTIONABLE (button->gobj()), "example.newstandard");
toolbar->add(*button);
button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("application-exit");
//We can't do this until we can break the ToolButton ABI: button->set_detailed_action_name("example.quit");
gtk_actionable_set_detailed_action_name (GTK_ACTIONABLE (button->gobj()), "example.quit");
toolbar->add(*button);
m_Box.pack_start(*toolbar, Gtk::PACK_SHRINK);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_menu_file_quit()
{
hide(); //Closes the main window to stop the app->run().
}
void ExampleWindow::on_menu_file_new_generic()
{
std::cout << "A File|New menu item was selected." << std::endl;
}
void ExampleWindow::on_menu_others()
{
std::cout << "A menu item was selected." << std::endl;
}
void ExampleWindow::on_menu_choices(const Glib::ustring& parameter)
{
//The radio action's state does not change automatically:
m_refChoice->change_state(parameter);
Glib::ustring message;
if(parameter == "a")
message = "Choice a was selected.";
else
message = "Choice b was selected";
std::cout << message << std::endl;
}
void ExampleWindow::on_menu_choices_other(int parameter)
{
//The radio action's state does not change automatically:
m_refChoiceOther->change_state(parameter);
Glib::ustring message;
if(parameter == 1)
message = "Choice 1 was selected.";
else
message = "Choice 2 was selected";
std::cout << message << std::endl;
}
void ExampleWindow::on_menu_toggle()
{
bool active = false;
m_refToggle->get_state(active);
//The toggle action's state does not change automatically:
m_refToggle->change_state(!active);
active = !active;
Glib::ustring message;
if(active)
message = "Toggle is active.";
else
message = "Toggle is not active";
std::cout << message << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="menu-example-popup"><title>Ejemplo de menú emergente</title>
<figure id="figure-menus-popup">
<title>Menú emergente</title>
<screenshot>
<graphic format="PNG" fileref="figures/menu_popup.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/menus/popup/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
virtual bool on_button_press_event(GdkEventButton* event);
void on_menu_file_popup_generic();
//Child widgets:
Gtk::Box m_Box;
Gtk::EventBox m_EventBox;
Gtk::Label m_Label;
Glib::RefPtr<Gtk::Builder> m_refBuilder;
Gtk::Menu* m_pMenuPopup;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_Box(Gtk::ORIENTATION_VERTICAL),
m_Label("Right-click to see the popup menu."),
m_pMenuPopup(0)
{
set_title("popup example");
set_default_size(200, 200);
add(m_Box);
//Add an event box that can catch button_press events:
m_Box.pack_start(m_EventBox);
m_EventBox.signal_button_press_event().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_press_event) );
m_EventBox.add(m_Label);
//Create actions:
//Fill menu:
Glib::RefPtr<Gio::SimpleActionGroup> refActionGroup =
Gio::SimpleActionGroup::create();
//File|New sub menu:
//These menu actions would normally already exist for a main menu, because a
//context menu should not normally contain menu items that are only available
//via a context menu.
refActionGroup->add_action("edit",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_popup_generic));
refActionGroup->add_action("process", //TODO: How to specify "<control>P" as an accelerator.
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_popup_generic));
refActionGroup->add_action("remove",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_popup_generic));
insert_action_group("examplepopup", refActionGroup);
m_refBuilder = Gtk::Builder::create();
//Layout the actions in a menubar and toolbar:
Glib::ustring ui_info =
"<interface>"
" <menu id='menu-examplepopup'>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Edit</attribute>"
" <attribute name='action'>examplepopup.edit</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Process</attribute>"
" <attribute name='action'>examplepopup.process</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Remove</attribute>"
" <attribute name='action'>examplepopup.remove</attribute>"
" </item>"
" </section>"
" </menu>"
"</interface>";
try
{
m_refBuilder->add_from_string(ui_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building menus failed: " << ex.what();
}
//Get the menu:
Glib::RefPtr<Glib::Object> object =
m_refBuilder->get_object("menu-examplepopup");
Glib::RefPtr<Gio::Menu> gmenu =
Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
if(!gmenu)
g_warning("GMenu not found");
m_pMenuPopup = new Gtk::Menu(gmenu);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_menu_file_popup_generic()
{
std::cout << "A popup menu item was selected." << std::endl;
}
bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
if( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) )
{
if(!m_pMenuPopup->get_attach_widget())
{
m_pMenuPopup->attach_to_widget(*this);
}
if(m_pMenuPopup)
m_pMenuPopup->popup(event->button, event->time);
return true; //It has been handled.
}
else
return false;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-toolpalette">
<title>ToolPalette</title>
<para>Una <classname>ToolPalette</classname> es similar a una <classname>Toolbar</classname>, pero puede contener una rejilla de elementos categorizados en grupos. El usuario puede ocultar o expandir cada grupo. Al igual que en una barra de herramientas, los elementos pueden aparecer sólo como iconos, como sólo texto, o en forma de iconos con el texto.</para>
<para>Los elementos del <classname>ToolPalette</classname> pueden arrastrarse o simplemente activarse. Por ejemplo, el usuario tal vez arrastre objetos a un lienzo para crear elementos nuevos allí. O bien, el usuario podría pulsar sobre un elemento para activar un determinado tamaño de pincel en una aplicación de dibujo.</para>
<para lang="en"><classname>ToolItemGroup</classname>s should be added to the tool palette via the base class's <function>Gtk::Container::add()</function> method, for instance like so:
</para>
<para>
<programlisting>
Gtk::ToolItemGroup* group_brushes =
Gtk::manage(new Gtk::ToolItemGroup("Brushes"));
m_ToolPalette.add(*group_brushes);
</programlisting>
</para>
<para>Entonces podrá añadir varios <classname>Gtk::ToolItem</classname> al grupo. Por ejemplo, así:</para>
<para>
<programlisting>
Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton(icon, "Big"));
button->set_tooltip_text("Big Brush);
group_brushes->insert(*button);
</programlisting>
</para>
<para>Entonces podrá manejar la señal <literal>clicked</literal> del <classname>ToolButton</classname>. Alternativamente puede permitir que se arrastre el elemento a otro widget, llamando a <methodname>Gtk::ToolPalette::add_drag_dest()</methodname> y después usando <methodname>Gtk::ToolPalette::get_drag_item()</methodname> en el manejador de la señal <literal>drag_data_received</literal> del otro widget.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToolPalette.html">ToolPalette Reference</ulink></para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToolItemGroup.html">ToolItemGroup Reference</ulink></para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToolItem.html">ToolItem Reference</ulink></para>
<sect1 id="toolpallete-dranganddrop">
<title>Arrastrar y soltar</title>
<para lang="en">Call <methodname>add_drag_dest()</methodname> to allow items or groups to be dragged from the tool palette to a particular destination widget. You can then use <methodname>get_drag_item()</methodname> to discover which ToolItem or ToolItemGroup is being dragged. You can use <literal>dynamic_cast</literal> to discover whether it is an item or a group. For instance, you might use this in your <literal>drag_data_received</literal> signal handler, to add a dropped item, or to show a suitable icon while dragging.</para>
<para>Consulte el capítulo <link linkend="chapter-draganddrop">Arrastrar y soltar</link> para obtener información general acerca de arrastrar y soltar con gtkmm.</para>
</sect1>
<sect1 id="toolpalette-example"><title>Ejemplo de ToolPalette</title>
<para>Este ejemplo añade una <classname>ToolPalette</classname> y una <classname>DrawingArea</classname> a una ventana y le permite al usuario arrastrar iconos de la paleta de herramientas al área de dibujo. La paleta de herramientas contiene varios grupos de elementos. Las cajas combinadas le permiten al usuario cambiar el estilo y la orientación de la paleta de herramientas.</para>
<figure id="figure-toolpalette">
<title>ToolPalette</title>
<screenshot>
<graphic format="PNG" fileref="figures/toolpalette.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/toolpalette/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>canvas.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_CANVAS_H
#define GTKMM_EXAMPLE_CANVAS_H
#include <gtkmm.h>
// This little canvas class is only here
// because gtkmm does not have a canvas class yet.
// Applications should probably use GooCanvas::Canvas (goocanvasmm) instead.
class Canvas : public Gtk::DrawingArea
{
public:
Canvas();
virtual ~Canvas();
private:
class CanvasItem
{
public:
CanvasItem(Gtk::Widget* canvas, Gtk::ToolButton* button, double x, double y)
{
Glib::ustring icon_name(button->get_icon_name());
if (icon_name.empty())
icon_name = button->get_label();
Glib::RefPtr<Gtk::IconTheme> icon_theme = Gtk::IconTheme::get_for_screen(canvas->get_screen());
int width = 0;
int height = 0; //ignored
Gtk::IconSize::lookup(Gtk::ICON_SIZE_DIALOG, width, height);
this->pixbuf = icon_theme->load_icon(icon_name, width, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);
this->x = x;
this->y = y;
}
Glib::RefPtr<Gdk::Pixbuf> pixbuf;
double x, y;
};
void item_draw(const CanvasItem *item,
const Cairo::RefPtr<Cairo::Context>& cr,
bool preview);
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
virtual void on_drag_data_received(const Glib::RefPtr<Gdk::DragContext>& context,
int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time);
virtual bool on_drag_motion(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, guint time);
virtual bool on_drag_drop(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, guint time);
virtual void on_drag_leave(const Glib::RefPtr<Gdk::DragContext>& context, guint time);
bool m_drag_data_requested_for_drop; //So we know what to do in on_drag_data_received().
CanvasItem* m_drop_item;
typedef std::vector<CanvasItem*> type_vec_items;
type_vec_items m_canvas_items;
};
#endif //GTKMM_EXAMPLE_CANVAS_H
</programlisting>
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
#include "canvas.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
private:
void load_icon_items();
void load_toggle_items();
void load_special_items();
//Signal handlers:
void on_combo_orientation_changed();
void on_combo_style_changed();
//Tree model columns:
class ModelColumnsOrientation : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumnsOrientation()
{ add(m_col_value); add(m_col_name); }
Gtk::TreeModelColumn<Gtk::Orientation> m_col_value;
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumnsOrientation m_ColumnsOrientation;
//Tree model columns:
class ModelColumnsStyle : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumnsStyle()
{ add(m_col_value); add(m_col_name); }
Gtk::TreeModelColumn<int> m_col_value; //We use int to also allow -1
Gtk::TreeModelColumn<Glib::ustring> m_col_name;
};
ModelColumnsStyle m_ColumnsStyle;
//Child widgets:
Gtk::Box m_VBox;
Gtk::Box m_HBox;
Gtk::ComboBox m_ComboOrientation;
Glib::RefPtr<Gtk::ListStore> m_refTreeModelOrientation;
Gtk::ComboBox m_ComboStyle;
Glib::RefPtr<Gtk::ListStore> m_refTreeModelStyle;
Gtk::ToolPalette m_ToolPalette;
Gtk::ScrolledWindow m_ScrolledWindowPalette;
Gtk::ScrolledWindow m_ScrolledWindowCanvas;
Canvas m_Canvas;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
void ExampleWindow::load_icon_items()
{
Glib::RefPtr<Gtk::IconTheme> icon_theme = Gtk::IconTheme::get_for_screen(get_screen());
typedef std::vector<Glib::ustring> type_stringvec;
type_stringvec icon_names = icon_theme->list_icons();
// Obtain the names of all contexts, and the icon names per context.
type_stringvec contexts = icon_theme->list_contexts();
std::sort(contexts.begin(), contexts.end());
int requested_icon_size = 0;
int requested_icon_height = 0; //ignored
Gtk::IconSize::lookup(Gtk::ICON_SIZE_BUTTON, requested_icon_size, requested_icon_height);
const guint max_icons_per_group = 10;
for (type_stringvec::const_iterator iter = contexts.begin(); iter != contexts.end(); ++iter)
{
const Glib::ustring context_name = *iter;
Gtk::ToolItemGroup* group =
Gtk::manage(new Gtk::ToolItemGroup(context_name));
m_ToolPalette.add(*group);
// Iterate through the icon names, populating the ToolItemGroup as appropriate.
type_stringvec icon_names = icon_theme->list_icons(context_name);
std::sort(icon_names.begin(), icon_names.end());
guint icons_count = 0;
for (type_stringvec::const_iterator iconiter = icon_names.begin(); iconiter != icon_names.end(); ++iconiter)
{
const Glib::ustring icon_name = *iconiter;
Glib::RefPtr<Gdk::Pixbuf> pixbuf;
try
{
pixbuf = icon_theme->load_icon(icon_name, requested_icon_size, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);
}
catch (const Gtk::IconThemeError& /* ex */)
{
// Gtk::IconTheme::list_icons() may return some names of icons
// that can't be loaded.
continue;
}
// Skip large icons, just to make the ToolPalette look better.
if (pixbuf->get_width() > 2*requested_icon_size ||
pixbuf->get_height() > 2*requested_icon_size)
continue;
Gtk::Image* image = Gtk::manage(new Gtk::Image(pixbuf));
Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton(*image, icon_name));
button->set_tooltip_text(icon_name);
button->set_is_important();
group->insert(*button);
// Prevent us having an insane number of icons:
++icons_count;
if(icons_count >= max_icons_per_group)
break;
}
}
}
void ExampleWindow::load_toggle_items()
{
Gtk::ToolItemGroup* group =
Gtk::manage(new Gtk::ToolItemGroup("Radio Item"));
m_ToolPalette.add(*group);
Gtk::RadioToolButton::Group radio_group;
for(int i = 1; i <= 10; ++i)
{
const Glib::ustring label = Glib::ustring::compose("#%1", i);
Gtk::RadioToolButton* button = Gtk::manage(new Gtk::RadioToolButton());
button->set_group(radio_group);
button->set_label(label);
group->insert(*button);
}
}
static Gtk::ToolItem* create_entry_item(const Glib::ustring& text)
{
Gtk::Entry* entry = Gtk::manage(new Gtk::Entry());
entry->set_text(text);
entry->set_width_chars(5);
Gtk::ToolItem* item = Gtk::manage(new Gtk::ToolItem());
item->add(*entry);
return item;
}
void ExampleWindow::load_special_items()
{
Gtk::ToolItemGroup* group = Gtk::manage(new Gtk::ToolItemGroup());
Gtk::Button *label_button = Gtk::manage(new Gtk::Button("Advanced Features"));
label_button->show();
group->set_label_widget(*label_button);
m_ToolPalette.add(*group);
Gtk::ToolItem* item = create_entry_item ("homogeneous=false");
group->insert(*item);
//TODO: Add Gtk::Container::set_child_property().
gtk_container_child_set (GTK_CONTAINER (group->gobj()), GTK_WIDGET (item->gobj()),
"homogeneous", FALSE, NULL);
item = create_entry_item ("homogeneous=FALSE, expand=TRUE");
group->insert(*item);
gtk_container_child_set (GTK_CONTAINER (group->gobj()), GTK_WIDGET (item->gobj()),
"homogeneous", FALSE, "expand", TRUE,
NULL);
item = create_entry_item ("homogeneous=FALSE, expand=TRUE, fill=FALSE");
group->insert(*item);
gtk_container_child_set (GTK_CONTAINER (group->gobj()), GTK_WIDGET (item->gobj()),
"homogeneous", FALSE, "expand", TRUE,
"fill", FALSE, NULL);
item = create_entry_item ("homogeneous=FALSE, expand=TRUE, new-row=TRUE");
group->insert(*item);
gtk_container_child_set (GTK_CONTAINER (group->gobj()), GTK_WIDGET (item->gobj()),
"homogeneous", FALSE, "expand", TRUE,
"new-row", TRUE, NULL);
Gtk::ToolButton *button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("go-up");
button->set_tooltip_text("Show on vertical palettes only");
group->insert(*button);
button->set_visible_horizontal(false);
button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("go-next");
button->set_tooltip_text("Show on horizontal palettes only");
group->insert(*button);
button->set_visible_vertical(false);
button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("edit-delete");
button->set_tooltip_text("Do not show at all");
button->set_no_show_all();
group->insert(*button);
button->set_visible_vertical(false);
button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("view-fullscreen");
button->set_tooltip_text("Expanded this item");
group->insert(*button);
gtk_container_child_set (GTK_CONTAINER (group->gobj()), GTK_WIDGET (button->gobj()),
"homogeneous", FALSE,
"expand", TRUE,
NULL);
button = Gtk::manage(new Gtk::ToolButton());
button->set_icon_name("help-contents");
button->set_tooltip_text("A regular item");
group->insert(*button);
}
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 6),
m_HBox(Gtk::ORIENTATION_HORIZONTAL, 6)
{
set_title("Gtk::ToolPalette example");
set_size_request(600, 600);
set_border_width(6);
add(m_VBox);
//The Orientation ComboBox:
m_refTreeModelOrientation = Gtk::ListStore::create(m_ColumnsOrientation);
Gtk::TreeModel::Row row = *(m_refTreeModelOrientation->append());
row[m_ColumnsOrientation.m_col_value] = Gtk::ORIENTATION_HORIZONTAL;
row[m_ColumnsOrientation.m_col_name] = "Horizontal";\
row = *(m_refTreeModelOrientation->append());
row[m_ColumnsOrientation.m_col_value] = Gtk::ORIENTATION_VERTICAL;
row[m_ColumnsOrientation.m_col_name] = "Vertical";
m_ComboOrientation.set_model(m_refTreeModelOrientation);
m_VBox.pack_start(m_ComboOrientation, Gtk::PACK_SHRINK);
m_ComboOrientation.pack_start(m_ColumnsOrientation.m_col_name);
m_ComboOrientation.signal_changed().connect(
sigc::mem_fun(*this, &ExampleWindow::on_combo_orientation_changed) );
m_ComboOrientation.set_active(row);
//The Style ComboBox:
m_refTreeModelStyle = Gtk::ListStore::create(m_ColumnsStyle);
row = *(m_refTreeModelStyle->append());
row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_TEXT;
row[m_ColumnsStyle.m_col_name] = "Text";\
row = *(m_refTreeModelStyle->append());
row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_BOTH;
row[m_ColumnsStyle.m_col_name] = "Both";
row = *(m_refTreeModelStyle->append());
row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_BOTH_HORIZ;
row[m_ColumnsStyle.m_col_name] = "Both: Horizontal";
row = *(m_refTreeModelStyle->append());
row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_ICONS;
row[m_ColumnsStyle.m_col_name] = "Icons";
row = *(m_refTreeModelStyle->append());
row[m_ColumnsStyle.m_col_value] = -1; // A custom meaning for this demo.
row[m_ColumnsStyle.m_col_name] = "Default";
m_ComboStyle.set_model(m_refTreeModelStyle);
m_VBox.pack_start(m_ComboStyle, Gtk::PACK_SHRINK);
m_ComboStyle.pack_start(m_ColumnsStyle.m_col_name);
m_ComboStyle.signal_changed().connect(
sigc::mem_fun(*this, &ExampleWindow::on_combo_style_changed) );
m_ComboStyle.set_active(row);
//Add and fill the ToolPalette:
load_icon_items();
load_toggle_items();
load_special_items();
m_VBox.pack_start(m_HBox, Gtk::PACK_EXPAND_WIDGET);
m_ScrolledWindowPalette.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
m_ScrolledWindowPalette.set_border_width(6);
m_ScrolledWindowPalette.add(m_ToolPalette);
m_HBox.pack_start(m_ScrolledWindowPalette);
on_combo_orientation_changed();
m_ScrolledWindowCanvas.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);
m_ScrolledWindowCanvas.set_border_width(6);
m_ScrolledWindowCanvas.add(m_Canvas);
m_ScrolledWindowCanvas.set_size_request(200, -1);
m_HBox.pack_start(m_ScrolledWindowCanvas);
m_ToolPalette.add_drag_dest(m_Canvas,
Gtk::DEST_DEFAULT_HIGHLIGHT, Gtk::TOOL_PALETTE_DRAG_ITEMS, Gdk::ACTION_COPY);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_combo_orientation_changed()
{
Gtk::TreeModel::iterator iter = m_ComboOrientation.get_active();
if(!iter)
return;
Gtk::TreeModel::Row row = *iter;
const Gtk::Orientation value = row[m_ColumnsOrientation.m_col_value];
m_ToolPalette.set_orientation(value);
if(value == Gtk::ORIENTATION_HORIZONTAL)
m_ScrolledWindowPalette.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER);
else
m_ScrolledWindowPalette.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
}
void ExampleWindow::on_combo_style_changed()
{
Gtk::TreeModel::iterator iter = m_ComboStyle.get_active();
if(!iter)
return;
Gtk::TreeModel::Row row = *iter;
const int value = row[m_ColumnsStyle.m_col_value];
if(value == -1)
m_ToolPalette.unset_style();
else
m_ToolPalette.set_style((Gtk::ToolbarStyle)value);
}
</programlisting>
<para lang="en">File: <filename>canvas.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "canvas.h"
#include <iostream>
Canvas::Canvas()
: m_drag_data_requested_for_drop(false),
m_drop_item(0)
{
set_app_paintable();
}
Canvas::~Canvas()
{
while(!m_canvas_items.empty())
{
type_vec_items::iterator iter = m_canvas_items.begin();
CanvasItem* item = *iter;
delete item;
m_canvas_items.erase(iter);
}
delete m_drop_item;
}
void Canvas::item_draw(const CanvasItem *item,
const Cairo::RefPtr<Cairo::Context>& cr,
bool preview)
{
if(!item || !item->pixbuf)
return;
const double cx = item->pixbuf->get_width();
const double cy = item->pixbuf->get_height();
Gdk::Cairo::set_source_pixbuf(cr,
item->pixbuf,
item->x - cx * 0.5, item->y - cy * 0.5);
if(preview)
cr->paint_with_alpha(0.6);
else
cr->paint();
}
bool Canvas::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
cr->set_source_rgb(1.0, 1.0, 1.0);
const Gtk::Allocation allocation = get_allocation();
cr->rectangle(0, 0, allocation.get_width(), allocation.get_height());
cr->fill();
for(type_vec_items::iterator iter = m_canvas_items.begin();
iter != m_canvas_items.end(); ++iter )
{
item_draw(*iter, cr, false);
}
if(m_drop_item)
item_draw (m_drop_item, cr, true);
return true;
}
bool Canvas::on_drag_motion(const Glib::RefPtr<Gdk::DragContext>& context,
int x, int y, guint time)
{
m_drag_data_requested_for_drop = false; //It's for drag-motion instead.
if(m_drop_item)
{
// We already have a drop indicator so just update its position.
m_drop_item->x = x;
m_drop_item->y = y;
queue_draw();
context->drag_status(Gdk::ACTION_COPY, time);
}
else
{
// Request DnD data for creating a drop indicator.
// This will cause on_drag_data_received() to be called.
const Glib::ustring target = drag_dest_find_target(context);
if (target.empty())
return false;
drag_get_data(context, target, time);
}
Gtk::DrawingArea::on_drag_motion(context, x, y, time);
return true;
}
void Canvas::on_drag_data_received(const Glib::RefPtr<Gdk::DragContext>& context,
int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time)
{
// Find the tool button which is the source of this DnD operation.
Gtk::Widget* widget = drag_get_source_widget(context);
Gtk::ToolPalette* drag_palette = dynamic_cast<Gtk::ToolPalette*>(widget);
while(widget && !drag_palette)
{
widget = widget->get_parent();
drag_palette = dynamic_cast<Gtk::ToolPalette*>(widget);
}
Gtk::ToolItem* drag_item = 0;
if(drag_palette)
drag_item = drag_palette->get_drag_item(selection_data);
// Create a drop indicator when a tool button was found:
Gtk::ToolButton* button = dynamic_cast<Gtk::ToolButton*>(drag_item);
if(!button)
return;
delete m_drop_item;
m_drop_item = 0;
try
{
CanvasItem* item = new CanvasItem(this, button, x, y);
if(m_drag_data_requested_for_drop)
{
m_canvas_items.push_back(item);
// Signal that the item was accepted and then redraw.
context->drag_finish(true /* success */, false /* del */, time);
}
else
{
m_drop_item = item;
// We are getting this data due to a request in drag_motion,
// rather than due to a request in drag_drop, so we are just
// supposed to call gdk_drag_status (), not actually paste in
// the data.
context->drag_status(Gdk::ACTION_COPY, time);
}
queue_draw();
}
catch (const Gtk::IconThemeError& ex)
{
std::cerr << "IconThemeError: " << ex.what() << std::endl;
}
Gtk::DrawingArea::on_drag_data_received(context, x, y, selection_data, info, time);
}
bool Canvas::on_drag_drop(const Glib::RefPtr<Gdk::DragContext>& context, int /* x */, int /* y */, guint time)
{
// Request DnD data for creating a dopped item.
// This will cause on_drag_data_received() to be called.
const Glib::ustring target = drag_dest_find_target(context);
if (target.empty())
return false;
m_drag_data_requested_for_drop = true;
drag_get_data(context, target, time);
return true;
}
void Canvas::on_drag_leave(const Glib::RefPtr<Gdk::DragContext>& context, guint time)
{
//This signal is emitted to clean up the item used for drag-motion,
//either when the cursor moves out of the widget or when we drop.
if(!m_drop_item)
return;
delete m_drop_item;
m_drop_item = 0;
queue_draw();
Gtk::DrawingArea::on_drag_leave(context, time);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect1>
</chapter>
<chapter id="chapter-adjustment">
<title>Ajustes</title>
<para><application>gtkmm</application> tiene varios widgets que pueden ajustarse visualmente usando el ratón o el teclado, como los widgets <classname>Range</classname> (descritos en la sección <link linkend="chapter-range-widgets">Widgets de rango</link>). También hay algunos widgets que muestran una parte ajustable de un área más grande, como el widget <classname>Viewport</classname>. Estos widgets tienen objetos <classname>Gtk::Adjustment</classname> que expresan esta parte común de sus API.</para>
<para>Para que las aplicaciones puedan reaccionar a los cambios, por ejemplo, cuando un usuario mueve una barra de desplazamiento, <classname>Gtk::Adjustment</classname> tiene una señal <literal>value_changed</literal>.Entonces, usar el método <methodname>get_value()</methodname> para descubrir el valor nuevo.</para>
<sect1 id="sec-creating-adjustment">
<title>Crear un ajuste</title>
<para lang="en">
The <classname>Gtk::Adjustment</classname> is created by its
<methodname>create()</methodname> method which is as follows:
</para>
<programlisting>Glib::RefPtr<Gtk::Adjustment> Gtk::Adjustment::create(
double value,
double lower,
double upper,
double step_increment = 1,
double page_increment = 10,
double page_size = 0);</programlisting>
<para lang="en">
The <parameter>value</parameter> argument is the initial value of the
adjustment, usually corresponding to the topmost or leftmost position of an
adjustable widget. The <parameter>lower</parameter> and
<parameter>upper</parameter> arguments specify the possible range of values
which the adjustment can hold. The
<parameter>step_increment</parameter> argument specifies the smaller of
the two increments by which the user can change the value, while the
<parameter>page_increment</parameter> is the larger one. The
<parameter>page_size</parameter> argument usually corresponds somehow to
the visible area of a panning widget. The <parameter>upper</parameter> argument
is used to represent the bottommost or rightmost coordinate in a panning
widget's child.
<!-- TODO: Investigate the upper argument properly. There was some unclear stuff about it not always being the upper value. -->
</para>
</sect1>
<sect1 id="sec-adjustments-easy">
<title>Usar ajustes de la manera fácil</title>
<para>Los widgets ajustables pueden dividirse en aquellos que usan y requieren unidades específicas para estos valores, y aquellos que los tratan como números arbitrarios.</para>
<para>El grupo que trata los valores como números arbitrarios incluye los widgets <classname>Range</classname> (<classname>Scrollbar</classname> y <classname>Scale</classname>), el widget <classname>ScaleButton</classname> y el widget <classname>SpinButton</classname>. Típicamente, el usuario «ajusta» directamente a estos widgets mediante el teclado o el ratón. Tratarán a los valores <parameter>lower</parameter> y <parameter>upper</parameter> de un ajuste como un rango dentro del cual el usuario podrá manipular el <parameter>value</parameter> del ajuste. De manera predeterminada, sólo modificarán el <parameter>value</parameter> de un ajuste.</para>
<para>El otro grupo incluye al widget <classname>Viewport</classname> y al widget <classname>ScrolledWindow</classname>. Todos estos widgets usan valores de píxel para sus ajustes. Típicamente, estos también se ajustan indirectamente usando barras de desplazamiento. A pesar de que todos los widgets que usan ajustes pueden crear los suyos o usar los que se les proporcionan, generalmente querrá dejarle a esta categoría particular de widgets crear sus propios ajustes.</para>
<para>Si comparte un objeto de ajuste entre una barra de desplazamiento y un widget «TextView», manipular la barra de desplazamiento ajustará automágicamente al widget «TextView». Puede establecerlo así:</para>
<programlisting>// creates its own adjustments
Gtk::TextView textview;
// uses the newly-created adjustment for the scrollbar as well
Gtk::Scrollbar vscrollbar (textview.get_vadjustment(), Gtk::ORIENTATION_VERTICAL);</programlisting>
</sect1>
<sect1 id="sec-adjustment-internals">
<title>Interioridades del ajuste</title>
<para>Hasta aquí está todo bien, pero ¿y si quiere crear sus propios manejadores para responder cuando el usuario ajusta un widget <classname>Range</classname> o un <classname>SpinButton</classname>? Para acceder al valor de un <classname>Gtk::Adjustment</classname>, puede usar los métodos <methodname>get_value()</methodname> y <methodname>set_value()</methodname>:</para>
<para>Como se mencionó anteriormente, <classname>Gtk::Adjustment</classname> puede emitir señales. Así es, por supuesto, cómo suceden las actualizaciones automáticamente cuando comparte un objeto <classname>Adjustment</classname> entre una <classname>Scrollbar</classname> y otro widget ajustable; todos los widgets ajustables conectan manejadores de señales a la señal <literal>value_changed</literal> de sus ajustes, como también puede su programa.</para>
<para>Entonces, por ejemplo, si tiene un widget <classname>Scale</classname>, y quiere cambiar la rotación de una imagen cuando su valor cambia, podría crear un manejador de señales de esta forma:</para>
<programlisting>void cb_rotate_picture (MyPicture* picture)
{
picture->set_rotation(adj->get_value());
...</programlisting>
<para>y conectarlo al ajuste del widget de escala así:</para>
<programlisting>adj->signal_value_changed().connect(sigc::bind<MyPicture*>(sigc::mem_fun(*this,
&cb_rotate_picture), picture));</programlisting>
<para>¿Qué pasa si un widget reconfigura los campos <parameter>upper</parameter> o <parameter>lower</parameter> de su <classname>Adjustment</classname>, como cuando un usuario le añade más texto a un widget de texto? En este caso, emite la señal <literal>changed</literal>.</para>
<para>Los widgets <classname>Range</classname> típicamente conectan un manejador a esta señal, que cambia su apariencia para reflejar el cambio: por ejemplo, el tamaño de un control deslizante en una barra de desplazamiento crecerá o se encogerá de manera inversamente proporcional a la diferencia entre los valores <parameter>lower</parameter> y <parameter>upper</parameter> de su <classname>Adjustment</classname>.</para>
<para>Probablemente nunca necesite adjuntarle un manejador a esta señal, a menos que esté escribiendo un nuevo tipo de widget de rango.</para>
<programlisting>adjustment->signal_changed();</programlisting>
</sect1>
</chapter>
<chapter id="chapter-widgets-without-xwindows">
<title>Widgets sin X-Windows</title>
<para>Algunos widgets no tienen una X-Window asociada, por lo que no reciben eventos de X. Esto significa que las señales descritas en la sección <link linkend="sec-xeventsignals">Señales de eventos de X</link> no se emitirán. Si quiere capturar eventos para estos widgets, puede usar un contenedor especial llamado <classname>Gtk::EventBox</classname>, que se describe en la sección <link linkend="sec-eventbox">EventBox</link>.</para>
<para>Aquí hay una lista de estos widgets</para>
<programlisting>Gtk::Alignment
Gtk::Arrow
Gtk::AspectFrame
Gtk::Bin
Gtk::Box
Gtk::Button
Gtk::CheckButton
Gtk::Fixed
Gtk::Frame
Gtk::Grid
Gtk::Image
Gtk::Label
Gtk::MenuItem
Gtk::Notebook
Gtk::Paned
Gtk::RadioButton
Gtk::Range
Gtk::ScrolledWindow
Gtk::Separator
Gtk::Table (marcado como obsoleto en la versión de <application>gtkmm</application> 3.4)
Gtk::Toolbar</programlisting>
<para>Estos widgets se usan principalmente para decorar o distribuir, por lo que a menudo no necesitará capturar sus eventos. Están destinados a no tener X-Window para mejorar su desempeño.</para>
<sect1 id="sec-eventbox">
<title>EventBox</title>
<para>Algunos widgets de <application>gtkmm</application> no tienen X-Windows asociadas; dibujan en las ventanas de sus padres. Es por esto que no pueden recibir eventos. Además, si tienen el tamaño incorrecto, no se recortan, por lo que puede aparecer sobrescritura errónea, etc. Para recibir eventos en uno de estos widgets, puede ponerlo dentro de un widget <classname>EventBox</classname> y después llamar a <methodname>Gtk::Widget::set_events()</methodname> en la «EventBox» antes de mostrarlo.</para>
<para>A pesar de que el nombre <classname>EventBox</classname> hace énfasis en el método de manipulación de eventos, el widget también puede usarse para recortar (y para más cosas; consulte el ejemplo más abajo).</para>
<!--
<para>TODO: Why don't they have X Windows - explain clipping.
Also, how does this affect platform such as Windows and MacOS that don't use X.
</para>
-->
<para>El constructor de <classname>Gtk::EventBox</classname> es:</para>
<programlisting>Gtk::EventBox();</programlisting>
<para>Se puede agregar un widget hijo a <classname>EventBox</classname> utilizando:</para>
<programlisting>event_box.add(child_widget);</programlisting>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1EventBox.html">Reference</ulink></para>
<sect2 id="eventbox-example">
<title>Ejemplo</title>
<para>El siguiente ejemplo demuestra ambos usos de una <classname>EventBox</classname>: se crea una etiqueta que se adjunta a un pequeño cuadro, configurada de manera que una pulsación del ratón en ella hace que el programa termine. Redimensionar la ventana revelará partes variables de la etiqueta.</para>
<figure id="figure-eventbox">
<title>EventBox</title>
<screenshot>
<graphic format="PNG" fileref="figures/eventbox.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/eventbox?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
virtual bool on_eventbox_button_press(GdkEventButton* event);
//Child widgets:
Gtk::EventBox m_EventBox;
Gtk::Label m_Label;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_Label("Click here to quit, quit, quit, quit, quit")
{
set_title ("EventBox");
set_border_width(10);
add(m_EventBox);
m_EventBox.add(m_Label);
//Clip the label short:
set_default_size(110, 20);
m_Label.set_size_request(110, 20);
m_Label.set_ellipsize(Pango::ELLIPSIZE_END);
//And bind an action to it:
m_EventBox.set_events(Gdk::BUTTON_PRESS_MASK);
m_EventBox.signal_button_press_event().connect(
sigc::mem_fun(*this, &ExampleWindow::on_eventbox_button_press) );
m_EventBox.set_tooltip_text("Click me!");
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
bool ExampleWindow::on_eventbox_button_press(GdkEventButton*)
{
hide();
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-dialogs">
<title>Diálogos</title>
<para>Los diálogos se usan como ventanas secundarias, para proporcionar información específica o hacer preguntas. Las ventanas <classname>Gtk::Dialog</classname> contienen algunos widgets pre-empaquetados para asegurar la consistencia, y un método <methodname>run()</methodname> que se bloquea hasta que el usuario cierra el diálogo.</para>
<para>Hay varias clases <classname>Dialog</classname> derivadas que podría encontrar útiles. <classname>Gtk::MessageDialog</classname> se usa para las notificaciones más simples. Pero en otras ocasiones, tal vez necesite derivar su propia clase de diálogo para proporcionar una funcionalidad más compleja.</para>
<para>Para empaquetar widgets en un diálogo personalizado, debe empaquetarlos en la <classname>Gtk::Box</classname>, disponible a través de <methodname>get_content_area()</methodname>. Para simplemente añadirle un <classname>Button</classname> a la parte inferior del <classname>Dialog</classname>, puede usar el método <methodname>add_button()</methodname>.</para>
<para>El método <methodname>run()</methodname> devuelve un <literal>int</literal>. Este podría ser el valor del <literal>Gtk::ResponseType</literal> si el usuario cerró el diálogo pulsando un botón estándar, o podría ser la respuesta personalizada que ha especificado cuando usó <methodname>add_button()</methodname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Dialog.html">Reference</ulink></para>
<sect1 id="sec-dialogs-messagedialog"><title>MessageDialog</title>
<para><classname>MessageDialog</classname> es una clase de conveniencia, usada para crear diálogos de mensajes estándar y simples, con un mensaje, un icono, y botones para la respuesta del usuario. Puede especificar el tipo de mensaje y el texto en el constructor, así como los botones estándar a través de la enum <literal>Gtk::ButtonsType</literal>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1MessageDialog.html">Reference</ulink></para>
<sect2 id="messagedialog-example">
<title>Ejemplo</title>
<figure id="figure-dialogs-messagedialog">
<title>MessageDialog</title>
<screenshot>
<graphic format="PNG" fileref="figures/dialogs_messagedialog.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/messagedialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_info_clicked();
void on_button_question_clicked();
//Child widgets:
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Info, m_Button_Question;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/messagedialog.h>
#include <iostream>
ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Info("Show Info MessageDialog"),
m_Button_Question("Show Question MessageDialog")
{
set_title("Gtk::MessageDialog example");
add(m_ButtonBox);
m_ButtonBox.pack_start(m_Button_Info);
m_Button_Info.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_info_clicked) );
m_ButtonBox.pack_start(m_Button_Question);
m_Button_Question.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_question_clicked) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_info_clicked()
{
Gtk::MessageDialog dialog(*this, "This is an INFO MessageDialog");
dialog.set_secondary_text(
"And this is the secondary text that explains things.");
dialog.run();
}
void ExampleWindow::on_button_question_clicked()
{
Gtk::MessageDialog dialog(*this, "This is a QUESTION MessageDialog",
false /* use_markup */, Gtk::MESSAGE_QUESTION,
Gtk::BUTTONS_OK_CANCEL);
dialog.set_secondary_text(
"And this is the secondary text that explains things.");
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::cout << "OK clicked." << std::endl;
break;
}
case(Gtk::RESPONSE_CANCEL):
{
std::cout << "Cancel clicked." << std::endl;
break;
}
default:
{
std::cout << "Unexpected button clicked." << std::endl;
break;
}
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-dialogs-filechooserdialog"><title>FileChooserDialog</title>
<para>El <classname>FileChooserDialog</classname> es adecuado para usarse con elementos «abrir» o «guardar» en el menú.</para>
<para>La mayoría de los métodos miembros útiles de esta clase están en realidad en la clase base <classname>Gtk::FileChooser</classname>.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FileChooserDialog.html">Reference</ulink></para>
<sect2 id="filechooserdialog-example">
<title>Ejemplo</title>
<figure id="figure-dialogs-filechooser">
<title>Selector de archivos</title>
<screenshot>
<graphic format="PNG" fileref="figures/dialogs_filechooser.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/filechooserdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_file_clicked();
void on_button_folder_clicked();
//Child widgets:
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_File, m_Button_Folder;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
m_Button_File("Choose File"),
m_Button_Folder("Choose Folder")
{
set_title("Gtk::FileSelection example");
add(m_ButtonBox);
m_ButtonBox.pack_start(m_Button_File);
m_Button_File.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_file_clicked) );
m_ButtonBox.pack_start(m_Button_Folder);
m_Button_Folder.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_folder_clicked) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_folder_clicked()
{
Gtk::FileChooserDialog dialog("Please choose a folder",
Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
dialog.set_transient_for(*this);
//Add response buttons the the dialog:
dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
dialog.add_button("Select", Gtk::RESPONSE_OK);
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::cout << "Select clicked." << std::endl;
std::cout << "Folder selected: " << dialog.get_filename()
<< std::endl;
break;
}
case(Gtk::RESPONSE_CANCEL):
{
std::cout << "Cancel clicked." << std::endl;
break;
}
default:
{
std::cout << "Unexpected button clicked." << std::endl;
break;
}
}
}
void ExampleWindow::on_button_file_clicked()
{
Gtk::FileChooserDialog dialog("Please choose a file",
Gtk::FILE_CHOOSER_ACTION_OPEN);
dialog.set_transient_for(*this);
//Add response buttons the the dialog:
dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
dialog.add_button("_Open", Gtk::RESPONSE_OK);
//Add filters, so that only certain file types can be selected:
Glib::RefPtr<Gtk::FileFilter> filter_text = Gtk::FileFilter::create();
filter_text->set_name("Text files");
filter_text->add_mime_type("text/plain");
dialog.add_filter(filter_text);
Glib::RefPtr<Gtk::FileFilter> filter_cpp = Gtk::FileFilter::create();
filter_cpp->set_name("C/C++ files");
filter_cpp->add_mime_type("text/x-c");
filter_cpp->add_mime_type("text/x-c++");
filter_cpp->add_mime_type("text/x-c-header");
dialog.add_filter(filter_cpp);
Glib::RefPtr<Gtk::FileFilter> filter_any = Gtk::FileFilter::create();
filter_any->set_name("Any files");
filter_any->add_pattern("*");
dialog.add_filter(filter_any);
//Show the dialog and wait for a user response:
int result = dialog.run();
//Handle the response:
switch(result)
{
case(Gtk::RESPONSE_OK):
{
std::cout << "Open clicked." << std::endl;
//Notice that this is a std::string, not a Glib::ustring.
std::string filename = dialog.get_filename();
std::cout << "File selected: " << filename << std::endl;
break;
}
case(Gtk::RESPONSE_CANCEL):
{
std::cout << "Cancel clicked." << std::endl;
break;
}
default:
{
std::cout << "Unexpected button clicked." << std::endl;
break;
}
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-color-selection-dialog"><title>ColorChooserDialog</title>
<para>El <classname>ColorChooserDialog</classname> le permite al usuario elegir un color. El <classname>ColorButton</classname> abre un diálogo de selección de color cuando se pulsa.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ColorChooserDialog.html">Reference</ulink></para>
<sect2 id="colorchooserdialog-example">
<title>Ejemplo</title>
<figure id="figure-dialogs-colorchooserdialog">
<title>ColorChooserDialog</title>
<screenshot>
<graphic format="PNG" fileref="figures/dialogs_colorchooserdialog.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/colorchooserdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_color_button_color_set();
void on_button_dialog_clicked();
//Child widgets:
Gtk::Box m_VBox;
Gtk::ColorButton m_ColorButton;
Gtk::Button m_Button_Dialog;
Gtk::DrawingArea m_DrawingArea; //To show the color.
Gdk::RGBA m_Color;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
m_Button_Dialog("Choose Color")
{
set_title("Gtk::ColorChooserDialog example");
set_default_size(200, 200);
add(m_VBox);
m_VBox.pack_start(m_ColorButton, Gtk::PACK_SHRINK);
m_ColorButton.signal_color_set().connect(sigc::mem_fun(*this,
&ExampleWindow::on_color_button_color_set) );
m_VBox.pack_start(m_Button_Dialog, Gtk::PACK_SHRINK);
m_Button_Dialog.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_dialog_clicked) );
//Set start color:
m_Color.set_red(0.0);
m_Color.set_green(0.0);
m_Color.set_blue(1.0);
m_Color.set_alpha(1.0); //opaque
m_ColorButton.set_rgba(m_Color);
m_DrawingArea.override_background_color(m_Color);
m_VBox.pack_start(m_DrawingArea);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_color_button_color_set()
{
//Store the chosen color, and show it:
m_Color = m_ColorButton.get_rgba();
m_DrawingArea.override_background_color(m_Color);
}
void ExampleWindow::on_button_dialog_clicked()
{
Gtk::ColorChooserDialog dialog("Please choose a color");
dialog.set_transient_for(*this);
//Get the previously selected color:
dialog.set_rgba(m_Color);
const int result = dialog.run();
//Handle the response:
switch(result)
{
case Gtk::RESPONSE_OK:
{
//Store the chosen color, and show it:
m_Color = dialog.get_rgba();
m_ColorButton.set_rgba(m_Color);
m_DrawingArea.override_background_color(m_Color);
break;
}
case Gtk::RESPONSE_CANCEL:
{
std::cout << "Cancel clicked." << std::endl;
break;
}
default:
{
std::cout << "Unexpected button clicked: " << result << std::endl;
break;
}
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-font-chooser-dialog"><title>FontChooserDialog</title>
<para>El <classname>FontChooserDialog</classname> le permite al usuario elegir una tipografía. El <classname>FontButton</classname> abre un diálogo de selección de tipografía cuando se pulsa.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FontChooserDialog.html">Reference</ulink></para>
<sect2 id="fontchooserdialog-example">
<title>Ejemplo</title>
<figure id="figure-dialogs-fontchooserdialog">
<title>FontChooserDialog</title>
<screenshot>
<graphic format="PNG" fileref="figures/dialogs_fontchooserdialog.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/fontchooserdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_font_button_font_set();
void on_button_dialog_clicked();
//Child widgets:
Gtk::ButtonBox m_ButtonBox;
Gtk::FontButton m_FontButton;
Gtk::Button m_Button_Dialog;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
m_FontButton("Sans 10"),
m_Button_Dialog("Choose Font")
{
set_title("Gtk::FontChooserDialog example");
add(m_ButtonBox);
m_ButtonBox.pack_start(m_FontButton);
m_FontButton.set_use_font(true);
m_FontButton.set_use_size(true);
m_FontButton.signal_font_set().connect(sigc::mem_fun(*this,
&ExampleWindow::on_font_button_font_set) );
m_ButtonBox.pack_start(m_Button_Dialog);
m_Button_Dialog.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_dialog_clicked) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_font_button_font_set()
{
Glib::ustring font_name = m_FontButton.get_font_name();
std::cout << "Font chosen: " << font_name << std::endl;
}
void ExampleWindow::on_button_dialog_clicked()
{
Gtk::FontChooserDialog dialog("Please choose a font", *this);
//Get the previously selected font name from the FontButton:
dialog.set_font(m_FontButton.get_font_name());
int result = dialog.run();
//Handle the response:
switch(result)
{
case Gtk::RESPONSE_OK:
{
Glib::ustring font_name = dialog.get_font();
std::cout << "Font chosen: " << font_name << std::endl;
m_FontButton.set_font_name(font_name);
break;
}
case Gtk::RESPONSE_CANCEL:
{
std::cout << "Cancel clicked." << std::endl;
break;
}
default:
{
std::cout << "Unexpected button clicked: " << result << std::endl;
break;
}
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-about-dialog"><title>AboutDialog no modal</title>
<para>La clase <classname>AboutDialog</classname> ofrece una manera sencilla de mostrar información sobre el programa, como su logo, nombre, copyright, página web y licencia.</para>
<para lang="en">
Most dialogs in this chapter are modal, that is, they freeze the rest of
the application while they are shown. It's also possible to create a non-modal
dialog, which does not freeze other windows in the application.
The following example shows a non-modal <classname>AboutDialog</classname>. This is
perhaps not the kind of dialog you would normally make non-modal, but non-modal
dialogs can be useful in other cases. E.g. <application>gedit</application>'s
search-and-replace dialog is non-modal.
</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AboutDialog.html">Reference</ulink></para>
<sect2 id="aboutdialog-example">
<title>Ejemplo</title>
<figure id="figure-dialogs-about">
<title>AboutDialog</title>
<screenshot>
<graphic format="PNG" fileref="figures/dialogs_about.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/aboutdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_clicked();
void on_about_dialog_response(int response_id);
//Child widgets:
Gtk::Box m_VBox;
Gtk::Label m_Label;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button;
Gtk::AboutDialog m_Dialog;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Label("The AboutDialog is non-modal. "
"You can select parts of this text while the AboutDialog is shown."),
m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
m_Button("Show AboutDialog")
{
set_title("Gtk::AboutDialog example");
add(m_VBox);
m_VBox.pack_start(m_Label);
m_Label.set_line_wrap(true);
m_Label.set_selectable(true);
m_VBox.pack_start(m_ButtonBox);
m_ButtonBox.pack_start(m_Button);
m_Button.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_clicked) );
m_Dialog.set_transient_for(*this);
m_Dialog.set_program_name("Example application");
m_Dialog.set_version("1.0.0");
m_Dialog.set_copyright("Murray Cumming");
m_Dialog.set_comments("This is just an example application.");
m_Dialog.set_license("LGPL");
m_Dialog.set_website("http://www.gtkmm.org");
m_Dialog.set_website_label("gtkmm website");
std::vector<Glib::ustring> list_authors;
list_authors.push_back("Murray Cumming");
list_authors.push_back("Somebody Else");
list_authors.push_back("AN Other");
m_Dialog.set_authors(list_authors);
m_Dialog.signal_response().connect(
sigc::mem_fun(*this, &ExampleWindow::on_about_dialog_response) );
show_all_children();
// The widget must be realized and mapped before grab_focus() is called.
// That's why it's called after show_all_children().
m_Button.grab_focus();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_about_dialog_response(int response_id)
{
std::cout << response_id
<< ", close=" << Gtk::RESPONSE_CLOSE
<< ", cancel=" << Gtk::RESPONSE_CANCEL
<< ", delete_event=" << Gtk::RESPONSE_DELETE_EVENT
<< std::endl;
if((response_id == Gtk::RESPONSE_CLOSE) ||
(response_id == Gtk::RESPONSE_CANCEL) )
{
m_Dialog.hide();
}
}
void ExampleWindow::on_button_clicked()
{
m_Dialog.show();
//Bring it to the front, in case it was already shown:
m_Dialog.present();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-drawingarea">
<title>El widget de área de dibujo</title>
<para>El widget <classname>DrawingArea</classname> es una ventana vacía que le da la libertad de crear cualquier gráfico que desee. Junto con esa libertad viene la responsabilidad de manejar las señales de dibujo en el widget. Cuando un widget se muestra por primera vez, o cuando se cubre y descubre, debe redibujarse a sí mismo. La mayoría de los widgets tiene código para hacer esto, pero el área de dibujo no, permitiéndole escribir su propio manejador de señales de dibujo para determinar cómo se dibujarán los contenidos del widget. La mayor parte de las veces, esto se hace sobrecargando la función miembro virtual <methodname>on_draw()</methodname>.</para>
<para>GTK+ usa la API de dibujo <ulink url="http://cairographics.org">Cairo</ulink>. Con <application>gtkmm</application>, puede usar la API C++ <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink> para Cairo.</para>
<para>Puede dibujar formas muy sofisticadas usando Cairo, pero los métodos para hacerlo son bastante básicos. Cairo proporciona métodos para dibujar líneas rectas, curvas, y arcos (incluyendo círculos). Estas formas básicas pueden combinarse para crear formas más complejas y caminos que pueden llenarse con colores sólidos, gradientes, patrones, y otras cosas. Además, Cairo puede realizar transformaciones complejas, componer imágenes, y generar texto con «antialiasing».</para>
<note>
<title>Cairo y Pango</title>
<para>A pesar de que Cairo puede generar texto, no está pensado para reemplazar a Pango. Pango es una mejor elección si necesita generar texto más avanzado, por ejemplo, con ajuste de línea o elipses. Sólo debe dibujar texto con Cairo si éste es parte de un gráfico.</para>
</note>
<para>En esta sección del tutorial, se cubrirá el modelo básico de dibujo con Cairo, describiendo cada uno de los elementos básicos de dibujo (con ejemplos), y luego se prsentará una aplicación simple que usa Cairo para dibujar un widget de reloj personalizado.</para>
<sect1 id="sec-cairo-drawing-model">
<title>El modelo de dibujo de Cairo</title>
<para>El concepto básico de dibujar con Cairo implica definir caminos «invisibles» y luego tacharlos o rellenarlos para hacerlos visibles.</para>
<para>Para hacer cualquier dibujo en <application>Gtkmm</application> con Cairo, primero debe crear un objeto <classname>Cairo::Context</classname>. Esta clase contiene a todos los parámetros del estado de gráficos que describen cómo se dibujará. Esto incluye información como el ancho de línea, color, la superficie a la que dibujar, y muchas otras cosas. Esto permite a las funciones de dibujo en si tomar menos argumentos para simplificar la interfaz. En <application>gtkmm</application>, un <classname>Cairo::Context</classname> se crea llamando a la función <methodname>Gdk::Window::create_cairo_context()</methodname>. Dado que los contextos de Cairo son objetos contados por referencia, esta función devuelve un objeto <classname>Cairo::RefPtr<Cairo::Context></classname></para>
<para>El siguiente ejemplo muestra cómo crear un contexto Cairo con un color de frente rojo y un ancho de 2. Cualquier función de dibujo que use este contexto usará esta configuración</para>
<programlisting>Gtk::DrawingArea myArea;
Cairo::RefPtr<Cairo::Context> myContext = myArea.get_window()->create_cairo_context();
myContext->set_source_rgb(1.0, 0.0, 0.0);
myContext->set_line_width(2.0);</programlisting>
<para>Cada <classname>Cairo::Context</classname> se asocia a una <classname>Gdk::Window</classname> particular, por lo que la primera línea del ejemplo de abajo crea un widget <classname>Gtk::DrawingArea</classname> y la segunda línea usa su <classname>Gdk::Window</classname> asociada para crear un objeto <classname>Cairo::Context</classname>. Las dos últimas líneas cambian el estado gráfico del contexto.</para>
<para>Hay varias variables del estado de gráficos que pueden establecerse para un contexto Cairo. Los atributos de contexto más comunes son color (usando <methodname>set_source_rgb()</methodname> o <methodname>set_source_rgba()</methodname> para colores traslúcidos), anchura de línea (usando <methodname>set_line_width()</methodname>), patrón de línea de puntos (usando <methodname>set_dash</methodname>), estilo de terminación de línea (usando <methodname>set_line_cap()</methodname>), estilo de unión de línea (usando <methodname>set_line_join()</methodname>), y estilos de fuente (usando <methodname>set_font_size()</methodname>, <methodname>set_font_face()</methodname> y otros). Hay muchas otras opciones también, como matrices de transformación, reglas de rellenado, realización de «antialiasing», y otros. Para obtener más información, consulte la documentación de la API de <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink>.</para>
<para lang="en">
The current state of a <classname>Cairo::Context</classname> can be
saved to an internal stack of saved states and later be restored to the
state it was in when you saved it. To do this, use the
<methodname>save()</methodname>
method and the <methodname>restore()</methodname> method. This can be
useful if you need to temporarily change the line width and color (or
any other graphics setting) in order to draw something and then return
to the previous settings. In this situation, you could call
<methodname>Cairo::Context::save()</methodname>, change the graphics
settings, draw the lines, and then call
<methodname>Cairo::Context::restore()</methodname> to restore the original
graphics state. Multiple calls to <methodname>save()</methodname> and
<methodname>restore()</methodname> can be nested; each call to
<methodname>restore()</methodname> restores the state from the
matching paired <methodname>save()</methodname>.
<tip>
<para lang="en">It is good practice to put all modifications to the graphics state
between <methodname>save()</methodname>/<methodname>restore()</methodname>
function calls. For example, if you have a function that takes a
<classname>Cairo::Context</classname> reference as an argument, you
might implement it as follows:
</para>
<programlisting lang="en">void doSomething(const Cairo::RefPtr<Cairo::Context>& context, int x)
{
context->save();
// change graphics state
// perform drawing operations
context->restore();
}</programlisting>
</tip>
</para>
<para>El método virtual <methodname>on_draw()</methodname> proporciona un contexto Cairo que deberá usar para dibujar en el widget <classname>Gtk::DrawingArea</classname>. No es necesario guardar y restaurar este contexto Cairo en <methodname>on_draw()</methodname>.</para>
</sect1>
<sect1 id="sec-cairo-drawing-lines">
<title>Dibujar Lineas Rectas</title>
<para lang="en">
Now that we understand the basics of the Cairo graphics library, we're
almost ready to start drawing. We'll start with the simplest of
drawing elements: the straight line. But first you need to know a
little bit about Cairo's coordinate system. The origin of the Cairo
coordinate system is located in the upper-left corner of the window
with positive x values to the right and positive y values going down.
<tip>
<para lang="en">Since the Cairo graphics library was written with support for
multiple output targets (the X window system, PNG images, OpenGL,
etc), there is a distinction between user-space and device-space
coordinates. The mapping between these two coordinate systems
defaults to one-to-one so that integer values map roughly to pixels
on the screen, but this setting can be adjusted if desired.
Sometimes it may be useful to scale the coordinates so that the
full width and height of a window both range from 0 to 1 (the 'unit
square') or some other mapping that works for your application.
This can be done with the
<methodname>Cairo::Context::scale()</methodname> function.</para>
</tip>
</para>
<sect2 id="cairo-example-lines"><title>Ejemplo</title>
<para>En este ejemplo, se construirá un programa <application>gtkmm</application> pequeño pero funcional y se dibujarán algunas líneas en la ventana. Las líneas se dibujan creando un camino y luego rellenándolo. Un camino se crea usando las funciones <methodname>Cairo::Context::move_to()</methodname> y <methodname>Cairo::Context::line_to()</methodname>. La función <methodname>move_to()</methodname> es similar al acto de levantar el bolígrafo del papel y ponerlo en algún otro lado: no se dibuja ninguna línea entre el punto en el que estaba y el punto al que se movió. Para dibujar una línea entre dos puntos, use la función <methodname>line_to()</methodname>.</para>
<para>Después de terminar de crear su camino, todavía no ha dibujado nada visible. Para hacer el camino visible, debe usar la función <methodname>stroke()</methodname> que rellenará el camino actual con la anchura y estilo de línea que se ha especificado en su objeto <classname>Cairo::Context</classname>. Después de rellenar, el camino actual se despejará para que pueda comenzar el próximo.</para>
<tip>
<para>Muchas funciones de dibujo de Cairo tienen una variante <methodname>_preserve()</methodname>. Normalmente, las funciones de dibujo como <methodname>clip()</methodname>, <methodname>fill()</methodname>, o <methodname>stroke()</methodname> despejarán el camino actual. Si usa la variante <methodname>_preserve()</methodname>, el camino actual se retendrá, por lo que podrá usar el mismo camino con la próxima función de dibujo.</para>
</tip>
<figure id="figure-drawingarea-lines">
<title>Área de dibujo: líneas</title>
<screenshot>
<graphic format="PNG" fileref="figures/drawingarea_lines.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/simple?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H
#include <gtkmm/drawingarea.h>
class MyArea : public Gtk::DrawingArea
{
public:
MyArea();
virtual ~MyArea();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
};
#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <cairomm/context.h>
MyArea::MyArea()
{
}
MyArea::~MyArea()
{
}
bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
// coordinates for the center of the window
int xc, yc;
xc = width / 2;
yc = height / 2;
cr->set_line_width(10.0);
// draw red lines out from the center of the window
cr->set_source_rgb(0.8, 0.0, 0.0);
cr->move_to(0, 0);
cr->line_to(xc, yc);
cr->line_to(0, height);
cr->move_to(xc, yc);
cr->line_to(width, yc);
cr->stroke();
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
int main(int argc, char** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window win;
win.set_title("DrawingArea");
MyArea area;
win.add(area);
area.show();
return app->run(win);
}
</programlisting>
<!-- end inserted example code -->
<para>Este programa contiene una sola clase, <classname>MyArea</classname>, que es una subclase de <classname>Gtk::DrawingArea</classname> y contiene una función miembro <methodname>on_draw()</methodname>. Esta función se llama siempre que la imagen en el área de dibujo deba redibujarse. Se le pasa un puntero <classname>Cairo::RefPtr</classname> al <classname>Cairo::Context</classname> que se usa para el dibujo. El código de dibujo real establece el color que queremos usar para dibujar usando <methodname>set_source_rgb()</methodname>, que toma argumentos definiendo los componentes de rojo, verde, y azul del color deseado (los valores válidos se hallan entre 0 y 1). Después de establecer el color, creamos un camino nuevo usando las funciones <methodname>move_to()</methodname> y <methodname>line_to()</methodname>, y luego lo rellenamos usando <methodname>stroke()</methodname>.</para>
<tip>
<title>Dibujar con coordenadas relativas</title>
<para>En el ejemplo anterior, se ha dibujado todo usando coordenadas absolutas. También puede dibujar usando coordenadas relativas. Para una línea recta, esto se hace con la función <methodname>Cairo::Context::rel_line_to()</methodname>.</para>
</tip>
</sect2>
<sect2 id="cairo-line-styles">
<title>Estilos de línea</title>
<para>Además de dibujar líneas rectas básicas, también puede personalizar algunas cosas de las líneas. Ya ha visto ejemplos de cómo establecer el color y anchura de una línea, pero también hay otras cosas.</para>
<para>Si ha dibujado una serie de líneas que forman un camino, tal vez quiera que se junten de alguna manera. Cairo le ofrece tres maneras distintas de juntar líneas: «Miter», «Bevel», y «Round». Se muestran a continuación:</para>
<figure id="figure-cairo-joins">
<title>Distintos tipos de uniones en Cairo</title>
<screenshot>
<graphic format="PNG" fileref="figures/cairo_joins.png"/>
</screenshot>
</figure>
<para>El estilo de unión de línea se establece usando la función <methodname>Cairo::Context::set_line_join()</methodname>.</para>
<para>Las puntas de las líneas pueden también tener distintos estilos. El estilo predeterminado consiste en que la línea comience y se detenga exactamente en sus puntos de destino. Esto se llama terminación «Butt». Las otras opciones son «Round» (usa una terminación redondeada, con el centro del círculo en el último punto) o «Square» (usa una terminación cuadrada, con el centro del cuadrado en el último punto). Esta opción se establece usando la función <methodname>Cairo::Context::set_line_cap()</methodname>.</para>
<para>Además, hay otras cosas que puede personalizar, incluyendo la creación de líneas punteadas y otras cosas. Para obtener más información, consulte la documentación de la API de Cairo.</para>
</sect2>
<sect2 id="sec-cairo-thin-lines">
<title>Dibujar líneas estrechas</title>
<para>Si intenta dibujar líneas de un píxel de anchura, notará que a veces la línea sale más borrosa y ancha de lo que debería. Esto sucede porque Cairo intentará dibujar desde la posición seleccionada, a ambos lados (mitad a cada uno), por que lo que si está posicionado justo en la intersección de los píxeles, y quiere líneas de un píxel de anchura, Cairo intentará usar la mitad de cada píxel adyacente, lo que no es posible (un píxel es la menor unidad posible). Esto sucede cuando la anchura de la línea es un número impar de píxeles (no sólo uno).</para>
<para>El truco está en posicionarse en la mitad del píxel en el que quiere que se dibuje la línea, garantizando así que obtendrá los resultados deseados. Consulte las <ulink url="http://cairographics.org/FAQ/#sharp_lines">preguntas más frecuentes de Cairo</ulink>.</para>
<figure id="figure-drawingarea-thin-lines">
<title>Área de dibujo: líneas estrechas</title>
<screenshot>
<graphic format="PNG" fileref="figures/drawingarea_thin_lines.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/thin_lines?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm/window.h>
#include <gtkmm/grid.h>
#include <gtkmm/checkbutton.h>
#include "myarea.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_toggled();
private:
Gtk::Grid m_Container;
MyArea m_Area_Lines;
Gtk::CheckButton m_Button_FixLines;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H
#include <gtkmm/drawingarea.h>
class MyArea : public Gtk::DrawingArea
{
public:
MyArea();
virtual ~MyArea();
void fix_lines(bool fix = true);
void force_redraw();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
private:
double m_fix;
};
#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_Button_FixLines("Fix lines")
{
set_title("Thin lines example");
m_Container.set_orientation(Gtk::ORIENTATION_HORIZONTAL);
m_Container.add(m_Area_Lines);
m_Container.add(m_Button_FixLines);
add(m_Container);
m_Button_FixLines.signal_toggled().connect(
sigc::mem_fun(*this, &ExampleWindow::on_button_toggled));
// Synchonize the drawing in m_Area_Lines with the state of the toggle button.
on_button_toggled();
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_toggled()
{
m_Area_Lines.fix_lines(m_Button_FixLines.get_active());
}
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
MyArea::MyArea()
: m_fix (0)
{
set_size_request (200, 100);
}
MyArea::~MyArea()
{
}
bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
cr->set_line_width(1.0);
// draw one line, every two pixels
// without the 'fix', you won't notice any space between the lines,
// since each one will occupy two pixels (width)
for (int i = 0; i < width; i += 2)
{
cr->move_to(i + m_fix, 0);
cr->line_to(i + m_fix, height);
}
cr->stroke();
return true;
}
// Toogle between both values (0 or 0.5)
void MyArea::fix_lines(bool fix)
{
// to get the width right, we have to draw in the middle of the pixel
m_fix = fix ? 0.5 : 0.0;
force_redraw();
}
// force the redraw of the image
void MyArea::force_redraw()
{
Glib::RefPtr<Gdk::Window> win = get_window();
if (win)
{
Gdk::Rectangle r(0, 0, get_allocation().get_width(), get_allocation().get_height());
win->invalidate_rect(r, false);
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char* argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-cairo-curved-lines">
<title>Dibujar líneas curvas</title>
<para>Además de dibujar líneas rectas, Cairo le permite dibujar líneas curvas fácilmente. (técnicamente, una spline cúbica de Bézier) usando las funciones <methodname>Cairo::Context::curve_to()</methodname> y <methodname>Cairo::Context::rel_curve_to()</methodname>. Estas funciones toman las coordenadas de un punto de destino y de dos puntos de «control». Esto se entiende mejor con un ejemplo, así que analícelo en profundidad.</para>
<sect2 id="cairo-example-curves">
<title>Ejemplo</title>
<para>Esta aplicación simple dibuja una curva con Cairo y muestra los puntos de control para cada punta de la curva.</para>
<figure id="figure-drawingarea-curve">
<title>Área de dibujo: líneas</title>
<screenshot>
<graphic format="PNG" fileref="figures/drawingarea_curve.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/curve?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H
#include <gtkmm/drawingarea.h>
class MyArea : public Gtk::DrawingArea
{
public:
MyArea();
virtual ~MyArea();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
};
#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <cairomm/context.h>
MyArea::MyArea()
{
}
MyArea::~MyArea()
{
}
bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
double x0=0.1, y0=0.5, // start point
x1=0.4, y1=0.9, // control point #1
x2=0.6, y2=0.1, // control point #2
x3=0.9, y3=0.5; // end point
// scale to unit square (0 to 1 width and height)
cr->scale(width, height);
cr->set_line_width(0.05);
// draw curve
cr->move_to(x0, y0);
cr->curve_to(x1, y1, x2, y2, x3, y3);
cr->stroke();
// show control points
cr->set_source_rgba(1, 0.2, 0.2, 0.6);
cr->move_to(x0, y0);
cr->line_to (x1, y1);
cr->move_to(x2, y2);
cr->line_to (x3, y3);
cr->stroke();
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
int main(int argc, char** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window win;
win.set_title("DrawingArea");
MyArea area;
win.add(area);
area.show();
return app->run(win);
}
</programlisting>
<!-- end inserted example code -->
<para>La única diferencia entre este ejemplo y el de la línea recta está en la función <methodname>on_draw()</methodname>, pero hay unos conceptos y funciones nuevas presentadas aquí, así que se examinarán brevemente.</para>
<para>Se hace una llamada a <methodname>Cairo::Context::scale()</methodname>, pasándole la anchura y altura del área de dibujo. Esto escala el sistema de coordenadas de espacio del usuario de tal manera que la anchura y altura del widget correspondan ambas a 1.0 «unidades». No hay una razón en particular para escalar el sistema de coordenadas en este caso, pero a veces, puede hacer las operaciones de dibujo más fáciles.</para>
<para lang="en">
The call to <methodname>Cairo::Context::curve_to()</methodname> should
be fairly self-explanatory. The first pair of coordinates define
the control point for the beginning of the curve. The second set
of coordinates define the control point for the end of the curve,
and the last set of coordinates define the destination point. To
make the concept of control points a bit easier to visualize, a
line has been drawn from each control point to the end-point on the
curve that it is associated with. Note that these control point
lines are both translucent. This is achieved with a variant of
<methodname>set_source_rgb()</methodname> called
<methodname>set_source_rgba()</methodname>. This function takes a
fourth argument specifying the alpha value of the color (valid
values are between 0 and 1).
</para>
</sect2>
</sect1>
<sect1 id="sec-cairo-drawing-arcs">
<title>Dibujar arcos y círculos</title>
<para>Con Cairo, la misma función se usa para dibujar arcos, círculos, o elipses: <methodname>Cairo::Context::arc()</methodname>. Esta función toma cinco argumentos. Los dos primeros son las coordenadas del punto central del arco, el tercer argumento es el radio del arco, y los últimos dos argumentos definen el ángulo de inicio y fin del arco. Todos los ángulos se definen en radianes, por lo que dibujar un círculo es lo mismo que dibujar un arco de 0 a 2 * M_PI radianes. Un ángulo de 0 está en la dirección del eje positivo de X (en espacio de usuario). Un ángulo de M_PI/2 radianes (90 grados) está en la dirección del eje positivo de Y (en espacio de usuario). Los ángulos se incrementan en la dirección del eje positivo de X hacia el eje positivo de Y, por lo que con la matriz de transformación predeterminada, los ángulos incrementan en la dirección de las agujas del reloj (recuerde que el eje positivo de Y apunta hacia abajo).</para>
<para lang="en">
To draw an ellipse, you can scale the current transformation matrix
by different amounts in the X and Y directions. For example, to draw
an ellipse with center at <varname>x</varname>, <varname>y</varname>
and size <varname>width</varname>, <varname>height</varname>:
<programlisting lang="en">context->save();
context->translate(x, y);
context->scale(width / 2.0, height / 2.0);
context->arc(0.0, 0.0, 1.0, 0.0, 2 * M_PI);
context->restore();</programlisting>
</para>
<sect2 id="cairo-example-arcs">
<title>Ejemplo</title>
<para>Aquí hay un programa simple de ejemplo que dibuja un arco, un círculo, y una elipse en un área de dibujo.</para>
<figure id="figure-drawingarea-arc">
<title>Área de dibujo: arcos</title>
<screenshot>
<graphic format="PNG" fileref="figures/drawingarea_arcs.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/arcs?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H
#include <gtkmm/drawingarea.h>
class MyArea : public Gtk::DrawingArea
{
public:
MyArea();
virtual ~MyArea();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
};
#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <cairomm/context.h>
#include <cmath>
MyArea::MyArea()
{
}
MyArea::~MyArea()
{
}
bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
// This is where we draw on the window
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
const int lesser = MIN(width, height);
// coordinates for the center of the window
int xc, yc;
xc = width / 2;
yc = height / 2;
cr->set_line_width(lesser * 0.02); // outline thickness changes
// with window size
// first draw a simple unclosed arc
cr->save();
cr->arc(width / 3.0, height / 4.0, lesser / 4.0, -(M_PI / 5.0), M_PI);
cr->close_path(); // line back to start point
cr->set_source_rgb(0.0, 0.8, 0.0);
cr->fill_preserve();
cr->restore(); // back to opaque black
cr->stroke(); // outline it
// now draw a circle
cr->save();
cr->arc(xc, yc, lesser / 4.0, 0.0, 2.0 * M_PI); // full circle
cr->set_source_rgba(0.0, 0.0, 0.8, 0.6); // partially translucent
cr->fill_preserve();
cr->restore(); // back to opaque black
cr->stroke();
// and finally an ellipse
double ex, ey, ew, eh;
// center of ellipse
ex = xc;
ey = 3.0 * height / 4.0;
// ellipse dimensions
ew = 3.0 * width / 4.0;
eh = height / 3.0;
cr->save();
cr->translate(ex, ey); // make (ex, ey) == (0, 0)
cr->scale(ew / 2.0, eh / 2.0); // for width: ew / 2.0 == 1.0
// for height: eh / 2.0 == 1.0
cr->arc(0.0, 0.0, 1.0, 0.0, 2 * M_PI); // 'circle' centered at (0, 0)
// with 'radius' of 1.0
cr->set_source_rgba(0.8, 0.0, 0.0, 0.7);
cr->fill_preserve();
cr->restore(); // back to opaque black
cr->stroke();
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
int main(int argc, char** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window win;
win.set_title("DrawingArea");
MyArea area;
win.add(area);
area.show();
return app->run(win);
}
</programlisting>
<!-- end inserted example code -->
<para>Hay un par de cosas que debe tener en cuenta acerca de este código de ejemplo. Nuevamente, la única diferencia real entre este ejemplo y los anteriores es la función <methodname>on_draw()</methodname>, por lo que nos limitaremos a trabajar esa función. Además, la primera parte de la función es casi idéntica a la de los ejemplos previos, por lo que se omitirá ese fragmento.</para>
<para>Tenga en cuenta que, en este caso, se ha expresado casi todo en términos de anchura y altura de la ventana, incluyendo la anchura de las líneas. Es por esto que, cuando cambie el tamaño de la ventana, todo se escalará a ella. Además, tenga en cuenta que hay tres secciones de dibujo en la función, y cada una está envuelta en un par <methodname>save()</methodname>/<methodname>restore()</methodname> para volver a un estado conocido después de cada dibujo.</para>
<para>La sección para dibujar un arco presenta una nueva función, <methodname>close_path()</methodname>. Esta función, en efecto, dibujará una línea recta desde el punto actual de vuelta al primer punto en el camino. Sin embargo, hay una diferencia significativa entre llamar a <methodname>close_path()</methodname> y dibujar una línea manualmente al punto de inicio. Si usa <methodname>close_path()</methodname>, las líneas se juntarán suavemente. Si usa <methodname>line_to()</methodname> en su lugar, las líneas terminarán en el mismo lugar, pero Cairo no las juntará de manera especial.</para>
<note>
<title>Dibujar en sentido anti-horario</title>
<para>La función <methodname>Cairo::Context::arc_negative()</methodname> es exactamente la misma que <methodname>Cairo::Context::arc()</methodname>, pero los ángulos van en la dirección opuesta.</para>
</note>
</sect2>
</sect1>
<sect1 id="sec-drawing-text">
<title>Dibujar texto</title>
<sect2 id="drawing-text-pango">
<title>Dibujar texto con Pango</title>
<para>El texto se dibuja a través de disposiciones de Pango. La manera más fácil de crear una <classname>Pango::Layout</classname> es usar <methodname>Gtk::Widget::create_pango_layout()</methodname>. Una vez creada, la disposición puede manipularse de varias maneras, incluyendo cambiar el texto, la tipografía, etc. Finalmente, la disposición puede mostrarse usando el método <methodname>Pango::Layout::show_in_cairo_context()</methodname>.</para>
</sect2>
<sect2 id="pango-text-example">
<title>Ejemplo</title>
<para>Aquí hay un ejemplo de un programa que dibuja texto, parte de él invertido. El capítulo de impresión contiene otro <link linkend="sec-printing-example">ejemplo</link> de dibujo de texto.</para>
<figure id="figure-drawingarea-pango-text">
<title>Área de dibujo: texto</title>
<screenshot>
<graphic format="PNG" fileref="figures/drawingarea_pango_text.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/pango_text?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H
#include <gtkmm/drawingarea.h>
class MyArea : public Gtk::DrawingArea
{
public:
MyArea();
virtual ~MyArea();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
private:
void draw_rectangle(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height);
void draw_text(const Cairo::RefPtr<Cairo::Context>& cr, int rectangle_width, int rectangle_height);
};
#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
MyArea::MyArea()
{
}
MyArea::~MyArea()
{
}
bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
const int rectangle_width = width;
const int rectangle_height = height / 2;
// Draw a black rectangle
cr->set_source_rgb(0.0, 0.0, 0.0);
draw_rectangle(cr, rectangle_width, rectangle_height);
// and some white text
cr->set_source_rgb(1.0, 1.0, 1.0);
draw_text(cr, rectangle_width, rectangle_height);
// flip the image vertically
// see http://www.cairographics.org/documentation/cairomm/reference/classCairo_1_1Matrix.html
// the -1 corresponds to the yy part (the flipping part)
// the height part is a translation (we could have just called cr->translate(0, height) instead)
// it's height and not height / 2, since we want this to be on the second part of our drawing
// (otherwise, it would draw over the previous part)
Cairo::Matrix matrix(1.0, 0.0, 0.0, -1.0, 0.0, height);
// apply the matrix
cr->transform(matrix);
// white rectangle
cr->set_source_rgb(1.0, 1.0, 1.0);
draw_rectangle(cr, rectangle_width, rectangle_height);
// black text
cr->set_source_rgb(0.0, 0.0, 0.0);
draw_text(cr, rectangle_width, rectangle_height);
return true;
}
void MyArea::draw_rectangle(const Cairo::RefPtr<Cairo::Context>& cr,
int width, int height)
{
cr->rectangle(0, 0, width, height);
cr->fill();
}
void MyArea::draw_text(const Cairo::RefPtr<Cairo::Context>& cr,
int rectangle_width, int rectangle_height)
{
// http://developer.gnome.org/pangomm/unstable/classPango_1_1FontDescription.html
Pango::FontDescription font;
font.set_family("Monospace");
font.set_weight(Pango::WEIGHT_BOLD);
// http://developer.gnome.org/pangomm/unstable/classPango_1_1Layout.html
Glib::RefPtr<Pango::Layout> layout = create_pango_layout("Hi there!");
layout->set_font_description(font);
int text_width;
int text_height;
//get the text dimensions (it updates the variables -- by reference)
layout->get_pixel_size(text_width, text_height);
// Position the text in the middle
cr->move_to((rectangle_width-text_width)/2, (rectangle_height-text_height)/2);
layout->show_in_cairo_context(cr);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
int main(int argc, char* argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window window;
window.set_title("Drawing text example");
MyArea area;
window.add(area);
area.show();
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<!--
<sect2 id="drawing-text-cairo">
<title>Drawing Text with Cairo</title>
<warning>TODO: Add Cairo content.</warning>
</sect2>
-->
</sect1>
<sect1 id="sec-draw-images">
<title>Dibujar imágenes</title>
<para>Hay un método para dibujar desde un <classname>Gdk::Pixbuf</classname> a un <classname>Cairo::Context</classname>. Un búfer <classname>Gdk::Pixbuf</classname> es un envoltorio útil alrededor de un grupo de píxeles, que puede leerse desde archivos y manipularse de varias maneras.</para>
<para>Probablemente la manera más común de crear un <classname>Gdk::Pixbuf</classname> es usar <methodname>Gdk::Pixbuf::create_from_file()</methodname>, que puede leer un archivo de imagen, como un archivo png, hacia un «pixbuf» listo para procesar.</para>
<para>El <classname>Gdk::Pixbuf</classname> puede procesarse estableciéndolo como el patrón fuente del contexto de Cairo con <methodname>Gdk::Cairo::set_source_pixbuf()</methodname>. Después, dibuje la imagen con <methodname>Cairo::Context::paint()</methodname> (para dibujar la imagen entera), o <methodname>Cairo::Context::rectangle()</methodname> y <methodname>Cairo::Context::fill()</methodname> (para rellenar el rectángulo especificado). <methodname>set_source_pixbuf()</methodname> no es un miembro de <classname>Cairo::Context</classname>. Toma un <classname>Cairo::Context</classname> como primer parámetro.</para>
<para>Aquí hay un poco de código que junta todo: (tenga en cuenta que normalmente no cargaría la imagen cada vez en el manejador de señal de dibujo. Se muestra aquí sólo para mantener a todo junto).</para>
<programlisting>bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_file("myimage.png");
// Draw the image at 110, 90, except for the outermost 10 pixels.
Gdk::Cairo::set_source_pixbuf(cr, image, 100, 80);
cr->rectangle(110, 90, image->get_width()-20, image->get_height()-20);
cr->fill();
return true;
}</programlisting>
<sect2 id="cairo-example-image">
<title>Ejemplo</title>
<para>Aquí hay un ejemplo de un programa simple que dibuja una imagen.</para>
<figure id="figure-drawingarea-image">
<title>Área de dibujo: imagen</title>
<screenshot>
<graphic format="PNG" fileref="figures/drawingarea_image.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/image?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H
#include <gtkmm/drawingarea.h>
#include <gdkmm/pixbuf.h>
class MyArea : public Gtk::DrawingArea
{
public:
MyArea();
virtual ~MyArea();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
Glib::RefPtr<Gdk::Pixbuf> m_image;
};
#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <cairomm/context.h>
#include <gdkmm/general.h> // set_source_pixbuf()
#include <glibmm/fileutils.h>
#include <iostream>
MyArea::MyArea()
{
try
{
// The fractal image has been created by the XaoS program.
// http://xaos.sourceforge.net
m_image = Gdk::Pixbuf::create_from_file("fractal_image.png");
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
}
catch(const Gdk::PixbufError& ex)
{
std::cerr << "PixbufError: " << ex.what() << std::endl;
}
// Show at least a quarter of the image.
if (m_image)
set_size_request(m_image->get_width()/2, m_image->get_height()/2);
}
MyArea::~MyArea()
{
}
bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
if (!m_image)
return false;
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
// Draw the image in the middle of the drawing area, or (if the image is
// larger than the drawing area) draw the middle part of the image.
Gdk::Cairo::set_source_pixbuf(cr, m_image,
(width - m_image->get_width())/2, (height - m_image->get_height())/2);
cr->paint();
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
int main(int argc, char** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window win;
win.set_title("DrawingArea");
win.set_default_size(300, 200);
MyArea area;
win.add(area);
area.show();
return app->run(win);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<!--
<sect1 id="sec-drawing-fill">
<title>Gradients and other fill techniques</title>
<warning>TODO: Add content.</warning>
</sect1>
<sect1 id="sec-drawing-transformations">
<title>Transformations with Cairo</title>
<warning>TODO: Add content.</warning>
</sect1>
-->
<sect1 id="sec-drawing-clock-example">
<title>Aplicación de ejemplo: crear un reloj con Cairo</title>
<para>Ahora que se ha cubierto lo básico acerca del dibujo con Cairo, junte todo y cree una aplicación simple que haga algo de verdad. El siguiente ejemplo usa Cairo para crear un widget <classname>Clock</classname> personalizado. El reloj tiene una manecilla de segundos, una de minutos, y una de horas; y se actualiza cada segundo.</para>
<screenshot>
<graphic format="PNG" fileref="figures/cairo_clock.png"/>
</screenshot>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/clock?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>clock.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_CLOCK_H
#define GTKMM_EXAMPLE_CLOCK_H
#include <gtkmm/drawingarea.h>
class Clock : public Gtk::DrawingArea
{
public:
Clock();
virtual ~Clock();
protected:
//Override default signal handler:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
bool on_timeout();
double m_radius;
double m_line_width;
};
#endif // GTKMM_EXAMPLE_CLOCK_H
</programlisting>
<para lang="en">File: <filename>clock.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <ctime>
#include <cmath>
#include <cairomm/context.h>
#include <glibmm/main.h>
#include "clock.h"
Clock::Clock()
: m_radius(0.42), m_line_width(0.05)
{
Glib::signal_timeout().connect( sigc::mem_fun(*this, &Clock::on_timeout), 1000 );
#ifndef GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
//Connect the signal handler if it isn't already a virtual method override:
signal_draw().connect(sigc::mem_fun(*this, &Clock::on_draw), false);
#endif //GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
}
Clock::~Clock()
{
}
bool Clock::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
// scale to unit square and translate (0, 0) to be (0.5, 0.5), i.e.
// the center of the window
cr->scale(width, height);
cr->translate(0.5, 0.5);
cr->set_line_width(m_line_width);
cr->save();
cr->set_source_rgba(0.337, 0.612, 0.117, 0.9); // green
cr->paint();
cr->restore();
cr->arc(0, 0, m_radius, 0, 2 * M_PI);
cr->save();
cr->set_source_rgba(1.0, 1.0, 1.0, 0.8);
cr->fill_preserve();
cr->restore();
cr->stroke_preserve();
cr->clip();
//clock ticks
for (int i = 0; i < 12; i++)
{
double inset = 0.05;
cr->save();
cr->set_line_cap(Cairo::LINE_CAP_ROUND);
if(i % 3 != 0)
{
inset *= 0.8;
cr->set_line_width(0.03);
}
cr->move_to(
(m_radius - inset) * cos (i * M_PI / 6),
(m_radius - inset) * sin (i * M_PI / 6));
cr->line_to (
m_radius * cos (i * M_PI / 6),
m_radius * sin (i * M_PI / 6));
cr->stroke();
cr->restore(); /* stack-pen-size */
}
// store the current time
time_t rawtime;
time(&rawtime);
struct tm * timeinfo = localtime (&rawtime);
// compute the angles of the indicators of our clock
double minutes = timeinfo->tm_min * M_PI / 30;
double hours = timeinfo->tm_hour * M_PI / 6;
double seconds= timeinfo->tm_sec * M_PI / 30;
cr->save();
cr->set_line_cap(Cairo::LINE_CAP_ROUND);
// draw the seconds hand
cr->save();
cr->set_line_width(m_line_width / 3);
cr->set_source_rgba(0.7, 0.7, 0.7, 0.8); // gray
cr->move_to(0, 0);
cr->line_to(sin(seconds) * (m_radius * 0.9),
-cos(seconds) * (m_radius * 0.9));
cr->stroke();
cr->restore();
// draw the minutes hand
cr->set_source_rgba(0.117, 0.337, 0.612, 0.9); // blue
cr->move_to(0, 0);
cr->line_to(sin(minutes + seconds / 60) * (m_radius * 0.8),
-cos(minutes + seconds / 60) * (m_radius * 0.8));
cr->stroke();
// draw the hours hand
cr->set_source_rgba(0.337, 0.612, 0.117, 0.9); // green
cr->move_to(0, 0);
cr->line_to(sin(hours + minutes / 12.0) * (m_radius * 0.5),
-cos(hours + minutes / 12.0) * (m_radius * 0.5));
cr->stroke();
cr->restore();
// draw a little dot in the middle
cr->arc(0, 0, m_line_width / 3.0, 0, 2 * M_PI);
cr->fill();
return true;
}
bool Clock::on_timeout()
{
// force our program to redraw the entire clock.
Glib::RefPtr<Gdk::Window> win = get_window();
if (win)
{
Gdk::Rectangle r(0, 0, get_allocation().get_width(),
get_allocation().get_height());
win->invalidate_rect(r, false);
}
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "clock.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
int main(int argc, char** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window win;
win.set_title("Cairomm Clock");
Clock c;
win.add(c);
c.show();
return app->run(win);
}
</programlisting>
<!-- end inserted example code -->
<para>Al igual que antes, casi todo lo interesante se hace en el manejador de señal de dibujo <methodname>on_draw()</methodname>. Antes de profundizar en el manejador de señal de dibujo, tenga en cuenta que el constructor del widget <classname>Clock</classname> conecta una función manejadora <methodname>on_timeout()</methodname> a un temporizador con un período de espera de 1000 milisegundos (1 segundo). Esto significa que <methodname>on_timeout()</methodname> se llamará una vez por segundo. La única responsabilidad de esta función es invalidar la ventana para que <application>gtkmm</application> se vea forzado a redibujarla.</para>
<para>Ahora, eche un vistazo al código que hace el dibujo en sí. La primera sección del <methodname>on_draw()</methodname> ya le debería resultar bastante familiar. Este ejemplo, otra vez, escala el sistema de coordenadas para ser un cuadrado unitario, así es más fácil dibujar el reloj como un porcentaje del tamaño de la ventana para que se escale automáticamente cuando el tamaño de la ventana se ajuste. Además, el sistema de coordenadas se escala de tal manera que la coordinada (0, 0) esté justo en el centro de la ventana.</para>
<para lang="en">
The function <methodname>Cairo::Context::paint()</methodname> is used here
to set the background color of the window. This function takes no
arguments and fills the current surface (or the clipped portion of
the surface) with the source color currently active. After setting
the background color of the window, we draw a circle for the clock
outline, fill it with white, and then stroke the outline in black.
Notice that both of these actions use the
<methodname>_preserve</methodname> variant to preserve the current path,
and then this same path is clipped to make sure that our next lines
don't go outside the outline of the clock.
</para>
<para>Después de haber dibujado el contorno, se recorre el reloj dibujando marcas por cada hora, con una marca más grande en la posición de las 12, 3, 6, y 9. Ahora, está finalmente listo para implementar la función del reloj, mostrar la hora, lo que simplemente implica obtener los valores actuales de la hora, minutos, y segundos, y dibujar las manecillas en los ángulos correctos.</para>
</sect1>
</chapter>
<chapter id="chapter-draganddrop">
<title>Arrastrar y soltar</title>
<para><classname>Gtk::Widget</classname> tiene varios métodos y señales cuyo prefijo es «drag_». Se usan para arrastrar y soltar.</para>
<sect1 id="sec-dnd-sources-destinations">
<title>Orígenes y destinos</title>
<para>Las cosas se arrastran desde las <literal>fuentes</literal> para soltarse en los <literal>destinos</literal>. Cada origen y destino tiene información acerca de los formatos de datos que puede recibir o enviar, proporcionada por elementos <classname>Gtk::TargetEntry</classname>. Un destino sólo aceptará un elemento arrastrado si ambos comparten un elemento <classname>Gtk::TargetEntry</classname> compatible. Las señales apropiadas se emitirán entonces, comunicándole a los manejadores de señales qué <classname>Gtk::TargetEntry</classname> se usó.</para>
<para lang="en">
<classname>Gtk::TargetEntry</classname> objects contain this information:
<itemizedlist>
<listitem><para lang="en">target: A name, such as "STRING"</para></listitem>
<listitem><para lang="en">info: An identifier which will be sent to your signals to tell you which TargetEntry was used.</para></listitem>
<listitem><para lang="en">flags: Used only for drag and drop, this specifies whether the data may be dragged to other widgets and applications, or only to the same ones.</para></listitem>
</itemizedlist>
</para>
</sect1>
<sect1 id="sec-dnd-methods">
<title>Métodos</title>
<para>Los <classname>Widgets</classname> pueden identificarse como orígenes o destinos usando estos métodos de <classname>Gtk::Widget</classname>:</para>
<programlisting>void drag_source_set(const std::vector<Gtk::TargetEntry>& targets,
Gdk::ModifierType start_button_mask, Gdk::DragAction actions);</programlisting>
<itemizedlist>
<listitem>
<para lang="en">
<literal>targets</literal> is a vector of
<classname>Gtk::TargetEntry</classname> elements.
</para>
</listitem>
<listitem>
<para><literal>start_button_mask</literal> es una combinación de valores complementarios, que especifica qué tecla modificadora o botón del ratón debe presionarse para empezar a arrastrar.</para>
</listitem>
<listitem>
<para><literal>actions</literal> es una combinación de valores complementarios, que especifican qué operaciones de arrastrar y soltar serán posibles desde este origen: por ejemplo, copiar, mover, o enlazar. El usuario puede elegir entre las acciones usando teclas modificadoras, como <keycap>Mayús</keycap> para cambiar de <literal>copiar</literal> a <literal>mover</literal>, y esto se mostrará con un cursor diferente.</para>
</listitem>
</itemizedlist>
<programlisting>void drag_dest_set(const std::vector<Gtk::TargetEntry>& targets,
Gtk::DestDefaults flags, Gdk::DragAction actions);</programlisting>
<itemizedlist>
<listitem>
<para><literal>flags</literal> es una combinación de valores complementarios que indica cómo responderá el widget visualmente a los objetos que se arrastran y sueltan.</para>
</listitem>
<listitem>
<para><literal>actions</literal> indica las acciones de arrastrar y soltar que este destino puede recibir: consulte la descripción arriba.</para>
</listitem>
</itemizedlist>
</sect1>
<sect1 id="sec-dnd-signals">
<title>Señales</title>
<para>Cuando un destino acepta un elemento arrastrado, se emiten ciertas señales, dependiendo de qué acción se ha seleccionado. Por ejemplo, el usuario podría haber mantenido presionada la tecla <keycap>Mayús</keycap> para especificar un <literal>movimiento</literal> en vez de una <literal>copia</literal>. Recuerde que el usuario sólo puede seleccionar las acciones que ha especificado en sus llamadas a <methodname>drag_dest_set()</methodname> y <methodname>drag_source_set()</methodname>.</para>
<sect2 id="sec-dnd-signals-copy">
<title>Copiar</title>
<para lang="en">
The source widget will emit these signals, in this order:
<itemizedlist>
<listitem><para lang="en"><literal>drag_begin</literal>: Provides DragContext.</para></listitem>
<listitem><para lang="en"><literal>drag_data_get</literal>: Provides <literal>info</literal> about the dragged data format, and a <literal>Gtk::SelectionData</literal> structure, in which you should put the requested data.</para></listitem>
<listitem><para lang="en"><literal>drag_end</literal>: Provides DragContext.</para></listitem>
</itemizedlist>
</para>
<para lang="en">
The destination widget will emit these signals, in this order:
<itemizedlist>
<listitem><para lang="en"><literal>drag_motion</literal>: Provides DragContext and coordinates.
You can call the <methodname>drag_status()</methodname> method of the DragContext
to indicate which action will be accepted.</para></listitem>
<listitem><para lang="en"><literal>drag_drop</literal>: Provides DragContext and coordinates.
You can call <methodname>drag_get_data()</methodname>, which triggers the
<literal>drag_data_get</literal> signal in the source widget, and then the
<literal>drag_data_received</literal> signal in the destination widget.</para></listitem>
<listitem>
<para lang="en">
<literal>drag_data_received</literal>: Provides <literal>info</literal>
about the dragged data format, and a
<literal>Gtk::SelectionData</literal> structure which contains the
dropped data. You should call the <methodname>drag_finish()</methodname>
method of the <literal>DragContext</literal> to indicate whether the
operation was successful.
</para>
</listitem>
</itemizedlist>
</para>
</sect2>
<sect2 id="dnd-signal-move">
<title>Mover</title>
<para lang="en">During a <literal>move</literal>, the source widget will also emit this signal:
<itemizedlist>
<listitem><para lang="en"><literal>drag_data_delete</literal>: Gives the source the opportunity to delete the original data if that's appropriate.</para></listitem>
</itemizedlist>
</para>
</sect2>
<!--
<sect2 id="dnd-signal-link">
<title>Link</title>
<para>TODO: Find an example or documentation.</para>
</sect2>
-->
</sect1>
<sect1 id="sec-dragcontext">
<title>DragContext</title>
<para>Las señales de arrastrar y soltar proporcionan un DragContext, que contiene información acerca de la esta operación y puede usarse para influir en el proceso. Por ejemplo, puede descubrir el widget de origen, o cambiar el icono de arrastrar y soltar, usando el método <methodname>set_icon()</methodname>. Aún más importante, debe llamar al método <methodname>drag_finish()</methodname> desde su manejador de señal <literal>drag_data_received</literal> para indicar si la operación tuvo éxito.</para>
</sect1>
<sect1 id="sec-dnd-example">
<title>Ejemplo</title>
<para>Aquí hay un ejemplo muy simple, demostrando arrastrar y soltar en una operación de <literal>copia</literal>:</para>
<figure id="figure-drag-and-drop">
<title>Arrastrar y soltar</title>
<screenshot>
<graphic format="PNG" fileref="figures/drag_and_drop.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drag_and_drop?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>dndwindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_DNDWINDOW_H
#define GTKMM_EXAMPLE_DNDWINDOW_H
#include <gtkmm/box.h>
#include <gtkmm/label.h>
#include <gtkmm/window.h>
#include <gtkmm/button.h>
class DnDWindow : public Gtk::Window
{
public:
DnDWindow();
virtual ~DnDWindow();
protected:
//Signal handlers:
void on_button_drag_data_get(
const Glib::RefPtr<Gdk::DragContext>& context,
Gtk::SelectionData& selection_data, guint info, guint time);
void on_label_drop_drag_data_received(
const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
const Gtk::SelectionData& selection_data, guint info, guint time);
//Member widgets:
Gtk::Box m_HBox;
Gtk::Button m_Button_Drag;
Gtk::Label m_Label_Drop;
};
#endif // GTKMM_EXAMPLE_DNDWINDOW_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "dndwindow.h"
#include <gtkmm/application.h>
int main (int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
DnDWindow dndWindow;
//Shows the window and returns when it is closed.
return app->run(dndWindow);
}
</programlisting>
<para lang="en">File: <filename>dndwindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "dndwindow.h"
#include <iostream>
DnDWindow::DnDWindow()
: m_Button_Drag("Drag Here\n"),
m_Label_Drop("Drop here\n")
{
set_title("DnD example");
add(m_HBox);
//Targets:
std::vector<Gtk::TargetEntry> listTargets;
listTargets.push_back( Gtk::TargetEntry("STRING") );
listTargets.push_back( Gtk::TargetEntry("text/plain") );
//Drag site:
//Make m_Button_Drag a DnD drag source:
m_Button_Drag.drag_source_set(listTargets);
//Connect signals:
m_Button_Drag.signal_drag_data_get().connect(sigc::mem_fun(*this,
&DnDWindow::on_button_drag_data_get));
m_HBox.pack_start(m_Button_Drag);
//Drop site:
//Make m_Label_Drop a DnD drop destination:
m_Label_Drop.drag_dest_set(listTargets);
//Connect signals:
m_Label_Drop.signal_drag_data_received().connect(sigc::mem_fun(*this,
&DnDWindow::on_label_drop_drag_data_received) );
m_HBox.pack_start(m_Label_Drop);
show_all();
}
DnDWindow::~DnDWindow()
{
}
void DnDWindow::on_button_drag_data_get(
const Glib::RefPtr<Gdk::DragContext>&,
Gtk::SelectionData& selection_data, guint, guint)
{
selection_data.set(selection_data.get_target(), 8 /* 8 bits format */,
(const guchar*)"I'm Data!",
9 /* the length of I'm Data! in bytes */);
}
void DnDWindow::on_label_drop_drag_data_received(
const Glib::RefPtr<Gdk::DragContext>& context, int, int,
const Gtk::SelectionData& selection_data, guint, guint time)
{
const int length = selection_data.get_length();
if((length >= 0) && (selection_data.get_format() == 8))
{
std::cout << "Received \"" << selection_data.get_data_as_string()
<< "\" in label " << std::endl;
}
context->drag_finish(false, false, time);
}
</programlisting>
<!-- end inserted example code -->
<para>Hay un ejemplo más complejo en examples/others/dnd.</para>
</sect1>
</chapter>
<chapter id="chapter-clipboard">
<title>El portapapeles</title>
<para>Widgets libres como <classname>Gtk::Entry</classname> y <classname>Gtk::TextView</classname>proporcionan una función de copiar y pegar texto simple, pero tal vez necesite código especial para manejar sus propios formatos de datos. Por ejemplo, un programa de dibujo necesitaría código especial para permitir copiar y pegar dentro de una vista, o entre documentos.</para>
<para><classname>Gtk::Clipboard</classname> es un «singleton». Puede obtener la instancia predeterminada del portapapeles con <methodname>Gtk::Clipboard::get()</methodname>. Esta es, probablemente, el único portapapeles que necesitará.</para>
<para>Para que su aplicación no necesite esperar a operaciones de portapapeles, particularmente en el tiempo en el que el usuario elige «copiar» y luego «pegar», la mayoría de los métodos de <classname>Gtk::Clipboard</classname> toman <classname>sigc::slot</classname> que especifican métodos de retorno de llamada. Cuando <classname>Gtk::Clipboard</classname> esté listo, llamará a estos métodos, proporcionándoles los datos o bien pidiéndolos.</para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Clipboard.html">Reference</ulink></para>
<sect1 id="sec-clipboard-targets">
<title>Objetivos</title>
<para>Diferentes aplicaciones contienen diferentes tipos de datos, y podrían hacer esos datos disponibles en una variedad de formatos. <application>gtkmm</application> llama a estos tipos de datos <literal>objetivos</literal>.</para>
<para>Por ejemplo, <application>gedit</application> puede proporcionar y recibir el objetivo <literal>"UTF8_STRING"</literal>, para que pueda pegar datos en <application>gedit</application> desde cualquier aplicación que proporcione ese objetivo. O bien, dos aplicaciones de edición de imágenes diferentes podrían proporcionar y recibir una variedad de formatos de imágenes como objetivos. Mientras que una aplicación pueda recibir uno de los objetivos que la otra proporciona, entonces podrá copiar los datos de una a la otra.</para>
<para>Un objetivo puede estar en una variedad de formatos binarios. Este capítulo, y los ejemplos, asumen que los datos están en texto de 8 bits. Esto permite usar un formato XML para los datos del portapapeles. Sin embargo, probablemente no sea apropiado para datos binarios como imágenes. <classname>Gtk::Clipboard</classname> proporciona sobrecargas que le permiten especificar el formato en mayor detalle si es necesario.</para>
<para>La API <link linkend="chapter-draganddrop">Arrastrar y soltar</link> usa el mismo mecanismo. Probablemente deba usar los mismos objetivos de datos y formatos para las operaciones de arrastrar y soltar así como para las de portapapeles.</para>
</sect1>
<sect1 id="sec-clipboard-copy">
<title>Copiar</title>
<para>Cuando el usuario pide copiar datos, debe decirle al <classname>Clipboard</classname> qué objetivos están disponibles y proporcionar los métodos de retorno de llamada que puede usar para obtener los datos. En este punto, debe almacenar una copia de los datos, para proporcionarla cuando el portapapeles llame a su método de retorno de llamada en respuesta a la acción de pegar.</para>
<para>Por ejemplo,</para>
<programlisting>Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
//Targets:
std::vector<Gtk::TargetEntry> targets;
targets.push_back( Gtk::TargetEntry("example_custom_target") );
targets.push_back( Gtk::TargetEntry("UTF8_STRING") );
refClipboard->set( targets,
sigc::mem_fun(*this, &ExampleWindow::on_clipboard_get),
sigc::mem_fun(*this, &ExampleWindow::on_clipboard_clear) );</programlisting>
<para>Su retorno de llamada proporcionará entonces los datos almacenados cuando el usuario elija pegarlos. Por ejemplo:</para>
<programlisting>void ExampleWindow::on_clipboard_get(
Gtk::SelectionData& selection_data, guint /* info */)
{
const std::string target = selection_data.get_target();
if(target == "example_custom_target")
selection_data.set("example_custom_target", m_ClipboardStore);
}</programlisting>
<para>El ejemplo <literal>ideal</literal> a continuación puede proporcionar más de un objetivo para el portapapeles.</para>
<para>El retorno de llamada «clear» le permite liberar la memoria que sus datos almacenados usan cuando el portapapeles reemplaza sus datos con otra cosa.</para>
</sect1>
<sect1 id="sec-clipboard-paste">
<title>Pegar</title>
<para>Cuando el usuario pide pegar datos desde el <classname>Clipboard</classname>, debe pedir un formato específico y proporcionar un método de retorno de llamada que se llamará con los datos en sí. Por ejemplo:</para>
<programlisting>refClipboard->request_contents("example_custom_target",
sigc::mem_fun(*this, &ExampleWindow::on_clipboard_received) );</programlisting>
<para>Aquí hay un ejemplo de un método de retorno de llamada:</para>
<programlisting>void ExampleWindow::on_clipboard_received(
const Gtk::SelectionData& selection_data)
{
Glib::ustring clipboard_data = selection_data.get_data_as_string();
//Do something with the pasted data.
}</programlisting>
<sect2 id="dnd-discovering-targets">
<title>Descubrir los objetivos disponibles</title>
<para>Para descubrir qué objetivos están actualmente disponibles en el <classname>Clipboard</classname> para pegar, llame al método <methodname>request_targets()</methodname>, especificando un método al que llamar con la información. Por ejemplo:</para>
<programlisting>refClipboard->request_targets( sigc::mem_fun(*this,
&ExampleWindow::on_clipboard_received_targets) );</programlisting>
<para>En su retorno de llamada, compare la lista de objetivos disponibles con aquellos que su aplicación soporta pegar. Puede activar o no el elemento en el menú «pegar», dependiendo de si pegar es posible o no actualmente. Por ejemplo:</para>
<programlisting>void ExampleWindow::on_clipboard_received_targets(
const std::vector<Glib::ustring>& targets)
{
const bool bPasteIsPossible =
std::find(targets.begin(), targets.end(),
example_target_custom) != targets.end();
// Enable/Disable the Paste button appropriately:
m_Button_Paste.set_sensitive(bPasteIsPossible);
}</programlisting>
</sect2>
</sect1>
<sect1 id="sec-clipboard-examples"><title>Ejemplos</title>
<sect2 id="sec-clipboard-example-simple"><title>Simple</title>
<para>Este ejemplo permite copiar y pegar datos específicos de la aplicación, usando el objetivo estándar de texto. A pesar de que esto es simple, no es lo ideal porque no identifica los datos del <classname>Clipboard</classname> como un tipo particular.</para>
<figure id="figure-clipboard-simple">
<title>Portapapeles: simple</title>
<screenshot>
<graphic format="PNG" fileref="figures/clipboard_simple.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/clipboard/simple/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_copy();
void on_button_paste();
void on_clipboard_text_received(const Glib::ustring& text);
//Child widgets:
Gtk::Box m_VBox;
Gtk::Label m_Label;
Gtk::Grid m_Grid;
Gtk::ToggleButton m_ButtonA1, m_ButtonA2, m_ButtonB1, m_ButtonB2;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Copy, m_Button_Paste;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Label("Select cells in the grid, click Copy, then open a second "
"instance of this example to try pasting the copied data."),
m_ButtonA1("A1"), m_ButtonA2("A2"), m_ButtonB1("B1"), m_ButtonB2("B2"),
m_Button_Copy("_Copy", /* mnemonic= */ true), m_Button_Paste("_Paste", true)
{
set_title("Gtk::Clipboard example");
set_border_width(12);
add(m_VBox);
m_VBox.pack_start(m_Label, Gtk::PACK_SHRINK);
//Fill Grid:
m_VBox.pack_start(m_Grid);
m_Grid.set_row_homogeneous(true);
m_Grid.set_column_homogeneous(true);
m_Grid.attach(m_ButtonA1, 0, 0, 1, 1);
m_Grid.attach(m_ButtonA2, 1, 0, 1, 1);
m_Grid.attach(m_ButtonB1, 0, 1, 1, 1);
m_Grid.attach(m_ButtonB2, 1, 1, 1, 1);
//Add ButtonBox to bottom:
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_VBox.set_spacing(6);
//Fill ButtonBox:
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_ButtonBox.pack_start(m_Button_Copy, Gtk::PACK_SHRINK);
m_Button_Copy.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_copy) );
m_ButtonBox.pack_start(m_Button_Paste, Gtk::PACK_SHRINK);
m_Button_Paste.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_paste) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_copy()
{
//Build a string representation of the stuff to be copied:
//Ideally you would use XML, with an XML parser here:
Glib::ustring strData;
strData += m_ButtonA1.get_active() ? "1" : "0";
strData += m_ButtonA2.get_active() ? "1" : "0";
strData += m_ButtonB1.get_active() ? "1" : "0";
strData += m_ButtonB2.get_active() ? "1" : "0";
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
refClipboard->set_text(strData);
}
void ExampleWindow::on_button_paste()
{
//Tell the clipboard to call our method when it is ready:
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
refClipboard->request_text(sigc::mem_fun(*this,
&ExampleWindow::on_clipboard_text_received) );
}
void ExampleWindow::on_clipboard_text_received(const Glib::ustring& text)
{
//See comment in on_button_copy() about this silly clipboard format.
if(text.size() >= 4)
{
m_ButtonA1.set_active( text[0] == '1' );
m_ButtonA2.set_active( text[1] == '1' );
m_ButtonB1.set_active( text[2] == '1' );
m_ButtonB2.set_active( text[3] == '1' );
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
//APPLICATION_NON_UNIQUE because it shall be possible to run several
//instances of this application simultaneously.
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(
argc, argv, "org.gtkmm.example", Gio::APPLICATION_NON_UNIQUE);
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
<sect2 id="sec-clipboard-example-ideal"><title>Ideal</title>
<para lang="en">This is like the simple example, but it
<orderedlist>
<listitem><simpara lang="en">Defines a custom clipboard target, though the format of that target is still text.</simpara></listitem>
<listitem><simpara lang="en">It supports pasting of 2 targets - both the custom one and a text one that creates an arbitrary text representation of the custom data.</simpara></listitem>
<listitem><simpara lang="en">It uses <methodname>request_targets()</methodname> and the <literal>owner_change</literal> signal and disables the Paste button if it can't use anything on the clipboard.</simpara></listitem>
</orderedlist>
</para>
<figure id="figure-clipboard-ideal">
<title>Portapapeles: ideal</title>
<screenshot>
<graphic format="PNG" fileref="figures/clipboard_ideal.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/clipboard/ideal/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_copy();
void on_button_paste();
void on_clipboard_owner_change(GdkEventOwnerChange* event);
void on_clipboard_get(Gtk::SelectionData& selection_data, guint info);
void on_clipboard_clear();
void on_clipboard_received(const Gtk::SelectionData& selection_data);
void on_clipboard_received_targets(const std::vector<Glib::ustring>& targets);
virtual void update_paste_status(); //Disable the paste button if there is nothing to paste.
//Child widgets:
Gtk::Box m_VBox;
Gtk::Label m_Label;
Gtk::Grid m_Grid;
Gtk::ToggleButton m_ButtonA1, m_ButtonA2, m_ButtonB1, m_ButtonB2;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Copy, m_Button_Paste;
Glib::ustring m_ClipboardStore; //Keep copied stuff here, until it is pasted. This could be a big complex data structure.
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <algorithm>
namespace
{
//These should usually be MIME types.
const char example_target_custom[] = "gtkmmclipboardexample";
const char example_target_text[] = "UTF8_STRING";
} // anonymous namespace
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Label("Select cells in the grid, click Copy, then open a second instance "
"of this example to try pasting the copied data.\nOr try pasting the "
"text representation into gedit."),
m_ButtonA1("A1"), m_ButtonA2("A2"), m_ButtonB1("B1"), m_ButtonB2("B2"),
m_Button_Copy("_Copy", /* mnemonic= */ true), m_Button_Paste("_Paste", true)
{
set_title("Gtk::Clipboard example");
set_border_width(12);
add(m_VBox);
m_VBox.pack_start(m_Label, Gtk::PACK_SHRINK);
//Fill Grid:
m_VBox.pack_start(m_Grid);
m_Grid.set_row_homogeneous(true);
m_Grid.set_column_homogeneous(true);
m_Grid.attach(m_ButtonA1, 0, 0, 1, 1);
m_Grid.attach(m_ButtonA2, 1, 0, 1, 1);
m_Grid.attach(m_ButtonB1, 0, 1, 1, 1);
m_Grid.attach(m_ButtonB2, 1, 1, 1, 1);
//Add ButtonBox to bottom:
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_VBox.set_spacing(6);
//Fill ButtonBox:
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_ButtonBox.pack_start(m_Button_Copy, Gtk::PACK_SHRINK);
m_Button_Copy.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_copy) );
m_ButtonBox.pack_start(m_Button_Paste, Gtk::PACK_SHRINK);
m_Button_Paste.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_paste) );
//Connect a signal handler that will be called when the contents of
//the clipboard change.
Gtk::Clipboard::get()->signal_owner_change().connect(sigc::mem_fun(*this,
&ExampleWindow::on_clipboard_owner_change) );
show_all_children();
update_paste_status();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_copy()
{
//Build a string representation of the stuff to be copied:
//Ideally you would use XML, with an XML parser here:
Glib::ustring strData;
strData += m_ButtonA1.get_active() ? "1" : "0";
strData += m_ButtonA2.get_active() ? "1" : "0";
strData += m_ButtonB1.get_active() ? "1" : "0";
strData += m_ButtonB2.get_active() ? "1" : "0";
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
//Targets:
std::vector<Gtk::TargetEntry> targets;
targets.push_back( Gtk::TargetEntry(example_target_custom) );
targets.push_back( Gtk::TargetEntry(example_target_text) );
refClipboard->set(targets,
sigc::mem_fun(*this, &ExampleWindow::on_clipboard_get),
sigc::mem_fun(*this, &ExampleWindow::on_clipboard_clear) );
//Store the copied data until it is pasted:
//(Must be done after the call to refClipboard->set(), because that call
//may trigger a call to on_clipboard_clear.)
m_ClipboardStore = strData;
update_paste_status();
}
void ExampleWindow::on_button_paste()
{
//Tell the clipboard to call our method when it is ready:
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
refClipboard->request_contents(example_target_custom,
sigc::mem_fun(*this, &ExampleWindow::on_clipboard_received) );
update_paste_status();
}
void ExampleWindow::on_clipboard_owner_change(GdkEventOwnerChange*)
{
update_paste_status();
}
void ExampleWindow::on_clipboard_get(Gtk::SelectionData& selection_data,
guint /* info */)
{
// info corresponds to the optional info parameter in Gtk::TargetEntry's
// constructor. We don't use that, so we use selection_data's target instead.
const std::string target = selection_data.get_target();
if(target == example_target_custom)
{
// This set() override uses an 8-bit text format for the data.
selection_data.set(example_target_custom, m_ClipboardStore);
}
else if(target == example_target_text)
{
//Build some arbitrary text representation of the data,
//so that people see something when they paste into a text editor:
Glib::ustring text_representation;
text_representation += m_ButtonA1.get_active() ? "A1, " : "";
text_representation += m_ButtonA2.get_active() ? "A2, " : "";
text_representation += m_ButtonB1.get_active() ? "B1, " : "";
text_representation += m_ButtonB2.get_active() ? "B2, " : "";
selection_data.set_text(text_representation);
}
else
{
g_warning("ExampleWindow::on_clipboard_get(): "
"Unexpected clipboard target format.");
}
}
void ExampleWindow::on_clipboard_clear()
{
//This isn't really necessary. I guess it might save memory.
m_ClipboardStore.clear();
}
void ExampleWindow::on_clipboard_received(
const Gtk::SelectionData& selection_data)
{
const std::string target = selection_data.get_target();
//It should always be this, because that's what we asked for when calling
//request_contents().
if(target == example_target_custom)
{
Glib::ustring clipboard_data = selection_data.get_data_as_string();
//See comment in on_button_copy() about this silly clipboard format.
if(clipboard_data.size() >= 4)
{
m_ButtonA1.set_active( clipboard_data[0] == '1' );
m_ButtonA2.set_active( clipboard_data[1] == '1' );
m_ButtonB1.set_active( clipboard_data[2] == '1' );
m_ButtonB2.set_active( clipboard_data[3] == '1' );
}
}
}
void ExampleWindow::update_paste_status()
{
//Disable the paste button if there is nothing to paste.
Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
//Discover what targets are available:
refClipboard->request_targets(sigc::mem_fun(*this,
&ExampleWindow::on_clipboard_received_targets) );
}
void ExampleWindow::on_clipboard_received_targets(
const std::vector<Glib::ustring>& targets)
{
const bool bPasteIsPossible =
std::find(targets.begin(), targets.end(),
example_target_custom) != targets.end();
// Enable/Disable the Paste button appropriately:
m_Button_Paste.set_sensitive(bPasteIsPossible);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
//APPLICATION_NON_UNIQUE because it shall be possible to run several
//instances of this application simultaneously.
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(
argc, argv, "org.gtkmm.example", Gio::APPLICATION_NON_UNIQUE);
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-printing">
<title>Impresión</title>
<para lang="en">
At the application development level, <application>gtkmm</application>'s printing API
provides dialogs that are consistent across applications and allows use of Cairo's common drawing API, with Pango-driven text rendering. In the implementation of this common API, platform-specific backends and printer-specific drivers are used.
</para>
<sect1 id="sec-printoperation">
<title>PrintOperation</title>
<para>El objeto primario es <classname>Gtk::PrintOperation</classname>, reservado por cada operación de impresión. Para manejar el dibujo de una página, conecte sus señales, o herede de él y sobrecargue los manejadores de señales virtuales predeterminados. <classname>PrintOperation</classname> maneja automáticamente todas las opciones que afectan al bucle de impresión.</para>
<sect2 id="sec-printoperation-signals">
<title>Señales</title>
<para lang="en">
The <methodname>PrintOperation::run()</methodname> method starts the print loop,
during which various signals are emitted:
<itemizedlist>
<listitem>
<para lang="en">
<literal>begin_print</literal>:
You must handle this signal, because this is where you
create and set up a <classname>Pango::Layout</classname> using the
provided <classname>Gtk::PrintContext</classname>, and break up your
printing output into pages.
</para>
</listitem>
<listitem>
<para lang="en">
<literal>paginate</literal>: Pagination is potentially slow so if you
need to monitor it you can call the
<methodname>PrintOperation::set_show_progress()</methodname> method and
handle this signal.
</para>
</listitem>
<listitem>
<para lang="en">
For each page that needs to be rendered, the following signals
are emitted:
<itemizedlist>
<listitem>
<para lang="en">
<literal>request_page_setup</literal>: Provides a
<classname>PrintContext</classname>, page number and
<classname>Gtk::PageSetup</classname>. Handle this signal if you
need to modify page setup on a per-page basis.
</para>
</listitem>
<listitem>
<para lang="en">
<literal>draw_page</literal>: You must handle this signal, which provides a
<classname>PrintContext</classname> and a page number.
The <classname>PrintContext</classname> should be used
to create a <classname>Cairo::Context</classname> into which
the provided page should be drawn. To render text, iterate over
the <classname>Pango::Layout</classname> you created in the
<literal>begin_print</literal> handler.
</para>
</listitem>
</itemizedlist>
</para>
</listitem>
<listitem>
<para lang="en">
<literal>end_print</literal>: A handler for it is a safe place to free
any resources related to a <classname>PrintOperation</classname>.
If you have your custom class that inherits from
<classname>PrintOperation</classname>, it is naturally simpler to do it
in the destructor.
</para>
</listitem>
<listitem>
<para lang="en">
<literal>done</literal>: This signal is emitted when printing is finished, meaning when the
print data is spooled. Note that the provided
<literal>Gtk::PrintOperationResult</literal> may indicate that
an error occurred. In any case you probably want to notify the user
about the final status.
</para>
</listitem>
<listitem>
<para lang="en">
<literal>status_changed</literal>: Emitted whenever a print job's
status changes, until it is finished. Call the
<methodname>PrintOperation::set_track_print_status()</methodname> method to
monitor the job status after spooling. To see the status, use
<methodname>get_status()</methodname> or
<methodname>get_status_string()</methodname>.
</para>
</listitem>
</itemizedlist>
</para>
<para lang="en">
<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PrintOperation.html">Reference</ulink>
</para>
</sect2>
</sect1>
<sect1 id="sec-page-setup">
<title>Configuración de página</title>
<para>La clase <classname>PrintOperation</classname> tiene un método llamado <methodname>set_default_page_setup()</methodname> que selecciona el tamaño de papel, orientación y márgenes predeterminados. Para mostrar un diálogo de configuración de página desde su aplicación, use el método <methodname>Gtk::run_page_setup_dialog()</methodname>, que devuelve un objeto <classname>Gtk::PageSetup()</classname> con la configuración elegida. Use este objeto para actualizar una <classname>PrintOperation</classname> y acceder a <classname>Gtk::PaperSize</classname>, <literal>Gtk::PageOrientation</literal> y los márgenes específicos de la impresora.</para>
<para>Debe guardar la <classname>Gtk::PageSetup</classname> elegida para poder usarla luego si se vuelve a mostrar el diálogo de configuración de la página.</para>
<para lang="en">For instance,
<programlisting lang="en">
//Within a class that inherits from Gtk::Window and keeps m_refPageSetup and m_refSettings as members...
Glib::RefPtr<Gtk::PageSetup> new_page_setup = Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
m_refPageSetup = new_page_setup;
</programlisting>
</para>
<para lang="en">
<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PageSetup.html">Reference</ulink>
</para>
<para>El sistema de coordenadas de Cairo, en el manejador <literal>draw_page</literal>, rota automáticamente a la orientación de la página actual. Normalmente está dentro de los márgenes de la impresora, pero puede cambiar esto mediante el método <methodname>PrintOperation::set_use_full_page()</methodname>. La unidad de medida predeterminada es el píxel del dispositivo. Para seleccionar otras unidades, use el método <methodname>PrintOperation::set_unit()</methodname>.</para>
</sect1>
<sect1 id="sec-printing-rendering-text">
<title>Renderizar texto</title>
<para>El texto se renderiza usando Pango. El objeto <classname>Pango::Layout</classname> para la impresión debe crearse llamando al método <methodname>PrintContext::create_pango_layout()</methodname>. El objeto <classname>PrintContext</classname> también proporciona las medidas de la página, mediante <methodname>get_width()</methodname> y <methodname>get_height()</methodname>. El número de páginas puede establecerse con <methodname>PrintOperation::set_n_pages()</methodname>. Para renderizar el texto de Pango en <literal>on_draw_page</literal>, obtenga un <classname>Cairo::Context</classname> con <methodname>PrintContext::get_cairo_context()</methodname> y haga visibles las <classname>Pango::LayoutLine</classname> que aparecen dentro del número de página pedido.</para>
<para>Consulte <link linkend="sec-printing-example-simple">un ejemplo</link> de cómo realizar esto exactamente. </para>
</sect1>
<sect1 id="sec-async-printing-ops">
<title>Operaciones asíncronas</title>
<para>De manera predeterminada, <methodname>PrintOperation::run()</methodname> retorna cuando una operación de impresión ha terminado. Si necesite ejecutar una operación no modal de impresión, llame a <methodname>PrintOperation::set_allow_async()</methodname>. Tenga en cuenta que, a pesar de que no todas las plataformas soportan <methodname>set_allow_async()</methodname>, la señal <literal>done</literal> se emitirá de todos modos.</para>
<para><methodname>run()</methodname> puede devolver <literal>PRINT_OPERATION_RESULT_IN_PROGRESS</literal>. Para rastrear el estado y manejar el resultado de un error, necesita implementar manejadores de las señales <literal>done</literal> y <literal>status_changed</literal>.</para>
<para lang="en">For instance,
<programlisting lang="en">
// in class ExampleWindow's method...
Glib::RefPtr<PrintOperation> op = PrintOperation::create();
// ...set up op...
op->signal_done().connect(sigc::bind(sigc::mem_fun(*this, &ExampleWindow::on_printoperation_done), op));
// run the op
</programlisting>
</para>
<para lang="en">Second, check for an error and connect to the <literal>status_changed</literal> signal. For instance:
<programlisting lang="en">
void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result, const Glib::RefPtr<PrintOperation>& op)
{
if (result == Gtk::PRINT_OPERATION_RESULT_ERROR)
//notify user
else if (result == Gtk::PRINT_OPERATION_RESULT_APPLY)
//Update PrintSettings with the ones used in this PrintOperation
if (! op->is_finished())
op->signal_status_changed().connect(sigc::bind(sigc::mem_fun(*this, &ExampleWindow::on_printoperation_status_changed), op));
}
</programlisting>
</para>
<para lang="en">Finally, check the status. For instance,
<programlisting lang="en">
void ExampleWindow::on_printoperation_status_changed(const Glib::RefPtr<PrintFormOperation>& op)
{
if (op->is_finished())
//the print job is finished
else
//get the status with get_status() or get_status_string()
//update UI
}
</programlisting>
</para>
</sect1>
<sect1 id="sec-printing-export-to-pdf">
<title>Exportar a PDF</title>
<para lang="en">
The 'Print to file' option is available in the print dialog, without the need for extra implementation. However, it is sometimes useful to generate a pdf file directly from code. For instance,
<programlisting lang="en">
Glib::RefPtr<Gtk::PrintOperation> op = Gtk::PrintOperation::create();
// ...set up op...
op->set_export_filename("test.pdf");
Gtk::PrintOperationResult res = op->run(Gtk::PRINT_OPERATION_ACTION_EXPORT);
</programlisting>
</para>
</sect1>
<sect1 id="sec-extending-print-dialog">
<title>Extender el diálogo de impresión</title>
<para lang="en">
You may add a custom tab to the print dialog:
<itemizedlist>
<listitem>
<para lang="en">
Set the title of the tab via
<methodname>PrintOperation::set_custom_tab_label()</methodname>,
create a new widget and return it from the
<literal>create_custom_widget</literal> signal handler. You'll probably
want this to be a container widget, packed with some others.
</para>
</listitem>
<listitem>
<para lang="en">
Get the data from the widgets in the
<literal>custom_widget_apply</literal> signal handler.
</para>
</listitem>
</itemizedlist>
</para>
<para lang="en">
Although the <literal>custom_widget_apply</literal> signal provides the widget you
previously created, to simplify things you can keep the widgets you expect
to contain some user input as class members. For example, let's say you have
a <classname>Gtk::Entry</classname> called <literal>m_Entry</literal> as
a member of your <classname>CustomPrintOperation</classname> class:
<programlisting lang="en">
Gtk::Widget* CustomPrintOperation::on_create_custom_widget()
{
set_custom_tab_label("My custom tab");
Gtk::Box* hbox = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 8);
hbox->set_border_width(6);
Gtk::Label* label = Gtk::manage(new Gtk::Label("Enter some text: "));
hbox->pack_start(*label, false, false);
label->show();
hbox->pack_start(m_Entry, false, false);
m_Entry.show();
return hbox;
}
void CustomPrintOperation::on_custom_widget_apply(Gtk::Widget* /* widget */)
{
Glib::ustring user_input = m_Entry.get_text();
//...
}
</programlisting>
</para>
<para>El ejemplo en examples/book/printing/advanced demuestra esto.</para>
</sect1>
<sect1 id="sec-printing-preview">
<title>Vista previa</title>
<para lang="en">
The native GTK+ print dialog has a preview button, but you may also start
a preview directly from an application:
<programlisting lang="en">
// in a class that inherits from Gtk::Window...
Glib::RefPtr<PrintOperation> op = PrintOperation::create();
// ...set up op...
op->run(Gtk::PRINT_OPERATION_ACTION_PREVIEW, *this);
</programlisting>
</para>
<para>En Unix, el manejador de previsualización predeterminado usa un programa visor externo. En Windows, se mostrará el diálogo nativo de previsualización. Si es necesario, puede modificar este comportamiento y proporcionar un diálogo de previsualización personalizado. Consulte el ejemplo en /examples/book/printing/advanced.</para>
</sect1>
<sect1 id="sec-printing-example">
<title>Ejemplo</title>
<sect2 id="sec-printing-example-simple">
<title>Simple</title>
<para>El siguiente ejemplo demuestra cómo imprimir entrada desde una interfaz de usuario. Muestra cómo implementar <literal>on_begin_print</literal> y <literal>on_draw_page</literal>, como también cómo rastrear el estado de la impresión y actualizar sus opciones.</para>
<figure id="figure-printing-simple">
<title>Impresión simple</title>
<screenshot>
<graphic format="PNG" fileref="figures/printing.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/printing/simple/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class PrintFormOperation;
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
void build_main_menu();
void print_or_preview(Gtk::PrintOperationAction print_action);
//PrintOperation signal handlers.
//We handle these so can get necessary information to update the UI or print settings.
//Our derived PrintOperation class also overrides some default signal handlers.
void on_printoperation_status_changed(const Glib::RefPtr<PrintFormOperation>& operation);
void on_printoperation_done(Gtk::PrintOperationResult result, const Glib::RefPtr<PrintFormOperation>& operation);
//Action signal handlers:
void on_menu_file_new();
void on_menu_file_page_setup();
void on_menu_file_print_preview();
void on_menu_file_print();
void on_menu_file_quit();
//Printing-related objects:
Glib::RefPtr<Gtk::PageSetup> m_refPageSetup;
Glib::RefPtr<Gtk::PrintSettings> m_refSettings;
//Child widgets:
Gtk::Box m_VBox;
Gtk::Grid m_Grid;
Gtk::Label m_NameLabel;
Gtk::Entry m_NameEntry;
Gtk::Label m_SurnameLabel;
Gtk::Entry m_SurnameEntry;
Gtk::Label m_CommentsLabel;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer;
unsigned m_ContextId;
Gtk::Statusbar m_Statusbar;
Glib::RefPtr<Gtk::Builder> m_refBuilder;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>printformoperation.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_PRINT_FORM_OPERATION_H
#define GTKMM_PRINT_FORM_OPERATION_H
#include <gtkmm.h>
#include <pangomm.h>
#include <vector>
//We derive our own class from PrintOperation,
//so we can put the actual print implementation here.
class PrintFormOperation : public Gtk::PrintOperation
{
public:
static Glib::RefPtr<PrintFormOperation> create();
virtual ~PrintFormOperation();
void set_name(const Glib::ustring& name) { m_Name = name; }
void set_comments(const Glib::ustring& comments) { m_Comments = comments; }
protected:
PrintFormOperation();
//PrintOperation default signal handler overrides:
virtual void on_begin_print(const Glib::RefPtr<Gtk::PrintContext>& context);
virtual void on_draw_page(const Glib::RefPtr<Gtk::PrintContext>& context, int page_nr);
Glib::ustring m_Name;
Glib::ustring m_Comments;
Glib::RefPtr<Pango::Layout> m_refLayout;
std::vector<int> m_PageBreaks; // line numbers where a page break occurs
};
#endif // GTKMM_PRINT_FORM_OPERATION_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include "printformoperation.h"
#include <iostream>
#include <pangomm.h>
const Glib::ustring app_title = "gtkmm Printing Example";
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_NameLabel("Name"),
m_SurnameLabel("Surname"),
m_CommentsLabel("Comments")
{
m_refPageSetup = Gtk::PageSetup::create();
m_refSettings = Gtk::PrintSettings::create();
m_ContextId = m_Statusbar.get_context_id(app_title);
set_title(app_title);
set_default_size(400, 300);
add(m_VBox);
build_main_menu();
m_VBox.pack_start(m_Grid);
//Arrange the widgets inside the grid:
m_Grid.set_row_spacing(5);
m_Grid.set_column_spacing(5);
m_Grid.attach(m_NameLabel, 0, 0, 1, 1);
m_Grid.attach(m_NameEntry, 1, 0, 1, 1);
m_Grid.attach(m_SurnameLabel, 0, 1, 1, 1);
m_Grid.attach(m_SurnameEntry, 1, 1, 1, 1);
//Add the TextView, inside a ScrolledWindow:
m_ScrolledWindow.add(m_TextView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_Grid.attach(m_CommentsLabel, 0, 2, 1, 1);
m_Grid.attach(m_ScrolledWindow, 1, 2, 1, 1);
m_ScrolledWindow.set_hexpand(true);
m_ScrolledWindow.set_vexpand(true);
m_refTextBuffer = Gtk::TextBuffer::create();
m_TextView.set_buffer(m_refTextBuffer);
m_VBox.pack_start(m_Statusbar);
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::build_main_menu()
{
//Create actions for menus and toolbars:
Glib::RefPtr<Gio::SimpleActionGroup> refActionGroup =
Gio::SimpleActionGroup::create();
//File menu:
refActionGroup->add_action("new",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new));
refActionGroup->add_action("pagesetup",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_page_setup));
refActionGroup->add_action("printpreview",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_print_preview));
refActionGroup->add_action("print",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_print));
refActionGroup->add_action("quit",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_quit));
insert_action_group("example", refActionGroup);
m_refBuilder = Gtk::Builder::create();
//TODO: add_accel_group(m_refBuilder->get_accel_group());
//Layout the actions in a menubar and toolbar:
Glib::ustring ui_info =
"<interface>"
" <menu id='menu-example'>"
" <submenu>"
" <attribute name='label' translatable='yes'>_File</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>Page _Setup</attribute>"
" <attribute name='action'>example.pagesetup</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Print Preview</attribute>"
" <attribute name='action'>example.printpreview</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>_Print</attribute>"
" <attribute name='action'>example.print</attribute>"
" </item>"
" </section>"
" </submenu>"
" </menu>"
/* TODO:
" <toolbar name='ToolBar'>"
" <toolitem action='New'/>"
" <toolitem action='Print'/>"
" <separator/>"
" <toolitem action='Quit'/>"
" </toolbar>"
*/
"</interface>";
try
{
m_refBuilder->add_from_string(ui_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building menus failed: " << ex.what();
}
//Get the menubar and toolbar widgets, and add them to a container widget:
Glib::RefPtr<Glib::Object> object =
m_refBuilder->get_object("menu-example");
Glib::RefPtr<Gio::Menu> gmenu =
Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
if(!gmenu)
g_warning("GMenu not found");
Gtk::MenuBar* pMenubar = new Gtk::MenuBar(gmenu);
m_VBox.pack_start(*pMenubar, Gtk::PACK_SHRINK);
/* TODO:
Gtk::Widget* pToolbar = m_refBuilder->get_widget("/ToolBar") ;
if(pToolbar)
m_VBox.pack_start(*pToolbar, Gtk::PACK_SHRINK);
*/
}
void ExampleWindow::on_printoperation_status_changed(
const Glib::RefPtr<PrintFormOperation>& operation)
{
Glib::ustring status_msg;
if (operation->is_finished())
{
status_msg = "Print job completed.";
}
else
{
//You could also use get_status().
status_msg = operation->get_status_string();
}
m_Statusbar.push(status_msg, m_ContextId);
}
void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result,
const Glib::RefPtr<PrintFormOperation>& operation)
{
//Printing is "done" when the print data is spooled.
if (result == Gtk::PRINT_OPERATION_RESULT_ERROR)
{
Gtk::MessageDialog err_dialog(*this, "Error printing form", false,
Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
err_dialog.run();
}
else if (result == Gtk::PRINT_OPERATION_RESULT_APPLY)
{
//Update PrintSettings with the ones used in this PrintOperation:
m_refSettings = operation->get_print_settings();
}
if (! operation->is_finished())
{
//We will connect to the status-changed signal to track status
//and update a status bar. In addition, you can, for example,
//keep a list of active print operations, or provide a progress dialog.
operation->signal_status_changed().connect(sigc::bind(sigc::mem_fun(*this,
&ExampleWindow::on_printoperation_status_changed),
operation));
}
}
void ExampleWindow::print_or_preview(Gtk::PrintOperationAction print_action)
{
//Create a new PrintOperation with our PageSetup and PrintSettings:
//(We use our derived PrintOperation class)
Glib::RefPtr<PrintFormOperation> print = PrintFormOperation::create();
print->set_name(m_NameEntry.get_text() + " " + m_SurnameEntry.get_text());
print->set_comments(m_refTextBuffer->get_text(false /*Don't include hidden*/));
print->set_track_print_status();
print->set_default_page_setup(m_refPageSetup);
print->set_print_settings(m_refSettings);
print->signal_done().connect(sigc::bind(sigc::mem_fun(*this,
&ExampleWindow::on_printoperation_done), print));
try
{
print->run(print_action /* print or preview */, *this);
}
catch (const Gtk::PrintError& ex)
{
//See documentation for exact Gtk::PrintError error codes.
std::cerr << "An error occurred while trying to run a print operation:"
<< ex.what() << std::endl;
}
}
void ExampleWindow::on_menu_file_new()
{
//Clear entries and textview:
m_NameEntry.set_text("");
m_SurnameEntry.set_text("");
m_refTextBuffer->set_text("");
m_TextView.set_buffer(m_refTextBuffer);
}
void ExampleWindow::on_menu_file_page_setup()
{
//Show the page setup dialog, asking it to start with the existing settings:
Glib::RefPtr<Gtk::PageSetup> new_page_setup =
Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
//Save the chosen page setup dialog for use when printing, previewing, or
//showing the page setup dialog again:
m_refPageSetup = new_page_setup;
}
void ExampleWindow::on_menu_file_print_preview()
{
print_or_preview(Gtk::PRINT_OPERATION_ACTION_PREVIEW);
}
void ExampleWindow::on_menu_file_print()
{
print_or_preview(Gtk::PRINT_OPERATION_ACTION_PRINT_DIALOG);
}
void ExampleWindow::on_menu_file_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>printformoperation.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "printformoperation.h"
PrintFormOperation::PrintFormOperation()
{
}
PrintFormOperation::~PrintFormOperation()
{
}
Glib::RefPtr<PrintFormOperation> PrintFormOperation::create()
{
return Glib::RefPtr<PrintFormOperation>(new PrintFormOperation());
}
void PrintFormOperation::on_begin_print(
const Glib::RefPtr<Gtk::PrintContext>& print_context)
{
//Create and set up a Pango layout for PrintData based on the passed
//PrintContext: We then use this to calculate the number of pages needed, and
//the lines that are on each page.
m_refLayout = print_context->create_pango_layout();
Pango::FontDescription font_desc("sans 12");
m_refLayout->set_font_description(font_desc);
const double width = print_context->get_width();
const double height = print_context->get_height();
m_refLayout->set_width(static_cast<int>(width * Pango::SCALE));
//Set and mark up the text to print:
Glib::ustring marked_up_form_text;
marked_up_form_text += "<b>Name</b>: " + m_Name + "\n\n";
marked_up_form_text += "<b>Comments</b>: " + m_Comments;
m_refLayout->set_markup(marked_up_form_text);
//Set the number of pages to print by determining the line numbers
//where page breaks occur:
const int line_count = m_refLayout->get_line_count();
Glib::RefPtr<Pango::LayoutLine> layout_line;
double page_height = 0;
for (int line = 0; line < line_count; ++line)
{
Pango::Rectangle ink_rect, logical_rect;
layout_line = m_refLayout->get_line(line);
layout_line->get_extents(ink_rect, logical_rect);
const double line_height = logical_rect.get_height() / 1024.0;
if (page_height + line_height > height)
{
m_PageBreaks.push_back(line);
page_height = 0;
}
page_height += line_height;
}
set_n_pages(m_PageBreaks.size() + 1);
}
void PrintFormOperation::on_draw_page(
const Glib::RefPtr<Gtk::PrintContext>& print_context, int page_nr)
{
//Decide which lines we need to print in order to print the specified page:
int start_page_line = 0;
int end_page_line = 0;
if(page_nr == 0)
{
start_page_line = 0;
}
else
{
start_page_line = m_PageBreaks[page_nr - 1];
}
if(page_nr < static_cast<int>(m_PageBreaks.size()))
{
end_page_line = m_PageBreaks[page_nr];
}
else
{
end_page_line = m_refLayout->get_line_count();
}
//Get a Cairo Context, which is used as a drawing board:
Cairo::RefPtr<Cairo::Context> cairo_ctx = print_context->get_cairo_context();
//We'll use black letters:
cairo_ctx->set_source_rgb(0, 0, 0);
//Render Pango LayoutLines over the Cairo context:
Pango::LayoutIter iter = m_refLayout->get_iter();
double start_pos = 0;
int line_index = 0;
do
{
if(line_index >= start_page_line)
{
Glib::RefPtr<Pango::LayoutLine> layout_line = iter.get_line();
Pango::Rectangle logical_rect = iter.get_line_logical_extents();
int baseline = iter.get_baseline();
if (line_index == start_page_line)
{
start_pos = logical_rect.get_y() / 1024.0;
}
cairo_ctx->move_to(logical_rect.get_x() / 1024.0,
baseline / 1024.0 - start_pos);
layout_line->show_in_cairo_context(cairo_ctx);
}
line_index++;
}
while(line_index < end_page_line && iter.next_line());
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-recent-documents">
<title>Documentos usados recientemente</title>
<para><application>gtkmm</application> proporciona una manera fácil de gestionar documentos usados recientemente. Las clases involucradas en la implementación de esta funcionalidad son <classname>RecentManager</classname>, <classname>RecentChooserDialog</classname>, <classname>RecentChooserMenu</classname>, <classname>RecentChooserWidget</classname>, <classname>RecentAction</classname>, y <classname>RecentFilter</classname>.</para>
<para>Cada elemento de la lista de archivos usados recientemente se identifica mediante su URI, y puede tener metadatos asociados. Los metadatos pueden usarse para especificar cómo se mostrará el archivo, su descripción, su tipo MIME, qué aplicación lo registró, si es privado de esta aplicación y muchas otras cosas.</para>
<sect1 id="sec-recentmanager">
<title>RecentManager</title>
<para><classname>RecentManager</classname> actúa como una base de datos de archivos usados recientemente. Use esta clase para registrar archivos nuevos, eliminarlos o buscarlos. Hay una lista de archivos usados recientemente por cada usuario.</para>
<para>Puede crear un <classname>RecentManager</classname> nuevo, pero es muy probable que prefiera usar el predeterminado. Puede obtener una referencia del <classname>RecentManager</classname> predeterminado con <methodname>get_default()</methodname>.</para>
<para><classname>RecentManager</classname> es el modelo de un patrón modelo-vista cuya vista es la clase que implementa la interfaz <classname>RecentChooser</classname>.</para>
<sect2 id="recent-files-adding">
<title>Agregar elementos a la lista de archivos recientes</title>
<para>Para añadir un archivo nuevo a la lista de documentos recientes, en el caso más simple, sólo necesita proporcionar su URI. Por ejemplo:</para>
<programlisting>Glib::RefPtr<Gtk::RecentManager> recent_manager = Gtk::RecentManager::get_default();
recent_manager->add_item(uri);</programlisting>
<para>Si quiere registrar un archivo con metadatos, puede pasar un parámetro <classname>RecentManager::Data</classname> al <methodname>add_item()</methodname>. Los metadatos que pueden establecerse en un elemento archivo particular son los siguientes:</para>
<itemizedlist id="list-file-metadata">
<listitem>
<para><varname>app_exec</varname>: la línea de comandos que se usará para lanzar este recurso. La cadena puede contener los caracteres de escape «f» y «u» que se expandirán en la ruta del archivo de recursos y el URI respectivamente</para>
</listitem>
<listitem>
<para><varname>app_name</varname>: el nombre de la aplicación que registró el recurso</para>
</listitem>
<listitem>
<para><varname>description</varname>: una descripción corta del recurso en una cadena codificada en UTF-8</para>
</listitem>
<listitem>
<para><varname>display_name</varname>: el nombre del recurso que se mostrará como una cadena codificada en UTF-8</para>
</listitem>
<listitem>
<para><varname>groups</varname>: una lista de grupos asociada con este elemento. Los grupos son esencialmente cadenas arbitrarias asociadas con un recurso en particular. Puede pensar en ellos como «categorías» (como «correo-e», «gráficos», etc), o etiquetas del recurso</para>
</listitem>
<listitem>
<para><varname>is_private</varname>: determina si el recurso debe ser visible sólo a las aplicaciones que lo han registrado o no</para>
</listitem>
<listitem>
<para><varname>mime_type</varname>: el tipo MIME del recurso</para>
</listitem>
</itemizedlist>
<para>Además de añadir elementos a la lista, puede buscarlos y modificarlos o eliminarlos.</para>
</sect2>
<sect2 id="recent-files-lookup">
<title>Buscar elementos en la lista de archivos recientes</title>
<para>Para buscar archivos usados recientemente, <classname>RecentManager</classname> proporciona varias funciones. Para buscar un elemento específico por su URI, puede usar la función <methodname>lookup_item()</methodname>, que devolverá una clase <classname>RecentInfo</classname>. Si el URI especificado no existe en la lista de archivos recientes, <methodname>lookup_item()</methodname> arroja una excepción <classname>RecentManagerError</classname>. Por ejemplo:</para>
<programlisting>Glib::RefPtr<Gtk::RecentInfo> info;
try
{
info = recent_manager->lookup_item(uri);
}
catch(const Gtk::RecentManagerError& ex)
{
std::cerr << "RecentManagerError: " << ex.what() << std::endl;
}
if (info)
{
// item was found
}</programlisting>
<para>Un objeto <classname>RecentInfo</classname> es esencialmente un objeto que contiene todos los metadatos de un solo archivo utilizado recientemente. Puede utilizar este objeto para buscar cualquiera de las propiedades enumeradas <link linkend="list-file-metadata">anteriormente</link>.</para>
<para>Si no quiere buscar un URI específico, sino obtener una lista de todos los elementos usados recientemente, <classname>RecentManager</classname> proporciona la función <methodname>get_items()</methodname>. El valor que devuelve esta función es un <classname>std::vector</classname> de todos los archivos usados recientemente. El siguiente código demuestra cómo puede obtener una lista de todos los archivos usados recientemente:</para>
<programlisting>std::vector< Glib::RefPtr<Gtk::RecentInfo> > info_list = recent_manager->get_items();</programlisting>
<para>La edad máxima de los elementos de la lista de archivos usados recientemente puede establecerse con <methodname>Gtk::Settings::property_gtk_recent_files_max_age()</methodname>. El valor predeterminado es 30 días.</para>
</sect2>
<sect2 id="recent-files-modifying">
<title>Modificar la lista de archivos recientes</title>
<para>Podría existir alguna ocasión en la que necesite modificar la lista de archivos usados recientemente. Por ejemplo, si un archivo se borra o renombra, necesitará actualizar la localización del archivo en la lista de archivos recientes para que no apunte a un lugar incorrecto. Puede actualizar la localización de un elemento usando <methodname>move_item()</methodname>.</para>
<para>Además de cambiar el URI de un archivo, también puede eliminar archivos de la lista uno a uno o todos juntos. Realice lo primero con <methodname>remove_item()</methodname>, y lo último con <methodname>purge_items()</methodname>.</para>
<note>
<para>Las funciones <methodname>move_item()</methodname>, <methodname>remove_item()</methodname> y <methodname>purge_items()</methodname> no tienen efecto en los archivos en sí a los que se refieren los URI, sólo modifican la lista de archivos recientes.</para>
</note>
</sect2>
</sect1>
<sect1 id="sec-recentchooser">
<title>RecentChooser</title>
<para><classname>RecentChooser</classname> es una interfaz que pueden implementar los widgets que muestran la lista de archivos usados recientemente. <application>gtkmm</application> proporciona cuatro implementaciones incorporadas para elegir archivos recientes: <classname>RecentChooserWidget</classname>, <classname>RecentChooserDialog</classname>, <classname>RecentChooserMenu</classname>, y <classname>RecentAction</classname>.</para>
<para><classname>RecentChooserWidget</classname> es un widget simple para mostrar una lista de archivos usados recientemente. <classname>RecentChooserWidget</classname> es el bloque de construcción básico de <classname>RecentChooserDialog</classname>, pero puede empotrarlo en su interfaz de usuario si quiere.</para>
<para><classname>RecentChooserMenu</classname> y <classname>RecentAction</classname> le permiten listar archivos usados recientemente en un menú.</para>
<sect2 id="recentchooserdialog-example">
<title>Ejemplo de RecentChooserDialog</title>
<para>Se muestra a continuación un ejemplo simple de cómo usar las clases <classname>RecentChooserDialog</classname> y <classname>RecentAction</classname> en un programa. Este programa simple tiene una barra de menú con un elemento de menú <guimenuitem>Recent Files Dialog</guimenuitem>. Cuando seleccione este elemento, aparecerá un diálogo mostrando la lista de archivos recientemente usados.</para>
<note>
<para>Si esta es la primera vez que usa un programa que utiliza el sistema de archivos recientes, el diálogo podría estar vacío. De lo contrario, debería mostrar la lista de documentos recientemente usados registrados por otras aplicaciones.</para>
</note>
<para>Después de haber seleccionado el elemento del menú <guimenuitem>Recent Files Dialog</guimenuitem>, debería ver algo similar a la siguiente ventana.</para>
<screenshot>
<graphic format="PNG" fileref="figures/recentchooserdialog.png"/>
</screenshot>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/recent_files?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_menu_file_recent_files_item();
void on_menu_file_recent_files_dialog();
void on_menu_file_quit();
void on_menu_file_new();
//Child widgets:
Gtk::Box m_Box;
Glib::RefPtr<Gtk::Builder> m_refBuilder;
Glib::RefPtr<Gio::SimpleActionGroup> m_refActionGroup;
Glib::RefPtr<Gtk::RecentManager> m_refRecentManager;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_Box(Gtk::ORIENTATION_VERTICAL),
m_refRecentManager(Gtk::RecentManager::get_default())
{
set_title("recent files example");
set_default_size(200, 200);
//We can put a MenuBar at the top of the box and other stuff below it.
add(m_Box);
//Create actions for menus and toolbars:
m_refActionGroup = Gio::SimpleActionGroup::create();
//File menu:
m_refActionGroup->add_action("new",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_new));
//A menu item to open the recent-files dialog:
m_refActionGroup->add_action("recent-files-dialog",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_recent_files_dialog) );
m_refActionGroup->add_action("quit",
sigc::mem_fun(*this, &ExampleWindow::on_menu_file_quit) );
insert_action_group("example", m_refActionGroup);
m_refBuilder = Gtk::Builder::create();
//TODO: add_accel_group(m_refBuilder->get_accel_group());
//Layout the actions in a menubar and toolbar:
const char* ui_info =
"<interface>"
" <menu id='menubar'>"
" <submenu>"
" <attribute name='label' translatable='yes'>_File</attribute>"
" <item>"
" <attribute name='label' translatable='yes'>_New</attribute>"
" <attribute name='action'>example.new</attribute>"
" <attribute name='accel'>&lt;Primary&gt;n</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>Recent Files _Dialog</attribute>"
" <attribute name='action'>example.recent-files-dialog</attribute>"
" <attribute name='accel'>&lt;Primary&gt;o</attribute>"
" </item>"
" <item>"
" <attribute name='label' translatable='yes'>_Quit</attribute>"
" <attribute name='action'>example.quit</attribute>"
" <attribute name='accel'>&lt;Primary&gt;q</attribute>"
" </item>"
" </submenu>"
" </menu>";
/* TODO:
" <toolbar name='ToolBar'>"
" <toolitem action='FileNew'/>"
" <toolitem action='FileQuit'/>"
" </toolbar>"
"</ui>";
*/
try
{
m_refBuilder->add_from_string(ui_info);
}
catch(const Glib::Error& ex)
{
std::cerr << "building menus failed: " << ex.what();
}
//Get the menubar and toolbar widgets, and add them to a container widget:
Glib::RefPtr<Glib::Object> object =
m_refBuilder->get_object("menubar");
Glib::RefPtr<Gio::Menu> gmenu =
Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
if(!gmenu)
g_warning("GMenu not found");
//Menubar:
Gtk::MenuBar* pMenubar = new Gtk::MenuBar(gmenu);
m_Box.pack_start(*pMenubar, Gtk::PACK_SHRINK);
/* TODO:
Gtk::Widget* pToolbar = m_refBuilder->get_widget("/ToolBar");
if(pToolbar)
m_Box.pack_start(*pToolbar, Gtk::PACK_SHRINK);
*/
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_menu_file_new()
{
std::cout << " New File" << std::endl;
}
void ExampleWindow::on_menu_file_quit()
{
hide(); //Closes the main window to stop the app->run().
}
void ExampleWindow::on_menu_file_recent_files_dialog()
{
Gtk::RecentChooserDialog dialog(*this, "Recent Files", m_refRecentManager);
dialog.add_button("Select File", Gtk::RESPONSE_OK);
dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
const int response = dialog.run();
dialog.hide();
if(response == Gtk::RESPONSE_OK)
{
std::cout << "URI selected = " << dialog.get_current_uri() << std::endl;
}
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
<para>El constructor de <classname>ExampleWindow</classname> crea el menú usando <classname>UIManager</classname> (consulte la <xref linkend="chapter-menus-and-toolbars"/> para obtener más información). Luego, añade el menú y la barra de herramientas a la ventana.</para>
</sect2>
<sect2 id="recent-files-filtering">
<title>Filtrar los archivos recientes</title>
<para>Para cualquiera de las clases <classname>RecentChooser</classname>, si no quiere mostrar todos los elementos en la lista de archivos recientes, puede filtrarlos para mostrar sólo aquellos que quiere. Puede realizar esto con ayuda de la clase <classname>RecentFilter</classname>. Esta clase le permite filtrar los archivos recientes por su nombre (<methodname>add_pattern()</methodname>), su tipo MIME (<methodname>add_mime_type()</methodname>), la aplicación que los registró (<methodname>add_application()</methodname>), o una función de filtrado personalizada (<methodname>add_custom()</methodname>). También proporciona la posibilidad de filtrar de acuerdo a cuánto tiempo pasó desde que el archivo se modificó y a qué grupo pertenece.</para>
<para>Después de que haya creado y configurado el filtro para seleccionar sólo los elementos que quiera, podrá aplicárselo a un widget selector con la función <methodname>RecentChooser::add_filter()</methodname>.</para>
</sect2>
</sect1>
</chapter>
<chapter id="chapter-plugs-sockets">
<title>«Plugs» y «Sockets»</title>
<sect1 id="sec-plugs-sockets-overview">
<title>Vista general</title>
<para>De vez en cuando, puede ser útil incrustar un widget de otra aplicación dentro de la suya. <application>gtkmm</application> le permite hacer esto con las clases <classname>Gtk::Socket</classname> y <classname>Gtk::Plug</classname>. Se anticipa que no muchas aplicaciones necesitan esta funcionalidad, pero en los raros casos en los que necesite mostrar un widget que esté ejecutándose en un proceso completamente diferente, estas clases pueden resultar muy útiles.</para>
<para>La comunicación entre un <classname>Socket</classname> y un <classname>Plug</classname> sigue el protocolo «XEmbed». Este protocolo, que también se ha implementado en otros kits de herramientas (por ejemplo, «Qt»), permite el mismo nivel de integración cuando se incrusta un widget Qt en uno GTK+ o viceversa.</para>
<para>La manera en la que los <classname>Sockets</classname> y los <classname>Plugs</classname> trabajan juntos es a través de sus ID de ventana. Tanto un <classname>Socket</classname> como un <classname>Plug</classname> tienen ID que pueden obtenerse con sus funciones miembro <methodname>get_id()</methodname>. El uso de estos ID se explicará a continuación en la <xref linkend="sec-connecting-plugs-sockets"/>.</para>
<sect2 id="sec-sockets">
<title>«Sockets»</title>
<para>Un <classname>Socket</classname> es un tipo especial de widget contenedor que ofrece la posibilidad de incorporar widgets de un proceso en otro proceso de manera que sea transparente para el usuario.</para>
</sect2>
<sect2 id="sec-plugs">
<title>«Plugs»</title>
<para>Un <classname>Plug</classname> es un tipo especial de ventana que se puede conectar a un <classname>Socket</classname>. Además de las propiedades y los métodos normales de <classname>Gtk::Window</classname>, un <classname>Plug</classname> proporciona un constructor que toma el ID de un <classname>Socket</classname>, lo que automáticamente incrusta el <classname>Plug</classname> en el <classname>Socket</classname> que coincide con el ID.</para>
<para>Dado que un <classname>Plug</classname> es sólo un tipo especial de la clase <classname>Gtk::Window</classname>, puede añadirle contenedores o widgets como si fuera cualquier otra ventana.</para>
</sect2>
<sect2 id="sec-connecting-plugs-sockets">
<title>Conectar «plugs» y «sockets»</title>
<para>Luego de que se crea un objeto <classname>Socket</classname> o <classname>Plug</classname>, puede obtener su ID con su función <methodname>get_id()</methodname>. Este ID puede entonces compartirse con otros procesos para que estos sepan cómo conectarse entre sí.</para>
<para lang="en">
There are two basic strategies that can be used:
<itemizedlist>
<listitem>
<para lang="en">
Create a <classname>Socket</classname> object in one process and
pass the ID of that <classname>Socket</classname> to another
process so that it can create a <classname>Plug</classname> object
by specifying the given <classname>Socket</classname> ID in its
constructor. There is no way to assign a
<classname>Plug</classname> to a particular
<classname>Socket</classname> after creation, so you must pass the
<classname>Socket</classname> ID to the
<classname>Plug</classname>'s constructor.
</para>
</listitem>
<listitem>
<para lang="en">
Create a <classname>Plug</classname> independantly from any
particular <classname>Socket</classname> and pass the ID of the
<classname>Plug</classname> to other processes that need to use
it. The ID of the <classname>Plug</classname> can be associated
with a particular <classname>Socket</classname> object using the
<methodname>Socket::add_id()</methodname> function. This is the
approach used in the example below.
</para>
</listitem>
</itemizedlist>
</para>
</sect2>
</sect1>
<sect1 id="sec-plugs-sockets-example">
<title>Ejemplo de «Plugs» y «Sockets».</title>
<para>El siguiente es un ejemplo simple del uso de «sockets» y «plugs». El método de comunicación entre los procesos se mantiene simple deliberadamente: el <classname>Plug</classname> escribe su ID en un archivo de texto llamado <filename>plug.id</filename> y el proceso con el «socket» lee el ID de este archivo. En un programa real, probablemente quiera usar un método más sofisticado de comunicación entre procesos.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/socket/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>plug.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include <fstream>
#include <gtkmm.h>
#include <gtkmm/plug.h>
#include <glib/gstdio.h>
using namespace std;
const char* id_filename = "plug.id";
void on_embed()
{
cout << "I've been embedded." << endl;
}
class MyPlug : public Gtk::Plug
{
public:
MyPlug() :
m_label("I am the plug")
{
set_size_request(150, 100);
add(m_label);
signal_embedded().connect(sigc::ptr_fun(on_embed));
show_all_children();
}
private:
Gtk::Label m_label;
};
int main(int argc, char** argv)
{
// The plug and the socket have different application ids, so they can run
// simultaneously.
Glib::RefPtr<Gtk::Application> app =
Gtk::Application::create(argc, argv, "org.gtkmm.example.plug");
MyPlug plug;
plug.show();
ofstream out(id_filename);
out << plug.get_id();
out.close();
cout << "The window ID is: " << plug.get_id() << endl;
app->run(plug);
// remove the ID file when the program exits
g_remove(id_filename);
return 0;
}
</programlisting>
<para lang="en">File: <filename>socket.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include <fstream>
#include <gtkmm.h>
#include <gtkmm/socket.h>
using namespace std;
const char* id_filename = "plug.id";
void plug_added()
{
cout << "A plug was added" << endl;
}
bool plug_removed()
{
cout << "A Plug was removed" << endl;
return true;
}
class MySocketWindow : public Gtk::Window
{
public:
MySocketWindow()
{
ifstream infile(id_filename);
if (infile)
{
Gtk::Socket* socket = Gtk::manage(new Gtk::Socket());
add(*socket);
socket->signal_plug_added().connect(sigc::ptr_fun(plug_added));
socket->signal_plug_removed().connect(sigc::ptr_fun(plug_removed));
::Window plug_id = 0;
infile >> plug_id;
infile.close();
socket->add_id(plug_id);
}
else
{
Gtk::Label* label = Gtk::manage(
new Gtk::Label(
"Plug id file not found.\n Make sure plug is running."));
add(*label);
set_size_request(150, 50);
}
show_all();
}
};
int main(int argc, char** argv)
{
// The plug and the socket have different application ids, so they can run
// simultaneously.
Glib::RefPtr<Gtk::Application> app =
Gtk::Application::create(argc, argv, "org.gtkmm.example.socket");
MySocketWindow win;
app->run(win);
return 0;
}
</programlisting>
<!-- end inserted example code -->
<para>Este ejemplo crea dos programas ejecutables: <filename>socket</filename> y <filename>plug</filename>. La idea es que <filename>socket</filename> tenga una ventana de aplicación en la que se empotre un widget del programa <filename>plug</filename>. Dada la manera en la que este ejemplo está diseñado, <filename>plug</filename> debe estar en ejecución antes de iniciar <filename>socket</filename>. Para ver el ejemplo en acción, ejecute los siguientes comandos en orden desde la carpeta de ejemplos:</para>
<para>Ejecute el programa <filename>plug</filename> y envíelo a segundo plano (o simplemente use otra terminal).</para>
<screen>$ ./plug &</screen>
<para>Después de esto debería ver algo así:</para>
<screen>The window ID is: 69206019</screen>
<para>Entonces, ejecute el programa <filename>socket</filename>:</para>
<screen>$ ./socket</screen>
<para>Después de haber ejecutado <filename>socket</filename>, debería ver la siguiente salida en la terminal:</para>
<screen>I've been embedded.
A plug was added</screen>
<para>La primera línea de la salida es de <filename>plug</filename>, después de que se le ha notificado que se empotró en un <classname>Socket</classname>. La segunda línea la emite <filename>socket</filename> en respuesta a su señal <methodname>plug_added</methodname>. Si todo se realizó como se describió anteriormente, la ventana <filename>socket</filename> debería verse más o menos así:</para>
<screenshot>
<graphic format="PNG" fileref="figures/socket.png"/>
</screenshot>
<para>Si, por alguna razón, el <classname>Socket</classname> no pudiera adjuntar el <classname>Plug</classname>, la ventana se vería más o menos así:</para>
<screenshot>
<graphic format="PNG" fileref="figures/socket-fail.png"/>
</screenshot>
</sect1>
</chapter>
<chapter id="chapter-keyboardevents">
<title>Eventos de teclado</title>
<para>Los eventos de X difieren un poco de otras señales. Estas diferencias se describen en la sección <link linkend="sec-xeventsignals">Señales de eventos de X</link> en el apéndice. Aquí se usarán los eventos del teclado para mostrar cómo pueden usarse en un programa los eventos de X.</para>
<sect1 id="sec-keyboardevents-overview">
<title>Vista general</title>
<para>Siempre que presiona o suelta una tecla, se emite un evento. Puede conectar un manejador de señales para manejar tales eventos.</para>
<para>Para recibir los eventos del teclado, primero debe llamar a la función <methodname>Gtk::Widget::add_events()</methodname> con una máscara de bits de los eventos en los que esté interesado. El manejador de señales de eventos recibirá un argumento que dependerá del tipo de evento. Para eventos del teclado, es un <type>GdkEventKey*</type>. Como de describe en el <link linkend="sec-xeventsignals">apéndice</link>, el manejador de señales de eventos devuelve un valor <type>bool</type> para indicar que se maneja completamente la señal (<literal>true</literal>) o permitir la propagación del evento (<literal>false</literal>).</para>
<para>Para determinar qué tecla se presionó o soltó, lea el valor de <varname>GdkEventKey::keyval</varname> y compárelo con una constante en el archivo de cabecera <filename><gdk/gdkkeysyms.h></filename>. Los estados de las teclas modificadoras (mayús, control, etc.) están disponibles como banderas de bits en <varname>GdkEventKey::state</varname>.</para>
<para lang="en">
Here's a simple example:
<programlisting lang="en">
bool on_key_press_or_release_event(GdkEventKey* event)
{
if (event->type == GDK_KEY_PRESS &&
event->keyval == GDK_KEY_1 &&
(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
{
handle_alt_1_press(); // GDK_MOD1_MASK is normally the Alt key
return true;
}
return false;
}
Gtk::Entry m_entry; // in a class definition
// in the class constructor
m_entry.signal_key_press_event().connect( sigc::ptr_fun(&on_key_press_or_release_event) );
m_entry.signal_key_release_event().connect( sigc::ptr_fun(&on_key_press_or_release_event) );
m_entry.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
</programlisting>
</para>
<sect2 id="keyboardevents-simple-example">
<title>Ejemplo</title>
<para>En este ejemplo hay tres combinaciones de teclas: <keycap>Alt</keycap>+<keycap>1</keycap> selecciona el primer botón de radio, <keycap>Alt</keycap>+<keycap>2</keycap> selecciona el segundo, y la tecla <keycap>Escape</keycap> oculta (cierra) la ventana. El manejador de eventos predeterminado se sobrecarga, como se describe en la sección <link linkend="sec-overriding-default-signal-handlers">Sobrecargar los manejadores de señales predeterminados</link> en el apéndice.</para>
<figure id="figure-keyboardevents-simple">
<title>Eventos del teclado: simple</title>
<screenshot>
<graphic format="PNG" fileref="figures/keyboardevents_simple.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/keyboard_events/simple/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
private:
//Override default signal handler:
virtual bool on_key_press_event(GdkEventKey* event);
Gtk::Grid m_container;
Gtk::RadioButton m_first;
Gtk::RadioButton m_second;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
{
set_title("Keyboard Events");
set_border_width(10);
add(m_container);
// Radio buttons:
m_first.set_label("First");
m_second.set_label("Second");
Gtk::RadioButton::Group group = m_first.get_group();
m_second.set_group(group);
m_first.set_active();
// Main Container:
m_container.add(m_first);
m_container.add(m_second);
// Events.
// We override the default event signal handler.
add_events(Gdk::KEY_PRESS_MASK);
show_all_children();
}
bool ExampleWindow::on_key_press_event(GdkEventKey* event)
{
//GDK_MOD1_MASK -> the 'alt' key(mask)
//GDK_KEY_1 -> the '1' key
//GDK_KEY_2 -> the '2' key
//select the first radio button, when we press alt + 1
if((event->keyval == GDK_KEY_1) &&
(event->state &(GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
{
m_first.set_active();
//returning true, cancels the propagation of the event
return true;
}
else if((event->keyval == GDK_KEY_2) &&
(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
{
//and the second radio button, when we press alt + 2
m_second.set_active();
return true;
}
else if(event->keyval == GDK_KEY_Escape)
{
//close the window, when the 'esc' key is pressed
hide();
return true;
}
//if the event has not been handled, call the base class
return Gtk::Window::on_key_press_event(event);
}
ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-keyboardevents-propagation">
<title>Propagación de eventos</title>
<para>Propagación de eventos significa que, cuando se emite un evento en un widget particular, puede pasarse a su widget padre (y ese widget puede pasárselo a su padre, y así sucesivamente) y, si el padre tiene un manejador de eventos, se llamará.</para>
<para>Al contrario que otros eventos, los eventos del teclado primero se envían a la ventana de nivel superior (<classname>Gtk::Window</classname>), donde se verifican los atajos del teclado establecidos (teclas aceleradoras y combinaciones, utilizadas para seleccionar elementos del menú desde el teclado). Después de esto (y asumuiendo que no se manejó el evento), se envía al widget que tiene el foco, y la propagación comienza desde allí.</para>
<para>El evento se propagará hasta que alcance el widget de mayor nivel, o hasta que detenga la propagación devolviendo <literal>true</literal> desde un manejador de eventos.</para>
<para>Tenga en cuenta que, después de haber cancelado un evento, no se llamará a ninguna otra función (incluso si es del mismo widget).</para>
<sect2 id="keyboardevents-propagation-example">
<title>Ejemplo</title>
<para>En este ejemplo hay tres manejadores de eventos que se llaman después del manejador de eventos predeterminado de <classname>Gtk::Window</classname>, uno en la <classname>Gtk::Entry</classname>, uno en el <classname>Gtk::Grid</classname> y uno en la <classname>Gtk::Window</classname>.</para>
<para>En la <classname>Gtk::Window</classname>, también está la sobrecarga del manejador predeterminado (<methodname>on_key_release_event()</methodname>), y otro manejador que se llama antes del predeterminado (<methodname>windowKeyReleaseBefore()</methodname>).</para>
<para>El propósito de este ejemplo es mostrar los pasos que el evento sigue cuando se emite.</para>
<para>Cuando escriba en el «entry», se emitirá un evento de liberación de tecla, que primero irá a la ventana superior (<classname>Gtk::Window</classname>), dado que hay un manejador de eventos establecido para que se llame antes, y ese es el que se llama primero (<methodname>windowKeyReleaseBefore()</methodname>). Después se llama al manejador de eventos predeterminado (al que se ha sobrecargado), y luego se envía el evento al widget que tiene el foco, el <classname>Entry</classname> en el ejemplo y, dependiendo de si lo dejamos propagar o no, puede alcanzar los manejadores de eventos del <classname>Grid</classname> y la <classname>Window</classname>. Si se propaga, el texto que esté escribiendo aparecerá en el <classname>Label</classname> arriba del <classname>Entry</classname>.</para>
<figure id="figure-keyboardevents-propagation">
<title>Eventos de teclado: propagación de eventos</title>
<screenshot>
<graphic format="PNG" fileref="figures/keyboardevents_propagation.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/keyboard_events/propagation/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EVENT_PROPAGATION_H
#define GTKMM_EVENT_PROPAGATION_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
private:
//Override default signal handler:
virtual bool on_key_release_event(GdkEventKey* event);
bool entryKeyRelease(GdkEventKey* event);
bool gridKeyRelease(GdkEventKey* event);
bool windowKeyReleaseBefore(GdkEventKey* event);
bool windowKeyRelease(GdkEventKey* event);
Gtk::Grid m_container;
Gtk::Label m_label;
Gtk::Entry m_entry;
Gtk::CheckButton m_checkbutton_can_propagate;
};
#endif //GTKMM_EVENT_PROPAGATION_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
{
add(m_container);
set_title("Event Propagation");
set_border_width(10);
m_label.set_label("A label");
m_checkbutton_can_propagate.set_label("Can Propagate");
m_checkbutton_can_propagate.set_active();
// Main Container
m_container.set_orientation(Gtk::ORIENTATION_VERTICAL);
m_container.add(m_label);
m_container.add(m_entry);
m_container.add(m_checkbutton_can_propagate);
// Events
add_events(Gdk::KEY_RELEASE_MASK);
m_entry.signal_key_release_event().connect(
sigc::mem_fun(*this, &ExampleWindow::entryKeyRelease));
m_container.signal_key_release_event().connect(
sigc::mem_fun(*this, &ExampleWindow::gridKeyRelease));
// Called before the default event signal handler.
signal_key_release_event().connect(
sigc::mem_fun(*this, &ExampleWindow::windowKeyReleaseBefore), false);
// Called after the default event signal handler.
signal_key_release_event().connect(
sigc::mem_fun(*this, &ExampleWindow::windowKeyRelease));
show_all_children();
}
//By changing the return value we allow, or don't allow, the event to propagate to other elements.
bool ExampleWindow::entryKeyRelease(GdkEventKey* /* event */ )
{
std::cout << "Entry" << std::endl;
if(m_checkbutton_can_propagate.get_active())
{
return false;
}
return true;
}
bool ExampleWindow::gridKeyRelease(GdkEventKey* /* event */ )
{
std::cout << "Grid" << std::endl;
//Let it propagate:
return false;
}
bool ExampleWindow::windowKeyReleaseBefore(GdkEventKey* /* event */ )
{
std::cout << "Window before" << std::endl;
return false;
}
bool ExampleWindow::on_key_release_event(GdkEventKey* event)
{
std::cout << "Window overridden" << std::endl;
// call base class function (to get the normal behaviour)
return Gtk::Window::on_key_release_event(event);
}
// This will set the entry's text in the label, every time a key is pressed.
bool ExampleWindow::windowKeyRelease(GdkEventKey* /* event */ )
{
std::cout << "Window after";
//checking if the entry is on focus, otherwise the label would get changed by pressing keys
//on the window (when the entry is not on focus), even if m_checkbutton_can_propagate wasn't active
if(m_entry.has_focus())
{
m_label.set_text(m_entry.get_text());
std::cout << ", " << m_entry.get_text();
}
std::cout << std::endl;
return true;
}
ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-chapter-timeouts">
<title>Tiempos de espera, E/S y funciones en espera</title>
<sect1 id="sec-timeouts">
<title>Tiempos de espera</title>
<para>Puede preguntarse cómo hacer que <application>gtkmm</application> haga trabajo útil mientras está en espera. Afortunadamente, cuenta con varias opciones. Usando los siguientes métodos puede crear un método de tiempo de espera que se llamará cada una cierta cantidad de milisegundos.</para>
<para>
<programlisting>
sigc::connection Glib::SignalTimeout::connect(const sigc::slot<bool>& slot,
unsigned int interval, int priority = Glib::PRIORITY_DEFAULT);
</programlisting>
</para>
<para>El primer argumento es un <classname>slot</classname> al que quiere que se llame cuando pase el período de espera. El segundo argumento es el número de milisegundos entre llamadas a ese método. Recibirá un objeto <classname>sigc::connection</classname> que podrá usar para desactivar la conexión utilizando su método <methodname>disconnect()</methodname>:</para>
<para>
<programlisting>
my_connection.disconnect();
</programlisting>
</para>
<para lang="en">
Another way of destroying the connection is your signal handler.
It has to be of the type <classname>sigc::slot<bool></classname>.
As you see from the definition your signal handler has to return a value of
the type <literal>bool</literal>. A definition of a sample method might
look like this:
<programlisting lang="en">
bool MyCallback() { std::cout << "Hello World!\n" << std::endl; return true; }
</programlisting>
</para>
<para>Puede detener el método del período de espera mediante la devolución de <literal>false</literal> desde su manejador de señales. Por lo tanto, si quiere que su método se llame repetidamente, debe devolver <literal>true</literal>.</para>
<para>Un ejemplo de esta técnica:</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/timeout/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>timerexample.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_TIMEREXAMPLE_H
#define GTKMM_EXAMPLE_TIMEREXAMPLE_H
#include <gtkmm.h>
#include <iostream>
#include <map>
class TimerExample : public Gtk::Window
{
public:
TimerExample();
protected:
// signal handlers
void on_button_add_timer();
void on_button_delete_timer();
void on_button_quit();
// This is the callback function the timeout will call
bool on_timeout(int timer_number);
// Member data:
Gtk::Box m_Box;
Gtk::Button m_ButtonAddTimer, m_ButtonDeleteTimer, m_ButtonQuit;
// Keep track of the timers being added:
int m_timer_number;
// These two constants are initialized in the constructor's member initializer:
const int count_value;
const int timeout_value;
// STL map for storing our connections
std::map<int, sigc::connection> m_timers;
// STL map for storing our timer values.
// Each timer counts back from COUNT_VALUE to 0 and is removed when it reaches 0
std::map<int, int> m_counters;
};
#endif // GTKMM_EXAMPLE_TIMEREXAMPLE_H
</programlisting>
<para lang="en">File: <filename>timerexample.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "timerexample.h"
TimerExample::TimerExample() :
m_Box(Gtk::ORIENTATION_HORIZONTAL, 10),
m_ButtonAddTimer("_Add", true),
m_ButtonDeleteTimer("_Remove", true),
m_ButtonQuit("_Quit", true),
m_timer_number(0), // start numbering the timers at 0
count_value(5), // each timer will count down 5 times before disconnecting
timeout_value(1500) // 1500 ms = 1.5 seconds
{
set_border_width(10);
add(m_Box);
m_Box.pack_start(m_ButtonAddTimer);
m_Box.pack_start(m_ButtonDeleteTimer);
m_Box.pack_start(m_ButtonQuit);
// Connect the three buttons:
m_ButtonQuit.signal_clicked().connect(sigc::mem_fun(*this,
&TimerExample::on_button_quit));
m_ButtonAddTimer.signal_clicked().connect(sigc::mem_fun(*this,
&TimerExample::on_button_add_timer));
m_ButtonDeleteTimer.signal_clicked().connect(sigc::mem_fun(*this,
&TimerExample::on_button_delete_timer));
show_all_children();
}
void TimerExample::on_button_quit()
{
hide();
}
void TimerExample::on_button_add_timer()
{
// Creation of a new object prevents long lines and shows us a little
// how slots work. We have 0 parameters and bool as a return value
// after calling sigc::bind.
sigc::slot<bool> my_slot = sigc::bind(sigc::mem_fun(*this,
&TimerExample::on_timeout), m_timer_number);
// This is where we connect the slot to the Glib::signal_timeout()
sigc::connection conn = Glib::signal_timeout().connect(my_slot,
timeout_value);
// Remember the connection:
m_timers[m_timer_number] = conn;
// Initialize timer count:
m_counters[m_timer_number] = count_value + 1;
// Print some info to the console for the user:
std::cout << "added timeout " << m_timer_number++ << std::endl;
}
void TimerExample::on_button_delete_timer()
{
// any timers?
if(m_timers.empty())
{
// no timers left
std::cout << "Sorry, there are no timers left." << std::endl;
}
else
{
// get the number of the first timer
int timer_number = m_timers.begin()->first;
// Give some info to the user:
std::cout << "manually disconnecting timer " << timer_number
<< std::endl;
// Remove the entry in the counter values
m_counters.erase(timer_number);
// Diconnect the signal handler:
m_timers[timer_number].disconnect();
// Forget the connection:
m_timers.erase(timer_number);
}
}
bool TimerExample::on_timeout(int timer_number)
{
// Print the timer:
std::cout << "This is timer " << timer_number;
// decrement and check counter value
if (--m_counters[timer_number] == 0)
{
std::cout << " being disconnected" << std::endl;
// delete the counter entry in the STL MAP
m_counters.erase(timer_number);
// delete the connection entry in the STL MAP
m_timers.erase(timer_number);
// Note that we do not have to explicitly call disconnect() on the
// connection since Gtk::Main does this for us when we return false.
return false;
}
// Print the timer value
std::cout << " - " << m_counters[timer_number] << "/"
<< count_value << std::endl;
// Keep going (do not disconnect yet):
return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "timerexample.h"
#include <gtkmm/application.h>
int main (int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
TimerExample example;
return app->run(example);
}
</programlisting>
<!-- end inserted example code -->
</sect1>
<sect1 id="sec-monitoring-io">
<title>Monitorizar E/S</title>
<para>Una característica elegante de Glib (una de las bibliotecas subyacentes de <application>gtkmm</application>) es la capacidad de verificar los datos en un descriptor de archivos. Esto es especialmente útil para aplicaciones de red. Se usa el siguiente método para lograrlo:</para>
<para>
<programlisting>
sigc::connection Glib::SignalIO::connect(const sigc::slot<bool,Glib::IOCondition>& slot,
int fd, Glib::IOCondition condition,
int priority = Glib::PRIORITY_DEFAULT);
</programlisting>
</para>
<para lang="en">
The first argument is a slot you wish to have called when
the specified event (see argument 3) occurs on the file descriptor you specify
using argument two. Argument three may be one or more (using
<literal>|</literal>) of:
</para>
<itemizedlist>
<listitem>
<para>Glib::IO_IN: llame a su método cuando haya datos listos para leerse en su descriptor de archivos.</para>
</listitem>
<listitem>
<para>Glib::IO_OUT: llame a su método cuando el descriptor de archivos esté listo para la escritura.</para>
</listitem>
<listitem>
<para>Glib::IO_PRI: llame a su método cuando el descriptor de archivos tenga datos urgentes para leer.</para>
</listitem>
<listitem>
<para>Glib::IO_ERR: llame a su método cuando haya ocurrido un error en el descriptor de archivos.</para>
</listitem>
<listitem>
<para>Glib::IO_HUP: llame a su método cuando se cuelgue (la conexión se ha roto, normalmente por tuberías y «sockets»).</para>
</listitem>
</itemizedlist>
<para>El valor de retorno es una <classname>sigc::connection</classname> que puede usarse para detener la monitorización del descriptor de archivos usando su método <methodname>disconnect()</methodname>. El manejador de señales <parameter>slot</parameter> debe declararse de la siguiente manera:</para>
<para>
<programlisting>
bool input_callback(Glib::IOCondition condition);
</programlisting>
</para>
<para>donde <parameter>condition</parameter> se especifica como se mencionó previamente. Como de costumbre, el «slot» se crea con <function>sigc::mem_fun()</function> (para un método miembro de un objeto), o <function>sigc::ptr_fun()</function> (para una función).</para>
<para>A continuación se muestra un pequeño ejemplo. Para usar el ejemplo, sólo ejecútelo desde un terminal; no crea una ventana. Creará una tubería llamada <literal>testfifo</literal> en la carpeta actual. Después inicie otro intérprete de comandos y ejecute <literal>echo "Hello" > testfifo</literal>. El ejemplo imprimirá cada línea que introduzca hasta que ejecute <literal>echo "Q" > testfifo</literal>.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/input/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <build/config.h>
#include <gtkmm/application.h>
#include <glibmm/main.h>
#include <glibmm/iochannel.h>
#include <fcntl.h>
#include <iostream>
#include <unistd.h> //The SUN Forte compiler puts F_OK here.
//The SUN Forte compiler needs these for mkfifo:
#include <sys/types.h>
#include <sys/stat.h>
Glib::RefPtr<Gtk::Application> app;
int read_fd;
Glib::RefPtr<Glib::IOChannel> iochannel;
/*
send to the fifo with:
echo "Hello" > testfifo
quit the program with:
echo "Q" > testfifo
*/
// this will be our signal handler for read operations
// it will print out the message sent to the fifo
// and quit the program if the message was 'Q'.
bool MyCallback(Glib::IOCondition io_condition)
{
if ((io_condition & Glib::IO_IN) == 0) {
std::cerr << "Invalid fifo response" << std::endl;
}
else {
Glib::ustring buf;
iochannel->read_line(buf);
std::cout << buf;
if (buf == "Q\n")
app->quit();
}
return true;
}
int main(int argc, char *argv[])
{
app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
if (access("testfifo", F_OK) == -1) {
// fifo doesn't exist - create it
#ifdef HAVE_MKFIFO
if (mkfifo("testfifo", 0666) != 0) {
std::cerr << "error creating fifo" << std::endl;
return -1;
}
#else
std::cerr << "error creating fifo: This platform does not have mkfifo()"
<< std::endl;
#endif //HAVE_MKFIFO
}
read_fd = open("testfifo", O_RDONLY);
if (read_fd == -1)
{
std::cerr << "error opening fifo" << std::endl;
return -1;
}
// connect the signal handler
Glib::signal_io().connect(sigc::ptr_fun(MyCallback), read_fd, Glib::IO_IN);
// Creates a iochannel from the file descriptor
iochannel = Glib::IOChannel::create_from_fd(read_fd);
// and last but not least - run the application main loop
app->hold(); // keep the application running without a window
app->run();
// now remove the temporary fifo
if(unlink("testfifo"))
std::cerr << "error removing fifo" << std::endl;
return 0;
}
</programlisting>
<!-- end inserted example code -->
</sect1>
<sect1 id="sec-idle-functions">
<title>Funciones en espera</title>
<para>Si quiere especificar un método que se llame cuando no está sucediendo nada más, use lo siguiente:</para>
<para>
<programlisting>
sigc::connection Glib::SignalIdle::connect(const sigc::slot<bool>& slot,
int priority = Glib::PRIORITY_DEFAULT_IDLE);
</programlisting>
</para>
<para>Esto hace que <application>gtkmm</application> llame al método especificado siempre que no esté sucediendo nada más. Puede añadir una prioridad (los números más bajos indican prioridades más altas). Hay dos maneras de eliminar el manejador de señales: llamando a <methodname>disconnect()</methodname> en el objeto <classname>sigc::connection</classname>, o devolviendo <literal>false</literal> en el manejador de señales, que debe declararse como se indica a continuación:</para>
<para>
<programlisting>
bool idleFunc();
</programlisting>
</para>
<para>Dado que esto es muy similar a los métodos mencionados anteriormente esta explicación es suficiente para entender lo que sucede. Sin embargo, aquí hay un pequeño ejemplo:</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/idle/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>idleexample.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_IDLEEXAMPLE_H
#define GTKMM_EXAMPLE_IDLEEXAMPLE_H
#include <gtkmm.h>
#include <iostream>
class IdleExample : public Gtk::Window
{
public:
IdleExample();
protected:
// Signal Handlers:
bool on_timer();
bool on_idle();
void on_button_clicked();
// Member data:
Gtk::Box m_Box;
Gtk::Button m_ButtonQuit;
Gtk::ProgressBar m_ProgressBar_c;
Gtk::ProgressBar m_ProgressBar_d;
};
#endif // GTKMM_EXAMPLE_IDLEEXAMPLE_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "idleexample.h"
#include <gtkmm/application.h>
int main (int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
IdleExample example;
return app->run(example);
}
</programlisting>
<para lang="en">File: <filename>idleexample.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "idleexample.h"
IdleExample::IdleExample() :
m_Box(Gtk::ORIENTATION_VERTICAL, 5),
m_ButtonQuit("_Quit", true)
{
set_border_width(5);
// Put buttons into container
// Adding a few widgets:
add(m_Box);
m_Box.pack_start( *Gtk::manage(new Gtk::Label("Formatting Windows drive C:")));
m_Box.pack_start( *Gtk::manage(new Gtk::Label("100 MB")) );
m_Box.pack_start(m_ProgressBar_c);
m_Box.pack_start( *Gtk::manage(new Gtk::Label("")) );
m_Box.pack_start( *Gtk::manage(new Gtk::Label("Formatting Windows drive D:")));
m_Box.pack_start( *Gtk::manage(new Gtk::Label("5000 MB")) );
m_Box.pack_start(m_ProgressBar_d);
Gtk::Box* hbox = Gtk::manage( new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL,10));
m_Box.pack_start(*hbox);
hbox->pack_start(m_ButtonQuit, Gtk::PACK_EXPAND_PADDING);
// Connect the signal handlers:
m_ButtonQuit.signal_clicked().connect( sigc::mem_fun(*this,
&IdleExample::on_button_clicked) );
// formatting drive c in timeout signal handler - called once every 50ms
Glib::signal_timeout().connect( sigc::mem_fun(*this, &IdleExample::on_timer),
50 );
// formatting drive d in idle signal handler - called as quickly as possible
Glib::signal_idle().connect( sigc::mem_fun(*this, &IdleExample::on_idle) );
show_all_children();
}
void IdleExample::on_button_clicked()
{
hide();
}
// this timer callback function is executed once every 50ms (set in connection
// above). Use timeouts when speed is not critical. (ie periodically updating
// something).
bool IdleExample::on_timer()
{
double value = m_ProgressBar_c.get_fraction();
// Update progressbar 1/500th each time:
m_ProgressBar_c.set_fraction(value + 0.002);
return value < 0.99; // return false when done
}
// This idle callback function is executed as often as possible, hence it is
// ideal for processing intensive tasks.
bool IdleExample::on_idle()
{
double value = m_ProgressBar_d.get_fraction();
// Update progressbar 1/5000th each time:
m_ProgressBar_d.set_fraction(value + 0.0002);
return value < 0.99; // return false when done
}
</programlisting>
<!-- end inserted example code -->
<para>Este ejemplo señala un poco la diferencia entre los métodos en espera y los de tiempo de espera. Si necesita métodos que se llamen periódicamente, y la velocidad no es muy importante, entonces quiere métodos de tiempo de espera. Si quiere métodos que se llamen tan a menudo como sea posible (como calcular un fractal en segundo plano), entonces use métodos de espera.</para>
<para>Pruebe a ejecutar este ejemplo e incrementar la carga del sistema. La barra de progreso superior incrementará progresivamente, la inferior irá más lentamente.</para>
</sect1>
</chapter>
<chapter id="chapter-memory">
<title>Gestión de la memoria</title>
<sect1 id="sec-memory-widgets">
<title>Widgets</title>
<sect2 id="memory-normal">
<title>Gestión normal de la memoria en C++</title>
<para><application>gtkmm</application> le permite al programador controlar la vida (esto es, la construcción y la destrucción) de cualquier widget de la misma manera que cualquier otro objeto de C++. Esta flexibilidad le permite usar <literal>new</literal> y <literal>delete</literal> para crear y destruir objetos dinámicamente o para usar miembros de clase regulares (que se destruyen automáticamente cuando se destruye la clase) o usar instancias locales (que se destruyen cuando la instancia sale del alcance). Esta flexibilidad no está presente en algunos toolkits de IGU de C++, que sólo le permiten al programador usar un subconjunto de las características de gestión de memoria de C++.</para>
<para>Algunos ejemplos de gestión normal de la memoria en C++:</para>
<sect3 id="memory-class-scope">
<title>Widgets de alcance de clase</title>
<para>Si un programador no necesita asignación dinámica de memoria, puede usar los widgets automáticos en el alcance de clase. Una ventaja de los widgets automáticos en el alcance de clase es que la gestión de la memoria se agrupa en un único lugar. El programador no se arriesga a fugas de memoria por no <literal>eliminar</literal> un widget.</para>
<para>La principal desventaja de usar widgets de alcance de clase es revelar la implementación de la clase en lugar de la interfaz en su cabecera.</para>
<para>
<programlisting>
#include <gtkmm/button.h>
#include <gtkmm/window.h>
class Foo : public Gtk::Window
{
private:
Gtk::Button theButton;
// will be destroyed when the Foo object is destroyed
};
</programlisting>
</para>
</sect3>
<sect3 id="memory-function-scope">
<title>Widgets de alcance de función</title>
<para lang="en">
If a programmer does not need a class scope widget, a function scope widget
may also be used. The advantages to function scope over class scope are the
increased data hiding and reduced dependencies.
<programlisting lang="en">
{
Gtk::Button aButton;
aButton.show();
...
app->run();
}
</programlisting>
</para>
</sect3>
<sect3 id="memory-dynamic-allocation">
<title>Asignación dinámica con new y delete</title>
<para lang="en">
Although, in most cases, the programmer will prefer to allow containers to
automatically destroy their children using <function>Gtk::manage()</function> (see
below), the programmer is not required to use <function>Gtk::manage()</function>.
The traditional <literal>new</literal> and <literal>delete</literal> operators
may also be used.
<programlisting lang="en">
Gtk::Button* pButton = new Gtk::Button("Test");
// do something useful with pButton
delete pButton;
</programlisting>
Here, the programmer deletes <varname>pButton</varname> to prevent a memory leak.
</para>
</sect3>
</sect2>
<sect2 id="memory-managed-widgets">
<title>Widgets gestionados</title>
<para>Alternativamente, puede permitirle al contenedor de un widget controlar cuándo se destruye. En la mayoría de los casos, querrá que un widget dure sólo tanto tiempo como el contenedor en el que está. Para delegarle la gestión de la vida del widget a su contenedor, primero créelo con <function>Gtk::manage()</function> y empaquételo en su contenedor con <methodname>Gtk::Container::add()</methodname>, <methodname>Gtk::Box::pack_start()</methodname>, o un método similar. Ahora el widget se destruirá cuando se destruya su contenedor.</para>
<sect3 id="memory-managed-dynamic">
<title>Asignación dinamica mediante el uso de manage() y add()</title>
<para><application>gtkmm</application> proporciona la función <function>manage()</function> y métodos <methodname>add()</methodname> para crear y destruir widgets. Cada widget, excepto una ventana de nivel superior, debe añadirse o empaquetarse en un contenedor para mostrarse. La función <function>manage()</function> marca un widget para que, cuando se añada a un contenedor, este se vuelva responsable de su eliminación.</para>
<para lang="en">
<programlisting lang="en">
MyContainer::MyContainer()
{
Gtk::Button* pButton = Gtk::manage(new Gtk::Button("Test"));
add(*pButton); //add *pButton to MyContainer
}
</programlisting>
Now, when objects of type <classname>MyContainer</classname> are destroyed, the
button will also be deleted. It is no longer necessary to delete <varname>pButton</varname>
to free the button's memory; its deletion has been delegated to the
<classname>MyContainer</classname> object.
</para>
<para>Por supuesto, un contenedor de nivel superior no se añadirá a otro contenedor. El programador es responsable de la destrucción del contenedor de nivel superior usando una de las técnicas tradicionales de C++. Por ejemplo, una ventana de nivel superior podría ser sólo una instancia en su función <function>main()</function>.</para>
</sect3>
</sect2>
</sect1>
<sect1 id="sec-memory-shared-resources">
<title>Recursos compartidos</title>
<para>Algunos objetos, como <classname>Gdk::Pixbuf</classname> y <classname>Pango::Font</classname>, se obtienen de un almacén compartido. Por lo tanto, no puede instanciar sus propias instancias. Estas clases típicamente heredan de <classname>Glib::Object</classname>. En lugar de requerirle referenciar y desreferenciar estos objetos, <application>gtkmm</application> usa el puntero inteligente <classname>Glib::RefPtr<></classname>. Cairomm tiene su propio puntero inteligente, <classname>Cairo::RefPtr<></classname>.</para>
<para lang="en">
Objects such as <classname>Gdk::Pixbuf</classname> can only be instantiated
with a <methodname>create()</methodname> function. For instance,
<programlisting lang="en">
Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create_from_file(filename);
</programlisting>
</para>
<para lang="en">
You have no way of getting a bare <classname>Gdk::Pixbuf</classname>. In the
example, <varname>pixbuf</varname> is a smart pointer, so you can do this, much
like a normal pointer:
<programlisting lang="en">
int width = 0;
if(pixbuf)
{
width = pixbuf->get_width();
}
</programlisting>
</para>
<para>Cuando <varname>pixbuf</varname> salga del alcance, un <methodname>unref()</methodname> sucederá en segundo plano y ya no necesitará preocuparse más de él. No hay <literal>new</literal>, por lo que no hay <literal>delete</literal>.</para>
<para lang="en">
If you copy a <classname>RefPtr</classname>, for instance
<programlisting lang="en">
Glib::RefPtr<Gdk::Pixbuf> pixbuf2 = pixbuf;
</programlisting>
, or if you pass it as a method argument or a return type, then
<classname>RefPtr</classname> will do any necessary referencing to ensure that
the instance will not be destroyed until the last <classname>RefPtr</classname>
has gone out of scope.
</para>
<para>Consulte el <link linkend="chapter-refptr">apéndice</link> para obtener información detallada acerca de «RefPtr».</para>
<para lang="en">
If you wish to learn more about smartpointers, you might look in these
books:
<itemizedlist>
<listitem><para lang="en">
Bjarne Stroustrup, "The C++ Programming Language" Forth Edition - section 34.3
</para></listitem>
<listitem><para lang="en">
Nicolai M. Josuttis, "The C++ Standard Library" - section 4.2
</para></listitem>
</itemizedlist>
</para>
</sect1>
</chapter>
<chapter id="chapter-builder">
<title>Glade y Gtk::Builder</title>
<para>A pesar de que puede usar código C++ para instanciar y ordenar widgets, esto puede pronto volverse tedioso y repetitivo; y requiere una recompilación para mostrar los cambios. La aplicación <application>Glade</application> le permite distribuir widgets en la pantalla y luego guardar una descripción XML de la distribución. Su aplicación podrá entonces usar la API <application>Gtk::Builder</application> para cargar ese archivo XML en tiempo de ejecución y obtener un puntero a instancias de widgets nombradas específicamente.</para>
<para lang="en">
This has the following advantages:
<orderedlist>
<listitem><simpara lang="en">Less C++ code is required.</simpara></listitem>
<listitem><simpara lang="en">UI changes can be seen more quickly, so UIs are able to improve.</simpara></listitem>
<listitem><simpara lang="en">Designers without programming skills can create and edit UIs.</simpara></listitem>
</orderedlist>
</para>
<para>Aún así necesitará código C++ para ocuparse de los cambios en la interfaz de usuario desencadenados por las acciones del usuario, pero usar <application>Gtk::Builder</application> para la distribución de los widgets le permite enfocarse en la implementación de esa funcionalidad.</para>
<sect1 id="sec-builder-loading-glade-file">
<title>Cargar el archivo .glade</title>
<para lang="en">
<classname>Gtk::Builder</classname> must be used via a
<classname>Glib::RefPtr</classname>. Like all such classes, you need to use a
<methodname>create()</methodname> method to instantiate it. For instance,
<programlisting lang="en">
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file("basic.glade");
</programlisting>
This will instantiate the windows defined in the .glade file, though they will
not be shown immediately unless you have specified that via the <guilabel>Properties</guilabel>
window in <application>Glade</application>.
</para>
<para lang="en">To instantiate just one window, or just one of the child widgets, you can specify the name of a widget as the second parameter. For instance,
<programlisting lang="en">
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file("basic.glade", "treeview_products");
</programlisting>
</para>
</sect1>
<sect1 id="sec-builder-accessing-widgets">
<title>Acceso a widgets</title>
<para lang="en">
To access a widget, for instance to <methodname>show()</methodname> a dialog, use
the <methodname>get_widget()</methodname> method, providing the widget's name. This
name should be specified in the <application>Glade</application> Properties
window. If the widget could not be found, or is of the wrong type, then the
pointer will be set to 0.
<programlisting lang="en">
Gtk::Dialog* pDialog = 0;
builder->get_widget("DialogBasic", pDialog);
</programlisting>
</para>
<para><application>Gtk::Builder</application> verifica si el puntero es nulo y si el widget es del tipo esperado, y le advertirá en la línea de comandos de estos casos.</para>
<para>Recuerde que no está instanciando un widget con <methodname>get_widget()</methodname>, sólo está obteniendo un puntero a uno que ya existe. Siempre recibirá un puntero a la misma instancia cuando llame a <methodname>get_widget()</methodname> en el mismo <classname>Gtk::Builder</classname> con el mismo nombre de widget. Los widgets se instancian durante <methodname>Gtk::Builder::create_from_file()</methodname>.</para>
<para><methodname>get_widget()</methodname> devuelve widgets hijos que gestiona <function>manage()</function> (consulte el capítulo <link linkend="chapter-memory">Gestión de memoria</link>), por lo que se eliminarán cuando se elimine su contenedor padre. Por lo tanto, si sólo obtiene un widget hijo de <application>Gtk::Builder</application>, en lugar de la ventana completa, debe ponerlo en un <classname>Container</classname> o bien eliminarlo. Las <classname>Windows</classname> (como <classname>Dialogs</classname>) no pueden gestionarse porque no tienen contenedor padre, por lo que debe eliminarlas en algún momento.</para>
<sect2 id="builder-example-loading">
<title>Ejemplo</title>
<para>Este ejemplo simple muestra cómo cargar un archivo <application>Glade</application> en tiempo de ejecución y acceder a los widgets con <application>Gtk::Builder</application>.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/builder/basic?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <gtkmm.h>
#include <iostream>
Gtk::Dialog* pDialog = 0;
static
void on_button_clicked()
{
if(pDialog)
pDialog->hide(); //hide() will cause main::run() to end.
}
int main (int argc, char **argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
//Load the GtkBuilder file and instantiate its widgets:
Glib::RefPtr<Gtk::Builder> refBuilder = Gtk::Builder::create();
try
{
refBuilder->add_from_file("basic.glade");
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
return 1;
}
catch(const Glib::MarkupError& ex)
{
std::cerr << "MarkupError: " << ex.what() << std::endl;
return 1;
}
catch(const Gtk::BuilderError& ex)
{
std::cerr << "BuilderError: " << ex.what() << std::endl;
return 1;
}
//Get the GtkBuilder-instantiated Dialog:
refBuilder->get_widget("DialogBasic", pDialog);
if(pDialog)
{
//Get the GtkBuilder-instantiated Button, and connect a signal handler:
Gtk::Button* pButton = 0;
refBuilder->get_widget("quit_button", pButton);
if(pButton)
{
pButton->signal_clicked().connect( sigc::ptr_fun(on_button_clicked) );
}
app->run(*pDialog);
}
delete pDialog;
return 0;
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-builder-using-derived-widgets">
<title>Usar widgets derivados</title>
<para>Puede usar <application>Glade</application> para distribuir sus propios widgets personalizados derivados de las clases de widgets de <application>gtkmm</application>. Esto mantiene su código organizado y encapsulado. Por supuesto, no verá la apariencia exacta ni las propiedades de su widget derivado en <application>Glade</application>, pero puede especificar su ubicación, widgets hijos y las propiedades de su clase base de <application>gtkmm</application>.</para>
<para lang="en">Use <methodname>Gtk::Builder::get_widget_derived()</methodname> like so:
<programlisting lang="en">
DerivedDialog* pDialog = 0;
builder->get_widget_derived("DialogBasic", pDialog);
</programlisting>
</para>
<para>Su clase derivada debe tener un constructor que tome un puntero al tipo C subyacente, y a la instancia <classname>Gtk::Builder</classname>. Todas las clases relevantes de <application>gtkmm</application> crean alias de sus tipos C subyacentes como <classname>BaseObjectType</classname> (<classname>Gtk::Dialog</classname> define un alias de <classname>BaseObjectType</classname> como <type>GtkDialog</type>, por ejemplo).</para>
<para lang="en">
You must call the base class's constructor in the initialization list, providing the C pointer. For
instance,
<programlisting lang="en">
DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& builder)
: Gtk::Dialog(cobject)
{
}
</programlisting>
</para>
<para lang="en">
You could then encapsulate the manipulation of the child widgets in the
constructor of the derived class, maybe using <methodname>get_widget()</methodname>
or <methodname>get_widget_derived()</methodname> again. For instance,
<programlisting lang="en">
DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& builder)
: Gtk::Dialog(cobject),
m_builder(builder),
m_pButton(0)
{
//Get the Glade-instantiated Button, and connect a signal handler:
m_builder->get_widget("quit_button", m_pButton);
if(m_pButton)
{
m_pButton->signal_clicked().connect( sigc::mem_fun(*this, &DerivedDialog::on_button_quit) );
}
}
</programlisting>
</para>
<sect2 id="builder-example-accessing">
<title>Ejemplo</title>
<para>Este ejemplo mustra cómo cargar un archivo <application>Glade</application> en tiempo de ejecución y acceder a los widgets mediante una clase derivada.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/builder/derived?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>deriveddialog.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_DERIVED_DIALOG_H
#define GTKMM_EXAMPLE_DERIVED_DIALOG_H
#include <gtkmm.h>
class DerivedDialog : public Gtk::Dialog
{
public:
DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade);
virtual ~DerivedDialog();
protected:
//Signal handlers:
void on_button_quit();
Glib::RefPtr<Gtk::Builder> m_refGlade;
Gtk::Button* m_pButton;
};
#endif //GTKMM_EXAMPLE_DERIVED_WINDOW_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "deriveddialog.h"
#include <iostream>
int main (int argc, char **argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
//Load the Glade file and instiate its widgets:
Glib::RefPtr<Gtk::Builder> refBuilder = Gtk::Builder::create();
try
{
refBuilder->add_from_file("derived.glade");
}
catch(const Glib::FileError& ex)
{
std::cerr << "FileError: " << ex.what() << std::endl;
return 1;
}
catch(const Glib::MarkupError& ex)
{
std::cerr << "MarkupError: " << ex.what() << std::endl;
return 1;
}
catch(const Gtk::BuilderError& ex)
{
std::cerr << "BuilderError: " << ex.what() << std::endl;
return 1;
}
//Get the GtkBuilder-instantiated dialog::
DerivedDialog* pDialog = 0;
refBuilder->get_widget_derived("DialogDerived", pDialog);
if(pDialog)
{
//Start:
app->run(*pDialog);
}
delete pDialog;
return 0;
}
</programlisting>
<para lang="en">File: <filename>deriveddialog.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "deriveddialog.h"
DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade)
: Gtk::Dialog(cobject),
m_refGlade(refGlade),
m_pButton(0)
{
//Get the Glade-instantiated Button, and connect a signal handler:
m_refGlade->get_widget("quit_button", m_pButton);
if(m_pButton)
{
m_pButton->signal_clicked().connect( sigc::mem_fun(*this, &DerivedDialog::on_button_quit) );
}
}
DerivedDialog::~DerivedDialog()
{
}
void DerivedDialog::on_button_quit()
{
hide(); //hide() will cause main::run() to end.
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-internationalization">
<title>Internacionalización y localización</title>
<para>Las aplicaciones de <application>gtkmm</application> pueden soportar múltiples lenguajes fácilmente, incluyendo los no europeos como chino y los de derecha a izquierda como árabe. Una aplicación de <application>gtkmm</application> escrita apropiadamente y traducida usará el lenguaje apropiado en tiempo de ejecución basado en el entorno del usuario.</para>
<para>Puede no anticipar la necesidad de soportar lenguajes adicionales, pero nunca puede excluirla. Y es más fácil desarrollar la aplicación apropiadamente en primer lugar en vez de adecuarla después.</para>
<para>El proceso de escribir código fuente que se pueda traducir se llama <literal>internacionalización</literal>, a menudo abreviado como <literal>i18n</literal>. El proceso de <literal>localización</literal>, a veces abreviado <literal>l10n</literal>, proporciona el texto traducido a otros lenguajes, basado en ese código fuente.</para>
<para>La principal actividad en el proceso de internacionalización es encontrar las cadenas vistas por los usuarios y marcarlas para traducir. No necesita hacerlo todo de una vez: si crea la infraestructura del proyecto necesaria correctamente, entonces su aplicación funcionará normalmente sin importar cuántas cadenas ha cubierto.</para>
<para>Las cadenas literales deben escribirse en el código fuente en inglés, pero rodeadas por una macro. La utilidad <application>gettext</application> (o intltool) puede entonces extraer las cadenas marcadas para traducción, y sustituir el texto traducido en tiempo de ejecución.</para>
<sect1 id="sec-internationalization-intro">
<title>Preparar su proyecto</title>
<note>
<para lang="en">
In the instructions below we will assume that you will not be using
<application>gettext</application> directly, but
<application>intltool</application>, which was written specifically for
<literal>GNOME</literal>. <application>intltool</application> uses
<function>gettext()</function>, which extracts strings from source code,
but <application>intltool</application> can also combine strings from
other files, for example from desktop menu details, and GUI resource
files such as <application>Glade</application> files, into standard
<application>gettext</application> <filename>.pot/.po</filename> files.
</para>
<para lang="en">
We also assume that you are using autotools (e.g.
<application>automake</application> and
<application>autoconf</application>) to build your project, and
that you are using <ulink url="http://git.gnome.org/browse/gnome-common/tree/autogen.sh">
<literal>./autogen.sh</literal> from
<application>gnome-common</application></ulink>, which, among other
things, takes care of some <application>intltool</application>
initialization.
</para>
</note>
<para>Cree una subcarpeta llamada <literal>po</literal> en la carpeta raíz de su proyecto. Esta carpeta eventualmente contendrá todas sus traducciones. Dentro de ella, cree un archivo llamado <literal>LINGUAS</literal> y otro llamado <literal>POTFILES.in</literal>. Es práctica común crear también un archivo <literal>ChangeLog</literal> en la carpeta <literal>po</literal> para que los traductores puedan rastrear los cambios de las traducciones.</para>
<para><literal>LINGUAS</literal> contiene una lista ordenada alfabéticamente de códigos que identifican los idiomas a los que se traduce su programa (las líneas de comentarios que comienzan con <literal>#</literal> se ignoran). Cada código de idioma listado en el archivo <literal>LINGUAS</literal> debe tener un archivo <literal>.po</literal> correspondiente. Entonces, si su programa estuviera traducido al alemán y al japonés, su archivo <literal>LINGUAS</literal> se vería así:</para>
<programlisting># keep this file sorted alphabetically, one language code per line
de
ja</programlisting>
<para>(Además, tendría los archivos <literal>ja.po</literal> y <literal>de.po</literal> en su carpeta <literal>po</literal> que contendrían las traducciones al alemán y al japonés, respectivamente).</para>
<para><literal>POTFILES.in</literal> es una lista de rutas a todos los archivos que contienen cadenas marcadas para traducción, comenzando desde la carpeta raíz del proyecto. Entonces, por ejemplo, si el código fuente de su proyecto estuviera en una subcarpeta llamda <literal>src</literal>, y si tuviera dos archivos conteniendo cadenas que deben traducirse, su archivo <literal>POTFILES.in</literal> se vería así:</para>
<programlisting>src/main.cc
src/other.cc</programlisting>
<para>Si está usando <application>gettext</application> directamente, sólo puede marcar cadenas para traducir si están en el archivo de código fuente. Sin embargo, si usa <application>intltool</application>, puede marcar cadenas para traducir en una variedad de otros formatos de archivo, incluyendo archivos de IU de <application>Glade</application>, xml, <ulink url="http://standards.freedesktop.org/desktop-entry-spec/latest/">archivos .desktop</ulink> y muchos más. Por lo tanto, si ha diseñado parte de la IU de la aplicación en <application>Glade</application>, entonces también añada sus archivos <filename>.glade</filename> a la lista en <literal>POTFILES.in</literal>.</para>
<para>Ahora que hay un lugar en el que poner sus traducciones, necesita inicializar <application>intltool</application> y <application>gettext</application>. Añádale el siguiente código a su <literal>configure.ac</literal>, substituyendo «programname» con el nombre de su programa:</para>
<programlisting>IT_PROG_INTLTOOL([0.35.0])
GETTEXT_PACKAGE=programname
AC_SUBST(GETTEXT_PACKAGE)
AC_DEFINE_UNQUOTED([GETTEXT_PACKAGE], ["$GETTEXT_PACKAGE"],
[The domain to use with gettext])
AM_GLIB_GNU_GETTEXT
PROGRAMNAME_LOCALEDIR=[${datadir}/locale]
AC_SUBST(PROGRAMNAME_LOCALEDIR)</programlisting>
<para>Esta variable <varname>PROGRAMNAME_LOCALEDIR</varname> se usará luego en el archivo <literal>Makefile.am</literal>, para definir una macro que se usará cuando inicialice <application>gettext</application> en su código fuente.</para>
<para lang="en">
In the top-level Makefile.am:
<itemizedlist>
<listitem>
<para lang="en">Add <literal>po</literal> to the <literal>SUBDIRS</literal>
variable. Without this, your translations won't get built and
installed when you build the program</para>
</listitem>
<listitem>
<para lang="en">
Define <literal>INTLTOOL_FILES</literal> as:
<programlisting lang="en">INTLTOOL_FILES = intltool-extract.in \
intltool-merge.in \
intltool-update.in</programlisting>
</para>
</listitem>
<listitem>
<para lang="en">
Add <literal>INTLTOOL_FILES</literal> to the
<literal>EXTRA_DIST</literal> list of files. This ensures that when
you do a <command>make dist</command>, these commands will be
included in the source tarball.
</para>
</listitem>
<listitem>
<para lang="en">
Update your <literal>DISTCLEANFILES</literal>:
<programlisting lang="en">DISTCLEANFILES = ... intltool-extract \
intltool-merge \
intltool-update \
po/.intltool-merge-cache</programlisting>
</para>
</listitem>
</itemizedlist>
</para>
<para>En su <literal>src/Makefile.am</literal>, actualice su <literal>AM_CPPFLAGS</literal> para añadir la siguiente definición de macro de preprocesador:</para>
<programlisting>AM_CPPFLAGS = ... -DPROGRAMNAME_LOCALEDIR=\"${PROGRAMNAME_LOCALEDIR}\"</programlisting>
<para>Esta macro se usará cuando inicialice <literal>gettext</literal> en su código fuente.</para>
</sect1>
<sect1 id="sec-i18n-marking-strings">
<title>Marcar cadenas para traducir</title>
<para>Las cadenas literales deben introducirse en el código fuente en inglés, pero deben rodearse por una llamada a la función <function>gettext()</function>. Estas cadenas se extraerán para traducción y las traducciones podrán usarse en tiempo de ejecución en lugar de las cadenas originales en inglés.</para>
<para>El paquete <application>GNU gettext</application> le permite marcar cadenas en el código fuente, extraer esas cadenas para su traducción, y usar las cadenas traducidas en su aplicación.</para>
<para lang="en">
However, <application>Glib</application> defines
<function>gettext()</function>
support macros which are shorter wrappers in an easy-to-use form.
To use these macros, include <literal><glibmm/i18n.h></literal>,
and then, for example, substitute:
<programlisting lang="en">display_message("Getting ready for i18n.");</programlisting>
with:
<programlisting lang="en">display_message(_("Getting ready for i18n."));</programlisting>
</para>
<para lang="en">
For reference, it is possible to generate a file which contains all
strings which appear in your code, even if they are not marked for translation,
together with file name and line
number references. To generate such a file named
<literal>my-strings</literal>, execute the following command,
within the source code directory:
<programlisting lang="en">xgettext -a -o my-strings --omit-header *.cc *.h</programlisting>
</para>
<para lang="en">
Finally, to let your program use the translation for the current locale,
add this code to the beginning of your <filename>main.cc</filename> file, to initialize gettext.
<programlisting lang="en">bindtextdomain(GETTEXT_PACKAGE, PROGRAMNAME_LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
textdomain(GETTEXT_PACKAGE);</programlisting>
</para>
<sect2 id="sec-i18n-gettext">
<title>Cómo funciona gettext</title>
<para>El script <application>intltool</application> / <application>xgettext</application> extrae las cadenas y las pone en un archivo <filename>mypackage.pot</filename>. Los traductores de su aplicación crean sus traducciones primero copiando este archivo <filename>.pot</filename> a un archivo <filename>localename.po</filename>. Una localización identifica a un lenguaje y una codificación para ese lenguaje, incluyendo formatos de fecha y numéricos. Más tarde, cuando el texto en su código fuente haya cambiado, el script <literal>msmerge</literal> se usará para actualizar los archivos <filename>localename.po</filename> del archivo <filename>.pot</filename> regenerado.</para>
<para>En tiempo de instalación, los archivos <filename>.po</filename> se convierten a formato binario (con la extensión <filename>.mo</filename>) y se ponen en una carpeta de sistema para archivos de localización, por ejemplo <filename>/usr/share/locale/</filename>.</para>
<para>Cuando la aplicación se ejecuta, la biblioteca <application>gettext</application> verifica la carpeta de sistema para comprobar si hay un archivo <filename>.mo</filename> para el entorno de localización del usuario (puede establecer la localización, por ejemplo, con «export LANG=de_DE.UTF-8» desde una consola bash). Más tarde, cuando el programa alcance una llamada a <literal>gettext</literal>, buscará la traducción de la cadena particular. Si no encuentra ninguna, usará la cadena original.</para>
</sect2>
<sect2 id="sec-i18n-testing">
<title>Comprobar y añadir las traducciones</title>
<para lang="en">
To convince yourself that you've done well, you may wish to add a
translation for a new locale. In order to do that, go to the
<filename>po</filename> subdirectory of your project and
execute the following command:
<programlisting lang="en">intltool-update --pot</programlisting>
</para>
<para>Eso creará un archivo llamado <filename>programname.pot</filename>. Ahora, copie ese archivo a <filename>languagecode.po</filename>, como por ejemplo <filename>de.po</filename> o <filename>hu.po</filename>. También añada ese código de lenguaje a <literal>LINGUAS</literal>. El archivo <filename>.po</filename> contiene una cabecera y una lista de cadenas en inglés, con espacios para introducir las cadenas traducidas. Asegúrese de establecer la codificación del archivo <filename>.po</filename> (especificada en la cabecera, pero también en el contenido) a <literal>UTF-8</literal>.</para>
<!-- TODO: This need more explanation. What's the point of the fuzzy tag then? murrayc -->
<note>
<para>Es posible que ciertas cadenas se marquen como <literal>fuzzy</literal> en el archivo <filename>.po</filename>. Estas traducciones no sustituirán la cadena original. Para hacerlas aparecer, simplemente elimine la etiqueta <literal>fuzzy</literal>.</para>
</note>
</sect2>
<sect2 id="sec-i18n-resources">
<title>Recursos</title>
<para lang="en">
More information about what lies behind the internationalization and localization process
is presented and demonstrated in:
<itemizedlist>
<listitem>
<para lang="en">
<ulink url="https://wiki.gnome.org/TranslationProject/DevGuidelines">
L10N Guidelines for Developers</ulink>
</para>
</listitem>
<listitem>
<para lang="en">
<ulink url="http://bazaar.launchpad.net/~intltool/intltool/trunk/view/head:/README">Intltool README</ulink>
</para>
</listitem>
<listitem>
<para lang="en">
<ulink url="https://wiki.gnome.org/TranslationProject/GitHowTo">How to use Git for GNOME translators</ulink>
</para>
</listitem>
<listitem>
<para lang="en">
<ulink url="http://www.gnu.org/software/gettext/manual/gettext.html">gettext manual</ulink>
</para>
</listitem>
<listitem>
<para lang="en">
<ulink url="http://ftp.gnome.org/pub/GNOME/sources/gtkmm_hello/"><literal>gtkmm_hello</literal> example package</ulink>
</para>
</listitem>
<listitem>
<para lang="en">
<ulink url="http://ftp.gnome.org/pub/GNOME/sources/gnomemm_hello/"><literal>gnomemm_hello</literal> example package</ulink>
</para>
</listitem>
</itemizedlist>
</para>
</sect2>
</sect1>
<sect1 id="sec-i18n-expecting-utf8">
<title>Esperar UTF8</title>
<para>Una aplicación adecuadamente internacionalizada no asumirá nada sobre el número de bytes en un carácter. Eso significa que no debe usar aritmética de punteros para avanzar sobre los caracteres en una cadena, y significa que no debe usar <classname>std::string</classname> o funciones estándar de C como <function>strlen()</function> porque asumen lo mismo.</para>
<para>Sin embargo, probablemente ya evite matrices char* simples y aritmética de punteros usando <classname>std::string</classname>, por lo que sólo necesita comenzar a usar <classname>Glib::ustring</classname> en su lugar. Consulte el capítulo <link linkend="sec-basics-ustring">Conceptos básicos</link> acerca de <classname>Glib::ustring</classname>.</para>
<sect2 id="i18n-ustring-iostreams"><title>Glib::ustring y std::iostreams</title>
<!-- <para>TODO: This section is not clear - it needs to spell things out more clearly and obviously.</para> -->
<para lang="en">
Unfortunately, the integration with the standard iostreams is not completely
foolproof. <application>gtkmm</application> converts <classname>Glib::ustring</classname>s to a
locale-specific encoding (which usually is not UTF-8) if you output them to an
<classname>ostream</classname> with <function>operator<<</function>.
Likewise, retrieving <classname>Glib::ustrings</classname> from
<classname>istream</classname> with <function>operator>></function>
causes a conversion in the opposite direction. But this scheme breaks down if
you go through a <classname>std::string</classname>, e.g. by inputting text
from a stream to a <classname>std::string</classname> and then implicitly
converting it to a <classname>Glib::ustring</classname>. If the string
contained non-ASCII characters and the current locale is not UTF-8 encoded, the
result is a corrupted <classname>Glib::ustring</classname>. You can work around
this with a manual conversion. For instance, to retrieve the
<classname>std::string</classname> from a <classname>ostringstream</classname>:
<programlisting lang="en">std::ostringstream output;
output.imbue(std::locale("")); // use the user's locale for this stream
output << percentage << " % done";
label->set_text(Glib::locale_to_utf8(output.str()));</programlisting>
</para>
</sect2>
</sect1>
<sect1 id="sec-i18n-pitfalls">
<title>Errores comunes</title>
<para>Hay algunos errores comunes que eventualmente descubriría por sí mismo. Pero esta sección le ayudará a evitarlos.</para>
<sect2 id="i18n-string-semantics">
<title>Mismas cadenas, semánticas diferentes</title>
<para>A veces, dos cadenas en inglés son idénticas pero tienen distintos significados en distintos contextos, por lo que probablemente no serían idénticas al traducirlas. Dado que las cadenas en inglés se usan como claves de búsqueda, esto causa problemas.</para>
<para>En estos casos, debe agregar caracteres adicionales a las cadenas. Por ejemplo, use <literal>"jumps[noun]"</literal> y <literal>"jumps[verb]"</literal> en lugar de sólo <literal>"jumps"</literal> y límpielas de nuevo fuera de la llamada a <function>gettext</function>. Si añade caracteres adicionales también debe añadir un comentario para los traductores antes de la llamada a <function>gettext</function>. Tales comentarios se mostrarán en los archivos <filename>.po</filename>. Por ejemplo:</para>
<programlisting>// note to translators: don't translate the "[noun]" part - it is
// just here to distinguish the string from another "jumps" string
text = strip(gettext("jumps[noun]"), "[noun]");</programlisting>
</sect2>
<sect2 id="i18n-composition">
<title>Composición de cadenas</title>
<para>Los programadores de C usan <function>sprintf()</function> para componer y concatenar cadenas. C++ favorece los flujos, pero desafortunadamente, este enfoque hace la traducción difícil, porque cada fragmento de texto se traduce separadamente, sin permitirle a los traductores reordenarlos de acuerdo a la gramática del lenguaje.</para>
<para>Por ejemplo, este código podría ser problemático:</para>
<programlisting>std::cout << _("Current amount: ") << amount
<< _(" Future: ") << future << std::endl;
label.set_text(_("Really delete ") + filename + _(" now?"));</programlisting>
<para lang="en">
So you should either avoid this situation or use
<ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1ustring.html"><function>Glib::ustring::compose()</function></ulink>
which supports syntax such as:
<programlisting lang="en">std::cout << Glib::ustring::compose(
_("Current amount: %1 Future: %2"), amount, future) << std::endl;
label.set_text(Glib::ustring::compose(_("Really delete %1 now?"), filename));</programlisting>
</para>
</sect2>
<sect2 id="i18n-display-size">
<title>Asumir el tamaño de las cadenas mostradas</title>
<para>Nunca sabe cuánto espacio ocupará una cadena en la pantalla cuando se haya traducido. Bien podría duplicar el tamaño de la cadena original en inglés. Afortunadamente, la mayoría de los widgets de <application>gtkmm</application> se expandirán en tiempo de ejecución al tamaño requerido.</para>
</sect2>
<sect2 id="i18n-unusual-words">
<title>Palabras poco frecuentes</title>
<para>Debe evitar abreviaciones crípticas, lenguaje vulgar o técnico. Estos son generalmente difíciles de traducir e incluso les pueden resultar difíciles de entender a los hablantes nativos. Por ejemplo, es preferible «application» antes que «app».</para>
</sect2>
<sect2 id="i18n-non-ascii-characters">
<title>Usar caracteres no ASCII en cadenas</title>
<para>Actualmente, <application>gettext</application> no soporta caracteres no ASCII (es decir, cualquier carácter con un código superior a 127) en el código fuente. Por ejemplo, no puede usar el signo de derechos de autor (©).</para>
<para>Para solucionar temporalmente esto, puede escribir un comentario en el código fuente justo antes de la cadena, diciéndole a los traductores que usen el carácter especial si está disponible en sus lenguajes. Para el inglés, después puede hacer una traducción a inglés americano <filename>en_US.po</filename> que use ese carácter especial.</para>
</sect2>
</sect1>
<sect1 id="sec-i18n-getting-help-with-translations">
<title>Obtener ayuda con las traducciones</title>
<para lang="en">If your program is free software, there is a whole <literal>GNOME</literal>
subproject devoted to helping you make translations, the
<ulink url="https://wiki.gnome.org/TranslationProject/"><literal>GNOME</literal>
Translation Project</ulink>.</para>
<para>Consiste en que contacte a la lista de correo gnome-i18n para descubrir cómo los traductores pueden acceder a su subcarpeta <filename>po/</filename>, y añadir su proyecto a la <ulink url="http://l10n.gnome.org/module/">lista de módulos para traducir</ulink>.</para>
<para>Después asegúrese de actualizar el archivo <filename>POTFILES.in</filename> en la subcarpeta <filename>po/</filename> (<command>intltool -update -M</command> le puede ayudar con esto) para que los traductores siempre accedan a archivos <filename>myprogram.pot</filename> actualizados, y simplemente congelen las cadenas por lo menos un par de días antes de que libere una versión nueva, anunciándolo en gnome-i18n. Dependiendo del número de cadenas que su programa contenga y cómo de popular sea, los traductores empezarán a generar archivos <filename>languagename.po</filename>.</para>
<para>Tenga en cuenta que la mayoría de los equipos de idiomas sólo constan de 1 a 3 personas, por lo que si su programa contiene muchas cadenas, puede pasar un tiempo antes de que alguien tenga el tiempo de echarle un vistazo. Además, la mayoría de los traductores no quieren perder el tiempo (traducir es una tarea que consume mucho) por lo que si no juzgan que su proyecto es realmente serio (en el sentido de que esté pulido y se mantenga) podrían decidir usar su tiempo en algún otro proyecto.</para>
</sect1>
</chapter>
<chapter id="chapter-customwidgets">
<title>Widgets personalizados</title>
<para><application>gtkmm</application> le hace fácil derivar widgets nuevos heredando de una clase de widget existente, derivando de un contenedor y añadiéndole widgets hijos, o derivando de un widget de un sólo elemento y cambiando su comportamiento. Pero ocasionalmente puede encontrar que no exista ningún punto de partida adecuado. En este caso, puede implementar un widget desde cero.</para>
<sect1 id="sec-custom-containers">
<title>Contenedores personalizados</title>
<para lang="en">When deriving from <classname>Gtk::Container</classname>, you should override the following virtual methods:
<itemizedlist>
<listitem><para lang="en"><methodname>get_request_mode_vfunc()</methodname>: Return what <literal>Gtk::SizeRequestMode</literal> is preferred by the container.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_width_vfunc()</methodname>: Calculate the minimum and natural width of the container.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_height_vfunc()</methodname>: Calculate the minimum and natural height of the container.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_width_for_height_vfunc()</methodname>: Calculate the minimum and natural width of the container, if it would be given the specified height.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_height_for_width_vfunc()</methodname>: Calculate the minimum and natural height of the container, if it would be given the specified width.</para></listitem>
<listitem><para lang="en"><methodname>on_size_allocate()</methodname>: Position the child widgets, given the height and width that the container has actually been given.</para></listitem>
<listitem><para lang="en"><methodname>forall_vfunc()</methodname>: Call the same callback for each of the children.</para></listitem>
<listitem><para lang="en"><methodname>on_add()</methodname>: Add a child widget to the container.</para></listitem>
<listitem><para lang="en"><methodname>on_remove()</methodname>: Remove a child widget from the container.</para></listitem>
<listitem><para lang="en"><methodname>child_type_vfunc()</methodname>: Return what type of child can be added.</para></listitem>
</itemizedlist>
</para>
<para>Los métodos virtuales <methodname>get_request_mode_vfunc()</methodname>, <methodname>get_preferred_width_vfunc()</methodname>, <methodname>get_preferred_height_vfunc()</methodname>, <methodname>get_preferred_width_for_height_vfunc()</methodname>, <methodname>get_preferred_height_for_width_vfunc()</methodname>, y <methodname>on_size_allocate()</methodname> controlan la distribución de los widgets hijos. Por ejemplo, si su contenedor tiene 2 widgets hijos, con uno debajo del otro, su <methodname>get_request_mode_vfunc()</methodname> puede pedir una distribución de altura por anchura. Después su <methodname>get_preferred_width_vfunc()</methodname> puede reportar el máximo de las anchuras de los widgets hijos, y <methodname>get_preferred_height_for_width_vfunc()</methodname> puede reportar la suma de sus anchuras. Si quiere espacios entre los widgets hijos, entonces añádaselos a la altura y a la anchura también. El contenedor de su widget usará este resultado para asegurarse de que obtenga espacio suficiente, y no menos. Examinando al padre de cada widget, y a su padre, esta lógica eventualmente decidirá el tamaño de la ventana de nivel superior.</para>
<para>No se le garantiza obtener el <literal>Gtk::SizeRequestMode</literal> que pida. Por lo tanto, los cuatro métodos <methodname>get_preferred_xxx_vfunc()</methodname> deben devolver valores razonables.</para>
<para><methodname>on_size_allocate()</methodname> recibe la altura y anchura reales que el contenedor padre ha decidido darle a su widget. Esto podría ser más del mínimo, o aún más que el tamaño natural, por ejemplo si se ha expandido la ventana de nivel superior. Puede escoger ignorar el espacio adicional y dejar un área en blanco, expandir a sus widgets hijos para llenar el espacio, o bien expandir la separación entre sus widgets. Es su contenedor, por lo que es su decisión. No olvide llamar a <methodname>set_allocation()</methodname> dentro de su implementación de <methodname>on_size_allocate()</methodname> para usar realmente el espacio asignado que le ha ofrecido el contenedor padre.</para>
<para>A menos que su contenedor sea una ventana de nivel superior que derive de <classname>Gtk::Window</classname>, probablemente también deba llamar a <methodname>Gtk::Widget::set_has_window(false)</methodname> en su constructor. Esto significa que su contenedor no crea su propia <classname>Gdk::Window</classname>, sino que usa la de su padre (note la diferencia entre <classname>Gtk::Window</classname> y <classname>Gdk::Window</classname>). Si su contenedor no necesita su propia <classname>Gdk::Window</classname>, y no deriva de <classname>Gtk::Window</classname>, también debe reemplazar el método <methodname>on_realize()</methodname> como se describe en la sección <link linkend="sec-custom-widgets">Widgets personalizados</link>. Y, a menos que su contenedor dibuje directamente sobre la <classname>Gdk::Window</classname> subyacente, probablemente deba llamar a <methodname>set_redraw_on_allocate(false)</methodname> para mejorar el rendimiento.</para>
<para>Reemplazar <methodname>forall_vfunc()</methodname> puede permitirle a las aplicaciones operar en todos los widgets hijos de los contenedores. Por ejemplo, <methodname>show_all_children()</methodname> usa esto para encontrar a todos los widgets hijos y mostrarlos.</para>
<para>A pesar de que su contenedor puede tener su propio método para establecer widgets hijos, aún así debe proporcionar una implementación para los métodos virtuales <methodname>on_add()</methodname> y <methodname>on_remove()</methodname> de la clase base, para que los métodos add() y remove() hagan algo apropiado si se llaman.</para>
<para>Su implementación del método <methodname>child_type_vfunc()</methodname> debe reportar el tipo de widget que puede añadírsele a su contenedor, si todavía no está lleno. Esto es generalmente <methodname>Gtk::Widget::get_type()</methodname> para indicar que el contenedor puede contener cualquier clase derivada de <classname>Gtk::Widget</classname>. Si el contenedor no puede contener más widgets, entonces este método debe devolver <literal>G_TYPE_NONE</literal>.</para>
<sect2 id="custom-container-example"><title>Ejemplo</title>
<para>Este ejemplo implementa un contenedor con dos widgets hijos, uno encima del otro. Por supuesto, en este caso sería mucho más simple usar sólo una <classname>Gtk::Box</classname> vertical.</para>
<figure id="figure-custom-container">
<title>Contenedor personalizado</title>
<screenshot>
<graphic format="PNG" fileref="figures/custom_container.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/custom/custom_container/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
#include "mycontainer.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
//Child widgets:
Gtk::Box m_VBox;
MyContainer m_MyContainer;
Gtk::Button m_Button_One;
Gtk::Label m_Label_Two;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>mycontainer.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H
#define GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H
#include <gtkmm/container.h>
class MyContainer : public Gtk::Container
{
public:
MyContainer();
virtual ~MyContainer();
void set_child_widgets(Gtk::Widget& child_one, Gtk::Widget& child_two);
protected:
//Overrides:
virtual Gtk::SizeRequestMode get_request_mode_vfunc() const;
virtual void get_preferred_width_vfunc(int& minimum_width, int& natural_width) const;
virtual void get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const;
virtual void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const;
virtual void get_preferred_width_for_height_vfunc(int height, int& minimum_width, int& natural_width) const;
virtual void on_size_allocate(Gtk::Allocation& allocation);
virtual void forall_vfunc(gboolean include_internals, GtkCallback callback, gpointer callback_data);
virtual void on_add(Gtk::Widget* child);
virtual void on_remove(Gtk::Widget* child);
virtual GType child_type_vfunc() const;
Gtk::Widget* m_child_one;
Gtk::Widget* m_child_two;
};
#endif //GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_One("Child One"),
m_Label_Two("Child 2"),
m_Button_Quit("Quit")
{
set_title("Custom Container example");
set_border_width(6);
set_default_size(400, 200);
add(m_VBox);
//Add the child widgets to the custom container:
m_MyContainer.set_child_widgets(m_Button_One, m_Label_Two);
m_Label_Two.set_alignment(1.0, 0.5);
m_VBox.pack_start(m_MyContainer, Gtk::PACK_EXPAND_WIDGET);
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(6);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
&ExampleWindow::on_button_quit) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>mycontainer.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include <iostream>
#include <algorithm> // std::max
#include "mycontainer.h"
MyContainer::MyContainer()
: m_child_one(0), m_child_two(0)
{
set_has_window(false);
set_redraw_on_allocate(false);
}
MyContainer::~MyContainer()
{
/*
// These calls to Gtk::Widget::unparent() are necessary if MyContainer is
// deleted before its children. But if you use a version of gtkmm where bug
// https://bugzilla.gnome.org/show_bug.cgi?id=605728
// has not been fixed (gtkmm 3.7.10 or earlier) and the children are deleted
// before the container, these calls can make the program crash.
// That's because on_remove() is not called, when the children are deleted.
if (m_child_one)
m_child_one->unparent();
if (m_child_two)
m_child_two->unparent();
*/
}
void MyContainer::set_child_widgets(Gtk::Widget& child_one,
Gtk::Widget& child_two)
{
m_child_one = &child_one;
m_child_two = &child_two;
m_child_one->set_parent(*this);
m_child_two->set_parent(*this);
}
//This example container is a simplified VBox with at most two children.
Gtk::SizeRequestMode MyContainer::get_request_mode_vfunc() const
{
return Gtk::SIZE_REQUEST_HEIGHT_FOR_WIDTH;
}
//Discover the total amount of minimum space and natural space needed by
//this container and its children.
void MyContainer::get_preferred_width_vfunc(int& minimum_width, int& natural_width) const
{
int child_minimum_width[2] = {0, 0};
int child_natural_width[2] = {0, 0};
if(m_child_one && m_child_one->get_visible())
m_child_one->get_preferred_width(child_minimum_width[0], child_natural_width[0]);
if(m_child_two && m_child_two->get_visible())
m_child_two->get_preferred_width(child_minimum_width[1], child_natural_width[1]);
//Request a width equal to the width of the widest visible child.
minimum_width = std::max(child_minimum_width[0], child_minimum_width[1]);
natural_width = std::max(child_natural_width[0], child_natural_width[1]);
}
void MyContainer::get_preferred_height_for_width_vfunc(int width,
int& minimum_height, int& natural_height) const
{
int child_minimum_height[2] = {0, 0};
int child_natural_height[2] = {0, 0};
int nvis_children = 0;
if(m_child_one && m_child_one->get_visible())
{
++nvis_children;
m_child_one->get_preferred_height_for_width(width, child_minimum_height[0],
child_natural_height[0]);
}
if(m_child_two && m_child_two->get_visible())
{
++nvis_children;
m_child_two->get_preferred_height_for_width(width, child_minimum_height[1],
child_natural_height[1]);
}
//The allocated height will be divided equally among the visible children.
//Request a height equal to the number of visible children times the height
//of the highest child.
minimum_height = nvis_children * std::max(child_minimum_height[0],
child_minimum_height[1]);
natural_height = nvis_children * std::max(child_natural_height[0],
child_natural_height[1]);
}
void MyContainer::get_preferred_height_vfunc(int& minimum_height, int& natural_height) const
{
int child_minimum_height[2] = {0, 0};
int child_natural_height[2] = {0, 0};
int nvis_children = 0;
if(m_child_one && m_child_one->get_visible())
{
++nvis_children;
m_child_one->get_preferred_height(child_minimum_height[0], child_natural_height[0]);
}
if(m_child_two && m_child_two->get_visible())
{
++nvis_children;
m_child_two->get_preferred_height(child_minimum_height[1], child_natural_height[1]);
}
//The allocated height will be divided equally among the visible children.
//Request a height equal to the number of visible children times the height
//of the highest child.
minimum_height = nvis_children * std::max(child_minimum_height[0],
child_minimum_height[1]);
natural_height = nvis_children * std::max(child_natural_height[0],
child_natural_height[1]);
}
void MyContainer::get_preferred_width_for_height_vfunc(int height,
int& minimum_width, int& natural_width) const
{
int child_minimum_width[2] = {0, 0};
int child_natural_width[2] = {0, 0};
int nvis_children = 0;
//Get number of visible children.
if(m_child_one && m_child_one->get_visible())
++nvis_children;
if(m_child_two && m_child_two->get_visible())
++nvis_children;
if(nvis_children > 0)
{
//Divide the height equally among the visible children.
const int height_per_child = height / nvis_children;
if(m_child_one && m_child_one->get_visible())
m_child_one->get_preferred_width_for_height(height_per_child,
child_minimum_width[0], child_natural_width[0]);
if(m_child_two && m_child_two->get_visible())
m_child_two->get_preferred_width_for_height(height_per_child,
child_minimum_width[1], child_natural_width[1]);
}
//Request a width equal to the width of the widest child.
minimum_width = std::max(child_minimum_width[0], child_minimum_width[1]);
natural_width = std::max(child_natural_width[0], child_natural_width[1]);
}
void MyContainer::on_size_allocate(Gtk::Allocation& allocation)
{
//Do something with the space that we have actually been given:
//(We will not be given heights or widths less than we have requested, though
//we might get more.)
//Use the offered allocation for this container:
set_allocation(allocation);
//Get number of visible children.
int nvis_children = 0;
if(m_child_one && m_child_one->get_visible())
++nvis_children;
if(m_child_two && m_child_two->get_visible())
++nvis_children;
if(nvis_children <= 0)
return;
//Assign space to the children:
Gtk::Allocation child_allocation_one;
Gtk::Allocation child_allocation_two;
//Place the first child at the top-left:
child_allocation_one.set_x( allocation.get_x() );
child_allocation_one.set_y( allocation.get_y() );
//Make it take up the full width available:
child_allocation_one.set_width( allocation.get_width() );
if(m_child_one && m_child_one->get_visible())
{
//Divide the height equally among the visible children.
child_allocation_one.set_height( allocation.get_height() / nvis_children);
m_child_one->size_allocate(child_allocation_one);
}
else
child_allocation_one.set_height(0);
//Place the second child below the first child:
child_allocation_two.set_x( allocation.get_x() );
child_allocation_two.set_y( allocation.get_y() +
child_allocation_one.get_height());
//Make it take up the full width available:
child_allocation_two.set_width( allocation.get_width() );
//Make it take up the remaining height:
child_allocation_two.set_height( allocation.get_height() -
child_allocation_one.get_height());
if(m_child_two && m_child_two->get_visible())
m_child_two->size_allocate(child_allocation_two);
}
void MyContainer::forall_vfunc(gboolean, GtkCallback callback, gpointer callback_data)
{
if(m_child_one)
callback(m_child_one->gobj(), callback_data);
if(m_child_two)
callback(m_child_two->gobj(), callback_data);
}
void MyContainer::on_add(Gtk::Widget* child)
{
if(!m_child_one)
{
m_child_one = child;
m_child_one->set_parent(*this);
}
else if(!m_child_two)
{
m_child_two = child;
m_child_two->set_parent(*this);
}
}
void MyContainer::on_remove(Gtk::Widget* child)
{
if(child)
{
const bool visible = child->get_visible();
bool found = false;
if(child == m_child_one)
{
m_child_one = 0;
found = true;
}
else if(child == m_child_two)
{
m_child_two = 0;
found = true;
}
if(found)
{
child->unparent();
if(visible)
queue_resize();
}
}
}
GType MyContainer::child_type_vfunc() const
{
//If there is still space for one widget, then report the type of widget that
//may be added.
if(!m_child_one || !m_child_two)
return Gtk::Widget::get_type();
else
{
//No more widgets may be added.
return G_TYPE_NONE;
}
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
<sect1 id="sec-custom-widgets">
<title>Widgets personalizados</title>
<para>Derivando directamente de <classname>Gtk::Widget</classname> puede hacer todo el dibujo de su widget directamente, en lugar de sólo ordenar widgets hijos. Por ejemplo, una <classname>Gtk::Label</classname> dibuja el texto de la etiqueta, pero no hace esto usando a otros widgets.</para>
<para lang="en">When deriving from <classname>Gtk::Widget</classname>, you should
override the following virtual methods. The methods marked (optional)
need not be overridden in all custom widgets. The base class's methods
may be appropriate.
<itemizedlist>
<listitem><para lang="en"><methodname>get_request_mode_vfunc()</methodname>: (optional) Return what <literal>Gtk::SizeRequestMode</literal> is preferred by the widget.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_width_vfunc()</methodname>: Calculate the minimum and natural width of the widget.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_height_vfunc()</methodname>: Calculate the minimum and natural height of the widget.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_width_for_height_vfunc()</methodname>: Calculate the minimum and natural width of the widget, if it would be given the specified height.</para></listitem>
<listitem><para lang="en"><methodname>get_preferred_height_for_width_vfunc()</methodname>: Calculate the minimum and natural height of the widget, if it would be given the specified width.</para></listitem>
<listitem><para lang="en"><methodname>on_size_allocate()</methodname>: Position the widget, given the height and width that it has actually been given.</para></listitem>
<listitem><para lang="en"><methodname>on_realize()</methodname>: Associate a <classname>Gdk::Window</classname> with the widget.</para></listitem>
<listitem><para lang="en"><methodname>on_unrealize()</methodname>: (optional) Break the association with the <classname>Gdk::Window</classname>. </para></listitem>
<listitem><para lang="en"><methodname>on_map()</methodname>: (optional)</para></listitem>
<listitem><para lang="en"><methodname>on_unmap()</methodname>: (optional)</para></listitem>
<listitem><para lang="en"><methodname>on_draw()</methodname>: Draw on the supplied <classname>Cairo::Context</classname>.</para></listitem>
</itemizedlist>
</para>
<para>Los 6 primeros métodos en la tabla anterior también se reemplazan en los contenedores personalizados. Se describen brevemente en la sección <link linkend="sec-custom-containers">Contenedores personalizados</link>.</para>
<para>La mayoría de los widgets personalizados necesitan su propia <classname>Gdk::Window</classname> sobre la que dibujar. Después podrá llamar a <methodname>Gtk::Widget::set_has_window(true)</methodname> en su constructor (este es el valor predeterminado). Si no llama a <methodname>set_has_window(false)</methodname>, debe reemplazar a <methodname>on_realize()</methodname> y llamar a <methodname>Gtk::Widget::set_realized()</methodname> y a <methodname>Gtk::Widget::set_window()</methodname> desde allí.</para>
<sect2 id="custom-widget-example"><title>Ejemplo</title>
<para>Este ejemplo implementa un widget que dibuja un triángulo de Penrose.</para>
<figure id="figure-custom-widget">
<title>Widget personalizado</title>
<screenshot>
<graphic format="PNG" fileref="figures/custom_widget.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/custom/custom_widget/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>mywidget.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_CUSTOM_WIDGET_MYWIDGET_H
#define GTKMM_CUSTOM_WIDGET_MYWIDGET_H
#include <gtkmm/widget.h>
#include <gtkmm/cssprovider.h>
class MyWidget : public Gtk::Widget
{
public:
MyWidget();
virtual ~MyWidget();
protected:
//Overrides:
virtual Gtk::SizeRequestMode get_request_mode_vfunc() const;
virtual void get_preferred_width_vfunc(int& minimum_width, int& natural_width) const;
virtual void get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const;
virtual void get_preferred_height_vfunc(int& minimum_height, int& natural_height) const;
virtual void get_preferred_width_for_height_vfunc(int height, int& minimum_width, int& natural_width) const;
virtual void on_size_allocate(Gtk::Allocation& allocation);
virtual void on_map();
virtual void on_unmap();
virtual void on_realize();
virtual void on_unrealize();
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
Glib::RefPtr<Gdk::Window> m_refGdkWindow;
Glib::RefPtr<Gtk::CssProvider> m_refStyleProvider;
int m_scale;
};
#endif //GTKMM_CUSTOM_WIDGET_MYWIDGET_H
</programlisting>
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
#include "mywidget.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_quit();
//Child widgets:
Gtk::Box m_VBox;
MyWidget m_MyWidget;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit;
};
#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
m_Button_Quit("Quit")
{
set_title("Custom Widget example");
set_border_width(6);
set_default_size(400, 200);
add(m_VBox);
m_VBox.pack_start(m_MyWidget, Gtk::PACK_EXPAND_WIDGET);
m_MyWidget.show();
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(6);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this, &ExampleWindow::on_button_quit) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_quit()
{
hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>mywidget.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "mywidget.h"
#include <gdkmm/general.h> // for cairo helper functions
#include <iostream>
//#include <gtk/gtkwidget.h> //For GTK_IS_WIDGET()
#include <cstring>
MyWidget::MyWidget() :
//The GType name will actually be gtkmm__CustomObject_mywidget
Glib::ObjectBase("mywidget"),
Gtk::Widget(),
m_scale(1000)
{
set_has_window(true);
//This shows the GType name, which must be used in the CSS file.
std::cout << "GType name: " << G_OBJECT_TYPE_NAME(gobj()) << std::endl;
//This shows that the GType still derives from GtkWidget:
//std::cout << "Gtype is a GtkWidget?:" << GTK_IS_WIDGET(gobj()) << std::endl;
//Install a style so that an aspect of this widget may be themed via a CSS
//style sheet file:
gtk_widget_class_install_style_property(GTK_WIDGET_CLASS(
G_OBJECT_GET_CLASS(gobj())),
g_param_spec_int("example_scale",
"Scale of Example Drawing",
"The scale to use when drawing. This is just a silly example.",
G_MININT,
G_MAXINT,
500,
G_PARAM_READABLE) );
m_refStyleProvider = Gtk::CssProvider::create();
Glib::RefPtr<Gtk::StyleContext> refStyleContext = get_style_context();
refStyleContext->add_provider(m_refStyleProvider,
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
try
{
m_refStyleProvider->load_from_path("custom_gtk.css");
}
catch(const Glib::Error& ex)
{
std::cerr << "Gtk::CssProvider::load_from_path() failed: " << ex.what() << std::endl;
}
}
MyWidget::~MyWidget()
{
}
Gtk::SizeRequestMode MyWidget::get_request_mode_vfunc() const
{
//Accept the default value supplied by the base class.
return Gtk::Widget::get_request_mode_vfunc();
}
//Discover the total amount of minimum space and natural space needed by
//this widget.
//Let's make this simple example widget always need minimum 60 by 50 and
//natural 100 by 70.
void MyWidget::get_preferred_width_vfunc(int& minimum_width, int& natural_width) const
{
minimum_width = 60;
natural_width = 100;
}
void MyWidget::get_preferred_height_for_width_vfunc(int /* width */,
int& minimum_height, int& natural_height) const
{
minimum_height = 50;
natural_height = 70;
}
void MyWidget::get_preferred_height_vfunc(int& minimum_height, int& natural_height) const
{
minimum_height = 50;
natural_height = 70;
}
void MyWidget::get_preferred_width_for_height_vfunc(int /* height */,
int& minimum_width, int& natural_width) const
{
minimum_width = 60;
natural_width = 100;
}
void MyWidget::on_size_allocate(Gtk::Allocation& allocation)
{
//Do something with the space that we have actually been given:
//(We will not be given heights or widths less than we have requested, though
//we might get more)
//Use the offered allocation for this container:
set_allocation(allocation);
if(m_refGdkWindow)
{
m_refGdkWindow->move_resize( allocation.get_x(), allocation.get_y(),
allocation.get_width(), allocation.get_height() );
}
}
void MyWidget::on_map()
{
//Call base class:
Gtk::Widget::on_map();
}
void MyWidget::on_unmap()
{
//Call base class:
Gtk::Widget::on_unmap();
}
void MyWidget::on_realize()
{
//Do not call base class Gtk::Widget::on_realize().
//It's intended only for widgets that set_has_window(false).
set_realized();
//Get the themed style from the CSS file:
get_style_property("example_scale", m_scale);
std::cout << "m_scale (example_scale from the theme/css-file) is: "
<< m_scale << std::endl;
if(!m_refGdkWindow)
{
//Create the GdkWindow:
GdkWindowAttr attributes;
memset(&attributes, 0, sizeof(attributes));
Gtk::Allocation allocation = get_allocation();
//Set initial position and size of the Gdk::Window:
attributes.x = allocation.get_x();
attributes.y = allocation.get_y();
attributes.width = allocation.get_width();
attributes.height = allocation.get_height();
attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.wclass = GDK_INPUT_OUTPUT;
m_refGdkWindow = Gdk::Window::create(get_parent_window(), &attributes,
GDK_WA_X | GDK_WA_Y);
set_window(m_refGdkWindow);
//set colors
override_background_color(Gdk::RGBA("red"));
override_color(Gdk::RGBA("blue"));
//make the widget receive expose events
m_refGdkWindow->set_user_data(gobj());
}
}
void MyWidget::on_unrealize()
{
m_refGdkWindow.reset();
//Call base class:
Gtk::Widget::on_unrealize();
}
bool MyWidget::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
const double scale_x = (double)get_allocation().get_width() / m_scale;
const double scale_y = (double)get_allocation().get_height() / m_scale;
// paint the background
Gdk::Cairo::set_source_rgba(cr, get_style_context()->get_background_color());
cr->paint();
// draw the foreground
Gdk::Cairo::set_source_rgba(cr, get_style_context()->get_color());
cr->move_to(155.*scale_x, 165.*scale_y);
cr->line_to(155.*scale_x, 838.*scale_y);
cr->line_to(265.*scale_x, 900.*scale_y);
cr->line_to(849.*scale_x, 564.*scale_y);
cr->line_to(849.*scale_x, 438.*scale_y);
cr->line_to(265.*scale_x, 100.*scale_y);
cr->line_to(155.*scale_x, 165.*scale_y);
cr->move_to(265.*scale_x, 100.*scale_y);
cr->line_to(265.*scale_x, 652.*scale_y);
cr->line_to(526.*scale_x, 502.*scale_y);
cr->move_to(369.*scale_x, 411.*scale_y);
cr->line_to(633.*scale_x, 564.*scale_y);
cr->move_to(369.*scale_x, 286.*scale_y);
cr->line_to(369.*scale_x, 592.*scale_y);
cr->move_to(369.*scale_x, 286.*scale_y);
cr->line_to(849.*scale_x, 564.*scale_y);
cr->move_to(633.*scale_x, 564.*scale_y);
cr->line_to(155.*scale_x, 838.*scale_y);
cr->stroke();
return true;
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>
</chapter>
<chapter id="chapter-multi-threaded-programs">
<title>Programas con múltiples hilos</title>
<sect1 id="sec-the-constraints">
<title>Las limitaciones</title>
<para><application>glibmm</application> proporciona el conjunto normal de funciones de lanzamiento de hilos, exclusión mutua, variables condicionales y clases de bloqueo de alcance requeridas para escribir programas de múltiples hilos usando C++.</para>
<para lang="en">
However, care is required when writing programs based on <application>gtkmm</application> using
multiple threads of execution, arising from the fact that
<application>libsigc++</application>, and in particular
<classname>sigc::trackable</classname>, are not thread-safe. That's
because none of the complex interactions that occur behind the scenes
when using <application>libsigc++</application> are protected by a
mutex or other means of synchronization.
<footnote>
<para lang="en">
These interactions arise from the fact that, amongst other things, a
class inheriting from <classname>sigc::trackable</classname> will, via
that inheritance, have a <classname>std::list</classname> object
keeping track of slots created by calls to
<function>sigc::mem_fun()</function> representing any of its
non-static methods (more particularly it keeps a list of callbacks
which will null the connected slots on its destruction). Each
<classname>sigc::slot</classname> object also keeps, via
<classname>sigc::slot_rep</classname>, its own
<classname>sigc::trackable</classname> object to track any
<classname>sigc::connection</classname> objects which it needs to
inform about its demise, and also has a function to deregister itself
from any <classname>sigc::trackable</classname> on disconnection or
destruction. <classname>sigc::signal</classname> objects also keep
lists of slots, which will be updated by a call to their
<methodname>connect()</methodname> method or calls to any
<classname>sigc::connection</classname> object relating to such a
connection.
</para>
</footnote>
</para>
<sect2 id="the-rules">
<title>Las reglas</title>
<para>Esto requiere que se observen una cantidad de reglas cuando escribe programas de múltiples hilos usando <application>gtkmm</application>. Estas se exponen abajo, pero un punto a destacar es que se requiere cuidado adicional cuando deriva clases de <classname>sigc::trackable</classname>, porque los efectos no son intuitivos (consulte particularmente los puntos 4 y 5 debajo).</para>
<orderedlist>
<listitem>
<para>Use <classname>Glib::Dispatcher</classname> para invocar las funciones de <application>gtkmm</application> desde hilos de trabajo (esto se explica con má detalle en la próxima sección).</para>
</listitem>
<listitem>
<para>Un objeto <classname>sigc::signal</classname> debe considerarse propiedad del hilo que lo creó. Solo ese hilo debe conectar un objeto <classname>sigc::slot</classname> al objeto de la señal, y solo ese hilo debe llamar a <methodname>emit()</methodname> u <methodname>operator()()</methodname> sobre la señal, o anular cualquier objeto <classname>sigc::slot</classname> conectado. Sigue (junto a otras cosas) que cualquier objeto de señal proporcionado por un widget de <application>gtkmm</application> solo se opere en el hilo principal de la IGU y cualquier objeto que derive de <classname>sigc::trackable</classname> con métodos no estáticos referenciados por «slots» conectados al objeto de señal solo deben destruirse en ese hilo.</para>
</listitem>
<listitem>
<para>Cualquier objeto <classname>sigc::connection</classname> solo debe considerarse propiedad del hilo en el que se llamó al método que devuelve el objeto <classname>sigc::connection</classname>. Solo ese hilo debe llamar a métodos de <classname>sigc::connection</classname> sobre el objeto.</para>
</listitem>
<listitem>
<para>Un objeto <classname>sigc::slot</classname> creado por una llamada a <function>sigc::mem_fun()</function> que referencia un método de una clase que deriva de <classname>sigc::trackable</classname> nunca debe copiarse a otro hilo, ni otro hilo aparte del que lo creó lo debe destruir. (Una consecuencia de esto es que <methodname>Glib::Threads::Thread::create()</methodname> no debe llamarse con un argumento de «slot» creado por una llamada a <function>sigc::mem_fun()</function> que represente a un método de una clase semejante. Sin embargo, es seguro pasarle <methodname>Glib::Threads::Thread::create()</methodname> a un objeto de función representando un método así usando, por ejemplo, <function>boost::bind()</function> o, en C++11, <function>std::bin()</function> o una expresión lambda de C++11).</para>
</listitem>
<listitem>
<para>Si un objeto de clase particular deriva de <classname>sigc::trackable</classname>, solo un hilo debe crear objetos <classname>sigc::slot</classname> representando cualquiera de los métodos no estáticos de la clase llamando a <function>sigc::mem_fun()</function>. El primer hilo que cree un «slot» semejante debe considerarse dueño del objeto relevante con el propósito de crear más «slots» referenciando a <emphasis>cualquiera</emphasis> de sus métodos no estáticos que usan esa función, o anulando aquellos «slots» desconectándolos o destruyendo el objeto «trackable».</para>
</listitem>
<listitem>
<para>A pesar de que <application>glib</application> en sí es segura para hilos, cualquier envoltorio de <application>glibmm</application> que use <application>libsigc++</application> no lo será. Entonces por ejemplo solo el hilo en el bucle principal debe llamar a <methodname>Glib::SignalIdle::connect()</methodname>, <methodname>Glib::SignalIO::connect()</methodname>, <methodname>Glib::SignalTimeout::connect()</methodname>, <methodname>Glib::SignalTimeout::connect_seconds</methodname> para ese bucle principal, o manipular cualquier objeto <classname>sigc::connection</classname> que devuelvan.</para>
<para>Las variantes de «connect*_once()», <methodname>Glib::SignalIdle::connect_once()</methodname>, <methodname>Glib::SignalTimeout::connect_once()</methodname>, <methodname>Glib::SignalTimeout::connect_seconds_once()</methodname>, son seguras para hilos para cualquier caso en el que el «slot» no lo cree una llamada a <methodname>sigc::mem_fun()</methodname> que represente a un método de una clase derivada de <methodname>sigc::trackable</methodname>. Esto es similar a <methodname>Glib::Threads::Thread::create()</methodname> como se menciona en el punto 4.</para>
</listitem>
</orderedlist>
</sect2>
</sect1>
<sect1 id="sec-using-glib-dispatcher">
<title>Usar Glib::Dispatcher</title>
<para>Los «slots» conectados a objetos <classname>sigc::signal</classname> se ejecutan en el hilo que llama a <methodname>emit()</methodname> u <methodname>operator()()</methodname> en la señal. <classname>Glib::Dispatcher</classname> no se comporta de esa manera: en su lugar, sus «slots» conectados se ejecutan en el hilo en el que el objeto <classname>Glib::Dispatcher</classname> se construyó (que debe tener un bucle principal de glib). Si un objeto <classname>Glib::Dispatcher</classname> se construye en el hilo principal de la IGU (que por ende será el hilo receptor), cualquier hilo de trabajo puede emitir sobre él y sus «slot» conectados podrán ejecutar funciones de <application>gtkmm</application> con seguridad.</para>
<para>Aún así, algunas reglas de seguridad de hilos sobre el uso de <classname>Glib::Dispatcher</classname> se aplican. Como se mencionó, un objeto <classname>Glib::Dispatcher</classname> debe construirse en el hilo receptor (aquel en cuyo bucle principal ejecutará sus «slot» conectados). Por defecto este es el hilo principal del programa, a pesar de que hay un constructor <classname>Glib::Dispatcher</classname> que toma el objeto <classname>Glib::MainContext</classname> de cualquier hilo que tiene un bucle principal. Solo el hilo receptor debe llamar a <methodname>connect()</methodname> en el objeto <classname>Glib::Dispatcher</classname>, o manipular cualquier objeto <classname>sigc::connection</classname> relacionado, a menos que se emplee sincronización adicional. Sin embargo, cualquier hilo de trabajo puede emitir con seguridad en el objeto <classname>Glib::Dispatcher</classname> sin bloquear una vez que el hilo receptor ha conectado los «slot», siempre que se construya antes de que el hilo de trabajo arranque (si se construye después, normalmente se requerirá sincronización adicional para asegurar la visibilidad).</para>
<para>Dejando de lado el hecho de que los «slot» conectados siempre se ejecutan en el hilo receptor, los objetos <classname>Glib::Dispatcher</classname> son similares a los objetos <classname>sigc::signal<void;></classname>. Por lo tanto, no pueden pasar argumentos sin vincular ni devolver un valor. La mejor manera de pasar esos argumentos es con una cola segura para hilos (asíncrona). Al momento de escritura, <application>glibmm</application> no tiene una, pero mucha gente escribiendo código de hilos múltiples tendrá una disponible (son relativamente fáciles de escribir a pesar de que son detalles de combinar seguridad de hilos con seguridad fuerte de excepciones).</para>
<para>Solo el hilo receptor o de trabajo pueden emitir in objeto <classname>Glib::Dispatcher</classname>, aunque que esto debe hacerse dentro de límites razonables. En sistemas similares a Unix, los objetos <classname>Glib::Dispatcher</classname> comparten un hilo común, que en teoría podría llenarse en un sistema muy cargado ejecutando un programa con un número muy alto de objetos <classname>Dispatcher</classname> en uso. Si la tubería se llenara antes de que el bucle principal del hilo tuviera la oportunidad de leerla para vaciarla, y el hilo receptor intentara emitir, es decir escribirle cuando está en esta condición, el hilo receptor se trabaría en la escritura, bloqueándose mutuamente. Cuando el hilo receptor está por emitir, un objeto <classname>sigc::signal<void></classname> normal puede usarse en su lugar.</para>
</sect1>
<sect1 id="sec-multithread-example">
<title>Ejemplo</title>
<para lang="en">
This is an example program with two threads, one GUI thread, like in all
<application>gtkmm</application> programs, and one worker thread. The worker thread is created when you
press the <literal>Start work</literal> button. It is deleted when the work is
finished, when you press the <literal>Stop work</literal> button, or when you
press the <literal>Quit</literal> button.
</para>
<para>Se usa un <classname>Glib::Dispatcher</classname> para enviar notificaciones desde el hilo activo al hilo de la IGU. La clase <classname>ExampleWorker</classname> contiene datos a los que acceden ambos hilos. Estos datos están protegidos por una clase <classname>Glib::Threads::Mutex</classname>. Sólo el hilo de la IGU actualiza la propia IGU.</para>
<figure id="figure-multithread">
<title>Programa con múltiples hilos</title>
<screenshot>
<graphic format="PNG" fileref="figures/multithread.png"/>
</screenshot>
</figure>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/multithread?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>exampleworker.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWORKER_H
#define GTKMM_EXAMPLEWORKER_H
#include <gtkmm.h>
class ExampleWindow;
class ExampleWorker
{
public:
ExampleWorker();
// Thread function.
void do_work(ExampleWindow* caller);
void get_data(double* fraction_done, Glib::ustring* message) const;
void stop_work();
bool has_stopped() const;
private:
// Synchronizes access to member data.
mutable Glib::Threads::Mutex m_Mutex;
// Data used by both GUI thread and worker thread.
bool m_shall_stop;
bool m_has_stopped;
double m_fraction_done;
Glib::ustring m_message;
};
#endif // GTKMM_EXAMPLEWORKER_H
</programlisting>
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
#include "exampleworker.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
// Called from the worker thread.
void notify();
private:
// Signal handlers.
void on_start_button_clicked();
void on_stop_button_clicked();
void on_quit_button_clicked();
void update_start_stop_buttons();
void update_widgets();
// Dispatcher handler.
void on_notification_from_worker_thread();
// Member data.
Gtk::Box m_VBox;
Gtk::ButtonBox m_ButtonBox;
Gtk::Button m_ButtonStart;
Gtk::Button m_ButtonStop;
Gtk::Button m_ButtonQuit;
Gtk::ProgressBar m_ProgressBar;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::Dispatcher m_Dispatcher;
ExampleWorker m_Worker;
Glib::Threads::Thread* m_WorkerThread;
};
#endif // GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow() :
m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
m_ButtonBox(Gtk::ORIENTATION_HORIZONTAL),
m_ButtonStart("Start work"),
m_ButtonStop("Stop work"),
m_ButtonQuit("_Quit", /* mnemonic= */ true),
m_ProgressBar(),
m_ScrolledWindow(),
m_TextView(),
m_Dispatcher(),
m_Worker(),
m_WorkerThread(0)
{
set_title("Multi-threaded example");
set_border_width(5);
set_default_size(300, 300);
add(m_VBox);
// Add the ProgressBar.
m_VBox.pack_start(m_ProgressBar, Gtk::PACK_SHRINK);
m_ProgressBar.set_text("Fraction done");
m_ProgressBar.set_show_text();
// Add the TextView, inside a ScrolledWindow.
m_ScrolledWindow.add(m_TextView);
// Only show the scrollbars when they are necessary.
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
m_TextView.set_editable(false);
// Add the buttons to the ButtonBox.
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_ButtonStart, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_ButtonStop, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_ButtonQuit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_spacing(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
// Connect the signal handlers to the buttons.
m_ButtonStart.signal_clicked().connect(sigc::mem_fun(*this, &ExampleWindow::on_start_button_clicked));
m_ButtonStop.signal_clicked().connect(sigc::mem_fun(*this, &ExampleWindow::on_stop_button_clicked));
m_ButtonQuit.signal_clicked().connect(sigc::mem_fun(*this, &ExampleWindow::on_quit_button_clicked));
// Connect the handler to the dispatcher.
m_Dispatcher.connect(sigc::mem_fun(*this, &ExampleWindow::on_notification_from_worker_thread));
// Create a text buffer mark for use in update_widgets().
Glib::RefPtr<Gtk::TextBuffer> buffer = m_TextView.get_buffer();
buffer->create_mark("last_line", buffer->end(), /* left_gravity= */ true);
update_start_stop_buttons();
show_all_children();
}
void ExampleWindow::on_start_button_clicked()
{
if (m_WorkerThread)
{
std::cout << "Can't start a worker thread while another one is running." << std::endl;
}
else
{
// Start a new worker thread.
m_WorkerThread = Glib::Threads::Thread::create(
sigc::bind(sigc::mem_fun(m_Worker, &ExampleWorker::do_work), this));
}
update_start_stop_buttons();
}
void ExampleWindow::on_stop_button_clicked()
{
if (!m_WorkerThread)
{
std::cout << "Can't stop a worker thread. None is running." << std::endl;
}
else
{
// Order the worker thread to stop.
m_Worker.stop_work();
m_ButtonStop.set_sensitive(false);
}
}
void ExampleWindow::update_start_stop_buttons()
{
const bool thread_is_running = m_WorkerThread != 0;
m_ButtonStart.set_sensitive(!thread_is_running);
m_ButtonStop.set_sensitive(thread_is_running);
}
void ExampleWindow::update_widgets()
{
double fraction_done;
Glib::ustring message_from_worker_thread;
m_Worker.get_data(&fraction_done, &message_from_worker_thread);
m_ProgressBar.set_fraction(fraction_done);
if (message_from_worker_thread != m_TextView.get_buffer()->get_text())
{
Glib::RefPtr<Gtk::TextBuffer> buffer = m_TextView.get_buffer();
buffer->set_text(message_from_worker_thread);
// Scroll the last inserted line into view. That's somewhat complicated.
Gtk::TextIter iter = buffer->end();
iter.set_line_offset(0); // Beginning of last line
Glib::RefPtr<Gtk::TextMark> mark = buffer->get_mark("last_line");
buffer->move_mark(mark, iter);
m_TextView.scroll_to(mark);
// TextView::scroll_to(iter) is not perfect.
// We do need a TextMark to always get the last line into view.
}
}
void ExampleWindow::on_quit_button_clicked()
{
if (m_WorkerThread)
{
// Order the worker thread to stop and wait for it to stop.
m_Worker.stop_work();
m_WorkerThread->join();
}
hide();
}
// notify() is called from ExampleWorker::do_work(). It is executed in the worker
// thread. It triggers a call to on_notification_from_worker_thread(), which is
// executed in the GUI thread.
void ExampleWindow::notify()
{
m_Dispatcher.emit();
}
void ExampleWindow::on_notification_from_worker_thread()
{
if (m_WorkerThread && m_Worker.has_stopped())
{
// Work is done.
m_WorkerThread->join();
m_WorkerThread = 0;
update_start_stop_buttons();
}
update_widgets();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include <gtkmm/application.h>
int main (int argc, char* argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
ExampleWindow window;
//Shows the window and returns when it is closed.
return app->run(window);
}
</programlisting>
<para lang="en">File: <filename>exampleworker.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "exampleworker.h"
#include "examplewindow.h"
#include <sstream>
ExampleWorker::ExampleWorker() :
m_Mutex(),
m_shall_stop(false),
m_has_stopped(false),
m_fraction_done(0.0),
m_message()
{
}
// Accesses to these data are synchronized by a mutex.
// Some microseconds can be saved by getting all data at once, instead of having
// separate get_fraction_done() and get_message() methods.
void ExampleWorker::get_data(double* fraction_done, Glib::ustring* message) const
{
Glib::Threads::Mutex::Lock lock(m_Mutex);
if (fraction_done)
*fraction_done = m_fraction_done;
if (message)
*message = m_message;
}
void ExampleWorker::stop_work()
{
Glib::Threads::Mutex::Lock lock(m_Mutex);
m_shall_stop = true;
}
bool ExampleWorker::has_stopped() const
{
Glib::Threads::Mutex::Lock lock(m_Mutex);
return m_has_stopped;
}
void ExampleWorker::do_work(ExampleWindow* caller)
{
{
Glib::Threads::Mutex::Lock lock(m_Mutex);
m_has_stopped = false;
m_fraction_done = 0.0;
m_message = "";
} // The mutex is unlocked here by lock's destructor.
// Simulate a long calculation.
for (int i = 0; ; ++i) // do until break
{
Glib::usleep(250000); // microseconds
Glib::Threads::Mutex::Lock lock(m_Mutex);
m_fraction_done += 0.01;
if (i % 4 == 3)
{
std::ostringstream ostr;
ostr << (m_fraction_done * 100.0) << "% done\n";
m_message += ostr.str();
}
if (m_fraction_done >= 1.0)
{
m_message += "Finished";
break;
}
if (m_shall_stop)
{
m_message += "Stopped";
break;
}
lock.release();
caller->notify();
}
Glib::Threads::Mutex::Lock lock(m_Mutex);
m_shall_stop = false;
m_has_stopped = true;
lock.release();
caller->notify();
}
</programlisting>
<!-- end inserted example code -->
</sect1>
</chapter>
<chapter id="chapter-recommended-techniques">
<title>Técnicas recomendadas</title>
<para>Esta sección es simplemente un acopio de sabiduría, pautas generales de estilo y consejos para crear aplicaciones en <application>gtkmm</application>.</para>
<para>Use <application>autoconf</application> y <application>automake</application> de GNU. Son sus amigos :). <application>Automake</application> examina archivos de C, determina cómo dependen entre sí, y genera un <filename>Makefile</filename> para que los archivos puedan compilarse en el orden correcto. <application>Autoconf</application> permite la configuración automática de la instalación de software, manipulando un gran número de peculiaridades de cada sistema para incrementar la portabilidad.</para>
<para>Herede los widgets para organizar mejor su código. Probablemente deba heredar al menos su <classname>Window</classname> principal. Entonces podrá hacer widgets hijos y manejadores de señales miembros de esa clase.</para>
<para>Cree sus propias señales en lugar de pasar punteros. Los objetos se pueden comunicar entre sí a través de las señales y manejadores de señales. Esto es mucho más simple que objetos que contengan punteros y llamen a sus métodos entre sí. Las clases de <application>gtkmm</application> usan versiones especiales de <classname>sigc::signal</classname>, pero debe usar <classname>sigc::signal</classname> normales, como se describe en la documentación de <application>libsigc++</application>.</para>
<sect1 id="sec-application-lifetime">
<title>Tiempo de vida de la aplicación</title>
<para>La mayoría de las aplicaciones sólo tendrán una <classname>Window</classname>, o sólo una ventana principal. Estas aplicaciones pueden usar la sobrecarga <methodname>Gtk::Application::run(Gtk::Window&)</methodname>. Muestra la ventana y vuelve cuando esta se ha ocultado. Esto puede suceder cuando el usuario la cierra, o cuando su código ejecuta <methodname>hide()</methodname> en ella. Puede evitar que el usuario cierre la ventana (por ejemplo, si hay cambios sin guardar) sobrecargando <methodname>Gtk::Window::on_delete_event()</methodname>.</para>
<para>La mayoría de los ejemplos usan esta técnica.</para>
</sect1>
<sect1 id="sec-using-a-gtkmm-widget">
<title>Usar un widget de <application>gtkmm</application></title>
<para>Todos los ejemplos tienden a tener la misma estructura. Siguen estos pasos para usar un <classname>widget</classname>:</para>
<para>
<orderedlist>
<listitem>
<para>Declare una variable del tipo del <classname>Widget</classname> que quiere usar, generalmente como variable miembro de una clase contenedora derivada. También puede declarar un puntero al tipo de widget, y luego crearlo con <literal>new</literal> en su código. Aún cuando use el widget a través de un puntero, probablemente lo mejor sea hacer que el puntero sea una variable miembro de una clase contenedora para que pueda acceder a él más tarde.</para>
</listitem>
<listitem>
<para>Establezca los atributos del widget. Si el widget no tiene un constructor predeterminado, tendrá que inicializar el widget en la lista inicializadora del constructor de su clase contenedora.</para>
</listitem>
<listitem>
<para>Conecte las señales que quiere usar a los manejadores apropiados.</para>
</listitem>
<listitem>
<para>Empaquete al widget en un contenedor usando la llamada apropiada, por ejemplo, <methodname>Gtk::Container::add()</methodname> o <methodname>pack_start()</methodname>.</para>
</listitem>
<listitem>
<para>Llame a <methodname>show()</methodname> para mostrar al widget.</para>
</listitem>
</orderedlist>
</para>
<para><methodname>Gtk::Widget::show()</methodname> le permite a <application>gtkmm</application> saber que se han terminado de establecer los atributos del widget, y que está listo para mostrarse. Puede usar <methodname>Gtk::Widget::hide()</methodname> para hacerlo desaparecer de nuevo. El orden en el que muestra los widgets no es importante, pero se le sugiere mostrar la ventana de nivel superior al final; de esta manera, toda la ventana aparecerá con su contenido ya dibujado. De lo contrario, el usuario verá primero una ventana vacía, en la que los widgets se dibujarán gradualmente.</para>
</sect1>
</chapter>
<chapter id="chapter-contributing">
<title>Contribuir</title>
<para>Fueron voluntarios los que crearon este documento, al igual que mucho otro software grandioso, gratuitamente. Si tiene conocimientos de cualquier aspecto de <application>gtkmm</application> que todavía no esté documentado, por favor considere contribuir a este documento.</para>
<para>Lo ideal sería que <ulink url="http://www.gtkmm.org/bugs.shtml">proporcionara un parche</ulink> al archivo <filename>docs/tutorial/C/gtkmm-tutorial-in.xml</filename>. Este archivo está actualmente en el módulo <literal>gtkmm-documentation</literal> en el git de GNOME.</para>
<para>Si decide contribuir, por favor envíe su contribución a la lista de correo de <application>gtkmm</application>, en <ulink url="mailto:gtkmm-list@gnome.org"><gtkmm-list@gnome.org></ulink>. Además, tenga en cuenta que la totalidad de este documento es libre, y cualquier adición que proporcione también debe serlo. Esto significa que la gente debe poder usar cualquier porción de sus ejemplos en sus programas, y las copias de este documento (incluyendo su contribución) se pueden distribuir libremente.</para>
</chapter>
<appendix id="chapter-refptr">
<title>El puntero inteligente RefPtr</title>
<para lang="en">
<classname>Glib::RefPtr</classname> is a smartpointer. Specifically, it is a
reference-counting smartpointer. You might be familiar with
<classname>std::auto_ptr<></classname>, <classname>std::unique_ptr<></classname>
and <classname>std::shared_ptr<></classname>, which are also smartpointers.
<classname>Glib::RefPtr<></classname> is similar to <classname>std::shared_ptr<></classname>,
which is also reference-counting. <classname>Glib::RefPtr<></classname> was introduced
long before there was a reference-counting smartpointer in the C++ Standard Library.
</para>
<para lang="en"><ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1RefPtr.html">Reference</ulink></para>
<para>Un puntero inteligente actúa como un puntero normal. Aquí hay algunos ejemplos.</para>
<sect1 id="sec-refptr-copying">
<title>Copiado</title>
<para>Puede copiar <classname>RefPtr</classname> como punteros normales. Pero, a diferencia de los punteros normales, no necesita preocuparse por la eliminación de la instancia subyacente.</para>
<para>
<programlisting>
Glib::RefPtr<Gdk::Pixbuf> refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Glib::RefPtr<Gdk::Pixbuf> refPixbuf2 = refPixbuf;
</programlisting>
</para>
<para>Por supuesto esto significa que puede almacenar <classname>RefPtr</classname> en contenedores estándar, como <classname>std::vector</classname> o <classname>std::list</classname>.</para>
<para>
<programlisting>
std::list< Glib::RefPtr<Gdk::Pixbuf> > listPixbufs;
Glib::RefPtr<Gdk::Pixbuf> refPixbuf = Gdk::Pixbuf::create_from_file(filename);
listPixbufs.push_back(refPixbuf);
</programlisting>
</para>
</sect1>
<sect1 id="sec-refptr-dereferencing"><title>Eliminar referencia</title>
<para>Puede desreferenciar un puntero inteligente con el operador -> para llamar a los métodos de la instancia subyacente, al igual que un puntero normal.</para>
<para>
<programlisting>
Glib::RefPtr<Gdk::Pixbuf> refPixbuf = Gdk::Pixbuf::create_from_file(filename);
int width = refPixbuf->get_width();
</programlisting>
</para>
<para>Pero a diferencia de la mayoría de punteros inteligentes, no se puede utilizar el operador * para acceder a la instancia de base.</para>
<para>
<programlisting>
Glib::RefPtr<Gdk::Pixbuf> refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Gdk::Pixbuf& underlying = *refPixbuf; //Syntax error - will not compile.
</programlisting>
</para>
</sect1>
<sect1 id="sec-refptr-casting"><title>Conversión de tipos</title>
<para>Puede convertir <classname>RefPtr</classname> a tipos base, al igual que a los punteros normales.</para>
<para>
<programlisting>
Glib::RefPtr<Gtk::TreeStore> refStore = Gtk::TreeStore::create(columns);
Glib::RefPtr<Gtk::TreeModel> refModel = refStore;
</programlisting>
</para>
<para>Esto significa que cualquier método que tome un argumento <type>const Glib::RefPtr<BaseType></type> también puede tomar un <type>const Glib::RefPtr<DerivedType></type>. La conversión es implícita, al igual que lo sería con un puntero normal.</para>
<para>También puede convertir a un tipo derivado, pero la sintaxis es un poco diferente que con un puntero normal.</para>
<para>
<programlisting>
Glib::RefPtr<Gtk::TreeStore> refStore =
Glib::RefPtr<Gtk::TreeStore>::cast_dynamic(refModel);
Glib::RefPtr<Gtk::TreeStore> refStore2 =
Glib::RefPtr<Gtk::TreeStore>::cast_static(refModel);
</programlisting>
</para>
</sect1>
<sect1 id="sec-refptr-checking-for-null"><title>Verificar si es nulo</title>
<para>Al igual que con los punteros normales, puede verificar si un <classname>RefPtr</classname> apunta a algo.</para>
<para>
<programlisting>
Glib::RefPtr<Gtk::TreeModel> refModel = m_TreeView.get_model();
if(refModel)
{
int cols_count = refModel->get_n_columns();
...
}
</programlisting>
</para>
<para>Pero, a diferencia de los punteros normales, los <classname>RefPtr</classname> se inicializan automáticamente a nulo, por lo que no necesita recordar hacerlo.</para>
</sect1>
<sect1 id="sec-refptr-constness"><title>Constancia</title>
<para>El uso de la palabra reservada <literal>const</literal> en C++ no siempre es claro. Puede no darse cuenta de que <type>const Algo*</type> declara un puntero a un <type>const Algo</type>. El puntero puede cambiarse, pero no el <type>Algo</type> al que apunta.</para>
<para>Por lo tanto, el equivalente <classname>RefPtr</classname> de <type>Algo*</type> para un parámetro de un método es <type>const Glib::RefPtr<Something>&</type>, y el equivalente de <type>const Algo*</type> es <type>const Glib::RefPtr<const Something>&</type>.</para>
<para>El <literal>const ... &</literal> que los rodea está sólo por eficiencia, como usar <literal>const std::string&</literal> en lugar de <classname>std::string</classname> como método de parámetro para evitar una copia innecesaria.</para>
</sect1>
</appendix>
<appendix id="chapter-signals">
<title>Señales</title>
<sect1 id="sec-connecting-signal-handlers">
<title>Conectar manejadores de señales</title>
<para>Las clases de widgets de <application>gtkmm</application> tienen métodos de acceso a señales, como <methodname>Gtk::Button::signal_clicked()</methodname>, que le permiten conectar su manejador de señales. Gracias a la flexibilidad de <application>libsigc++</application>, la biblioteca de retornos de llamada usada por <application>gtkmm</application>, el manejador de señales puede ser casi cualquier tipo de función, pero probablemente quiera usar un método de clase. Entre los programadores de C de <application>GTK+</application>, estos manejadores de señales a menudo se llaman retornos de llamada.</para>
<para>Aquí hay un ejemplo de un manejador de señales que se conecta a una señal:</para>
<para>
<programlisting>
#include <gtkmm/button.h>
void on_button_clicked()
{
std::cout << "Hello World" << std::endl;
}
main()
{
Gtk::Button button("Hello World");
button.signal_clicked().connect(sigc::ptr_fun(&on_button_clicked));
}
</programlisting>
</para>
<para>Hay mucho para pensar en este código no funcional. Primero, identifique a los grupos involucrados:</para>
<itemizedlist>
<listitem>
<para>El manejador de señales es <methodname>on_button_clicked()</methodname>.</para>
</listitem>
<listitem>
<para>Se engancha al objeto <classname>Gtk::Button</classname> llamado <varname>button</varname>.</para>
</listitem>
<listitem>
<para>Cuando el botón emita su señal <literal>clicked</literal>, se llamará a <methodname>on_button_clicked()</methodname>.</para>
</listitem>
</itemizedlist>
<para>Ahora, mire la conexión nuevamente:</para>
<para>
<programlisting>
...
button.signal_clicked().connect(sigc::ptr_fun(&on_button_clicked));
...
</programlisting>
</para>
<para>Tenga en cuenta que no se le pasa un puntero a <methodname>on_button_clicked()</methodname> directamente al método de la señal <methodname>connect()</methodname>. En su lugar, se llama a <function>sigc::ptr_fun()</function>, y se le pasa el resultado a <methodname>connect()</methodname>.</para>
<para><function>sigc::ptr_fun()</function> genera un <classname>sigc::slot</classname>. Un «slot» es un objeto que se comporta como una función, pero en realidad es un objeto. Estos también se llaman objetos función, o funtores. <function>sigc::ptr_fun()</function> genera un «slot» para una función independiente o un método estático. <function>sigc::mem_fun()</function> genera un «slot» para un método miembro de una instancia particular.</para>
<para>Aquí hay un ejemplo ligeramente más amplio de los «slots» en acción:</para>
<para>
<programlisting>
void on_button_clicked();
class some_class
{
void on_button_clicked();
};
some_class some_object;
main()
{
Gtk::Button button;
button.signal_clicked().connect( sigc::ptr_fun(&on_button_clicked) );
button.signal_clicked().connect( sigc::mem_fun(some_object, &some_class::on_button_clicked) );
}
</programlisting>
</para>
<para>La primera llamada a <methodname>connect()</methodname> es igual a la que vio la última vez; no hay nada nuevo aquí.</para>
<para>La siguiente es más interesante. <function>sigc::mem_fun()</function> se llama con dos argumentos. El primero es <parameter>some_object</parameter>, que es el objeto al que su nuevo «slot» apuntará. El segundo argumento es un puntero a uno de sus métodos. Esta versión particular de <function>sigc::mem_fun()</function> crea un «slot» que, cuando se «llame», llamará al método al que apunta del objeto especificado, en este caso, <methodname>some_object.on_button_clicked()</methodname>.</para>
<para>Otra cosa notable acerca de este ejemplo es que se ha hecho la llamada a <methodname>connect()</methodname> dos veces para el mismo objeto de señal. Esto está perfectamente bien: cuando se pulse el botón, se llamará a ambos manejadores de señales.</para>
<para>Como se mencionó, la señal <literal>clicked</literal> del botón está esperando llamar a un método sin argumentos. Todas las señales tienen requerimientos como este: no puede enganchar una función con dos argumentos a una señal que no espera ninguno (a menos que use un adaptador, como <function>sigc::bind()</function>, por supuesto). Por lo tanto, es importante saber qué tipo de manejador de señales se esperará que conecte a una señal dada.</para>
</sect1>
<sect1 id="sec-writing-signal-handlers">
<title>Escribir manejadores de señales</title>
<para>Para descubrir qué tipo de manejador de señales puede conectar a una señal, puede buscarlo en la documentación de referencia en el archivo de cabecera. Aquí hay un ejemplo de una declaración de señal que puede ver en las cabeceras de <application>gtkmm</application>:</para>
<para>
<programlisting>
Glib::SignalProxy1<bool, Gtk::DirectionType> signal_focus()
</programlisting>
</para>
<para>Aparte del nombre de la señal (<literal>focus</literal>), hay otras dos cosas importantes que tener en cuenta aquí: el número que sigue a la palabra <classname>SignalProxy</classname> en el principio (1, en este caso), y los tipos en la lista (<type>bool</type> y <type>Gtk::DirectionType</type>). El número indica cuántos argumentos debe tener el manejador de señales; el primer tipo, <type>bool</type>, es el tipo que el manejador de señales debe devolver; y el tipo siguiente, <type>Gtk::DirectionType</type>, es el tipo del primer y único argumento de esta señal. Mirando la documentación de referencia, también puede ver los nombres de los argumentos.</para>
<para>Los mismos principios se aplican a las señales que tienen más argumentos. Aquí hay una con tres (tomada de <filename><gtkmm/textbuffer.h></filename>):</para>
<para>
<programlisting>
Glib::SignalProxy3<void, const TextBuffer::iterator&, const Glib::ustrin&, int> signal_insert();
</programlisting>
</para>
<para>Sigue la misma forma. El número 3 al final del nombre del tipo indica que el manejador de señales necesitará tres argumentos. El primer tipo en la lista es <type>void</type>, por lo que ese será el tipo que devolverá el manejador de señales. Los tres tipos siguientes son los de los argumentos, en orden. El prototipo de manejador de señales se podría ver así:</para>
<para>
<programlisting>
void on_insert(const TextBuffer::iterator& pos, const Glib::ustring& text, int bytes)
</programlisting>
</para>
</sect1>
<sect1 id="sec-disconnecting-signal-handlers">
<title>Desconectar manejadores de señales</title>
<para>Eche otro vistazo al método <literal>connect</literal> de la señal:</para>
<para>
<programlisting>
sigc::signal<void,int>::iterator signal<void,int>::connect( const sigc::slot<void,int>& );
</programlisting>
</para>
<para lang="en">
Notice that the return value is of type
<classname>sigc::signal<void,int>::iterator</classname>. This can be
implicitly converted into a <classname>sigc::connection</classname> which in
turn can be used to control the connection. By keeping a connection object you
can disconnect its associated signal handler using the method
<methodname>sigc::connection::disconnect()</methodname>.
</para>
</sect1>
<sect1 id="sec-overriding-default-signal-handlers">
<title>Reemplazar manejadores de señales predeterminados</title>
<para>Hasta ahora se la ha enseñado a realizar acciones en respuesta a pulsaciones de botones o eventos similares manejando señales. Esa es seguramente una buena manera de hacer las cosas, pero no es la única.</para>
<para>En lugar de conectar manejadores de señales a señales laboriosamente, puede simplemente hacer una clase nueva que herede de un widget (por ejemplo, un botón) y luego reemplazar el manejador de señales predeterminado, como Button::on_clicked(). Esto puede ser mucho más simple que enganchar manejadores de señales para todo.</para>
<para>La herencia no es siempre la mejor manera de realizar cosas. Sólo es útil cuando quiere que el widget maneje su propia señal por sí mismo. Si quiere que alguna otra clase maneje la señal entonces necesitará conectar un manejador separado. Esto es aún más cierto si quiere que varios objetos manejen la misma señal, o si quiere que un manejador de señales responda a la misma señal desde diferentes objetos.</para>
<para>Las clases de <application>gtkmm</application> se diseñaron con los reemplazos en mente; contienen métodos miembro virtuales específicamente pensados para reemplazarse.</para>
<para>Eche un vistazo a un ejemplo de reemplazo:</para>
<para>
<programlisting>
#include <gtkmm/button.h>
class OverriddenButton : public Gtk::Button
{
protected:
virtual void on_clicked();
}
void OverriddenButton::on_clicked()
{
std::cout << "Hello World" << std::endl;
// call the base class's version of the method:
Gtk::Button::on_clicked();
}
</programlisting>
</para>
<para>Aquí se define una clase nueva llamada <classname>OverridenButton</classname>, que hereda de <classname>Gtk::Button</classname>. Lo único que se cambia es el método <methodname>on_clicked()</methodname>, que se llama siempre que <classname>Gtk::Button</classname> emite la señal <literal>clicked</literal>. Este método imprime «Hello World» a <literal>stdout</literal> y después llama al método original, reemplazado, para dejarle a <classname>Gtk::Button</classname> hacer lo que hubiera hecho si no se hubiera reemplazado.</para>
<para>No necesita llamar siempre al método del padre; hay veces en las que no querrá hacerlo. Tenga en cuenta que se ha llamado al método padre <emphasis>después</emphasis> de escribir «Hello World», pero se podría haber llamado antes. En este ejemplo simple, no importa mucho, pero hay veces en las que lo hará. Con señales, no es tan fácil cambiar detalles como este, y puede hacer algo aquí que no puede con manejadores de señales conectados: puede llamar al método padre en la <emphasis>mitad</emphasis> de su código personalizado.</para>
</sect1>
<sect1 id="sec-binding-extra-arguments">
<title>Enlazar argumentos adicionales</title>
<para lang="en">
If you use one signal handler to catch the same signal from several widgets,
you might like that signal handler to receive some extra information. For
instance, you might want to know which button was clicked. You can do this with
<function>sigc::bind()</function>. Here's some code from the <link linkend="sec-helloworld2">helloworld2</link> example.
<programlisting lang="en">
m_button1.signal_clicked().connect( sigc::bind<Glib::ustring>( sigc::mem_fun(*this, &HelloWorld::on_button_clicked), "button 1") );
</programlisting>
This says that we want the signal to send an extra
<classname>Glib::ustring</classname> argument to the signal handler, and that
the value of that argument should be "button 1". Of course we will need to add
that extra argument to the declaration of our signal handler:
<programlisting lang="en">
virtual void on_button_clicked(Glib::ustring data);
</programlisting>
Of course, a normal "clicked" signal handler would have no arguments.
</para>
<para><function>sigc::bind()</function> no se usa comúnmente, pero a veces la encontrará útil. Si está familiarizado con programación en <application>GTK+</application>, entonces probablemente ya haya notado que esto es similar a los argumentos <literal>gpointer data</literal> adicionales que todos los retornos de llamada de GTK+ tienen. Generalmente se abusa de esto en <application>GTK+</application> para pasar información que debe almacenarse como datos miembros en un widget derivado, pero la derivación de widgets es muy difícil en C. Hay mucha menos necesidad de este «hack» en <application>gtkmm</application>.</para>
</sect1>
<sect1 id="sec-xeventsignals">
<title>Señales de eventos de X</title>
<para>La clase <classname>Widget</classname> tiene algunas señales especiales que corresponden a los eventos de X-Window subyacentes. Estas tienen el sufijo <literal>_event</literal>; por ejemplo, <methodname>Widget::signal_button_press_event()</methodname>.</para>
<para lang="en">
You might occasionally find it useful to handle X events when there's something
you can't accomplish with normal signals. <classname>Gtk::Button</classname>,
for example, does not send mouse-pointer coordinates with its
<literal>clicked</literal> signal, but you could handle
<literal>button_press_event</literal> if you needed this
information. X events are also often used to handle key-presses.
</para>
<para>Estas señales se comportan levemente diferentes. El valor que devuelve el manejador de señales indica si ha «manejado» completamente el evento. Si el valor es <literal>false</literal>, entonces <application>gtkmm</application> pasará el evento al próximo manejador de señales. Si el valor es <literal>true</literal>, entonces no se necesitará llamar a ningún otro manejador de señales.</para>
<para lang="en">
Handling an X event doesn't affect the Widget's other signals. If you handle
<literal>button_press_event</literal> for
<classname>Gtk::Button</classname>, you'll still be able to get the
<literal>clicked</literal> signal. They are emitted at (nearly) the same time.
</para>
<para>Tenga también en cuenta que no todos los widgets reciben todos los eventos de X de manera predeterminada. Para recibir eventos de X adicionales, puede usar <methodname>Gtk::Widget::set_events()</methodname> antes de mostrar al widget, o <methodname>Gtk::Widget::add_events()</methodname> después de haberlo mostrado. Sin embargo, algunos widgets deben ponerse dentro de un widget <classname>EventBox</classname> primero. Consulte el capítulo <link linkend="chapter-widgets-without-xwindows">Widgets sin X-Windows</link>.</para>
<para lang="en">
Here's a simple example:
<programlisting lang="en">
bool on_button_press(GdkEventButton* event);
Gtk::Button button("label");
button.signal_button_press_event().connect( sigc::ptr_fun(&on_button_press) );
</programlisting>
</para>
<para>Cuando el ratón esté sobre el botón y el botón del ratón se presione, se llamará a <methodname>on_button_press()</methodname>.</para>
<para><type>GdkEventButton</type> es una estructura que contiene los parámetros del evento, como las coordenadas del puntero del ratón en el momento en el que se presionó el botón. Hay varios tipos diferentes de estructuras <type>GdkEvent</type> para la variedad de eventos.</para>
<sect2 id="signal-handler-sequence">
<title>Secuencia de los manejadores de señales</title>
<para lang="en">By default, your signal handlers are called after any previously-connected
signal handlers. However, this can be a problem with the X Event signals. For instance,
the existing signal handlers, or the default signal handler, might return <literal>true</literal>
to stop other signal handlers from being called. To specify that your signal handler
should be called before the other signal handlers, so that it will always be called,
you can specify <literal>false</literal> for the optional <literal>after</literal>
parameter. For instance,
<programlisting lang="en">
button.signal_button_press_event().connect( sigc::ptr_fun(&on_mywindow_button_press), false );
</programlisting>
</para>
<para>El evento se entrega primero al widget en el que ocurrió. Si todos los manejadores de señales de ese widget devuelven <literal>false</literal> (indicando que el evento no se ha manejado), entonces la señal se propagará al widget padre y se emitirá allí. Esto continúa hasta el widget de nivel superior si ninguno maneja el evento.</para>
</sect2>
</sect1>
<sect1 id="sec-exceptions-in-signal-handlers">
<title>Excepciones en manejadores de señales</title>
<para>Cuando se aborta un programa por una excepción de C++ no manejada, a veces es posible usar un depurador para encontrar el lugar en el que la excepción se lanzó. Esto es más difícil de lo normal si un manejador de señales lanzó la excepción.</para>
<para>Esta sección describe principalmente qué puede esperar en un sistema Linux, cuando usa el <ulink url="http://www.gnu.org/software/gdb/">depurador gdb</ulink>.</para>
<para lang="en">
First, let's look at a simple example where an exception is thrown from a normal
function (no signal handler).
<programlisting lang="en">
// without_signal.cc
#include <gtkmm.h>
bool throwSomething()
{
throw "Something";
return true;
}
int main(int argc, char** argv)
{
throwSomething();
Glib::RefPtr<Gtk::Application> app =
Gtk::Application::create(argc, argv, "org.gtkmm.without_signal");
return app->run();
}
</programlisting>
</para>
<para lang="en">
Here is an excerpt from a <application>gdb</application> session. Only the most
interesting parts of the output are shown.
<programlisting lang="en">
> gdb without_signal
(gdb) run
terminate called after throwing an instance of 'char const*'
Program received signal SIGABRT, Aborted.
(gdb) backtrace
#7 0x08048864 in throwSomething () at without_signal.cc:6
#8 0x0804887d in main (argc=1, argv=0xbfffecd4) at without_signal.cc:12
</programlisting>
You can see that the exception was thrown from <filename>without_signal.cc</filename>,
line 6 (<code>throw "Something";</code>).
</para>
<para lang="en">
Now let's see what happens when an exception is thrown from a signal handler.
Here's the source code.
<programlisting lang="en">
// with_signal.cc
#include <gtkmm.h>
bool throwSomething()
{
throw "Something";
return true;
}
int main(int argc, char** argv)
{
Glib::signal_timeout().connect(sigc::ptr_fun(throwSomething), 500);
Glib::RefPtr<Gtk::Application> app =
Gtk::Application::create(argc, argv, "org.gtkmm.with_signal");
app->hold();
return app->run();
}
</programlisting>
</para>
<para lang="en">
And here's an excerpt from a <application>gdb</application> session.
<programlisting lang="en">
> gdb with_signal
(gdb) run
(with_signal:2703): glibmm-ERROR **:
unhandled exception (type unknown) in signal handler
Program received signal SIGTRAP, Trace/breakpoint trap.
(gdb) backtrace
#2 0x0063c6ab in glibmm_unexpected_exception () at exceptionhandler.cc:77
#3 Glib::exception_handlers_invoke () at exceptionhandler.cc:150
#4 0x0063d370 in glibmm_source_callback (data=0x804d620) at main.cc:212
#13 0x002e1b31 in Gtk::Application::run (this=0x804f300) at application.cc:178
#14 0x08048ccc in main (argc=1, argv=0xbfffecd4) at with_signal.cc:16
</programlisting>
The exception is caught in <application>glibmm</application>, and the program
ends with a call to <function>g_error()</function>. Other exceptions may result
in different behaviour, but in any case the exception from a signal handler is
caught in <application>glibmm</application> or <application>gtkmm</application>, and
<application>gdb</application> can't see where it was thrown.
</para>
<para lang="en">
To see where the exception is thrown, you can use the <application>gdb</application>
command <userinput>catch throw</userinput>.
<programlisting lang="en">
> gdb with_signal
(gdb) catch throw
Catchpoint 1 (throw)
(gdb) run
Catchpoint 1 (exception thrown), 0x00714ff0 in __cxa_throw ()
(gdb) backtrace
#0 0x00714ff0 in __cxa_throw () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#1 0x08048bd4 in throwSomething () at with_signal.cc:6
(gdb) continue
Continuing.
(with_signal:2375): glibmm-ERROR **
unhandled exception (type unknown) in signal handler
Program received signal SIGTRAP, Trace/breakpoint trap.
</programlisting>
</para>
<para lang="en">
If there are many caught exceptions before the interesting uncaught one, this
method can be tedious. It can be automated with the following
<application>gdb</application> commands.
<programlisting lang="en">
(gdb) catch throw
(gdb) commands
(gdb) backtrace
(gdb) continue
(gdb) end
(gdb) set pagination off
(gdb) run
</programlisting>
These commands will print a backtrace from each <code>throw</code> and continue.
The backtrace from the last (or possibly the last but one) <code>throw</code>
before the program stops, is the interesting one.
</para>
</sect1>
</appendix>
<appendix id="chapter-custom-signals">
<title>Crear sus propias señales</title>
<para>Ahora que ha visto señales y manejadores de señales en <application>gtkmm</application>, tal vez quiera usar la misma técnica para permitir interacción entre sus propias clases. Eso es realmente muy simple usando la biblioteca <application>libsigc++</application> directamente.</para>
<para>Esto no es un asunto único de <application>gtkmm</application> o de IGU. <application>gtkmm</application> usa <application>libsigc++</application> para implementar sus envoltorios de proxy para el sistema de señales de <application>GTK+</application>, pero para las señales nuevas que no son de GTK+, puede crear señales de C++ puras, usando la plantilla <classname>sigc::signal<></classname>.</para>
<para lang="en">
For instance, to create a signal that sends 2 parameters, a <type>bool</type>
and an <type>int</type>, just declare a <classname>sigc::signal</classname>,
like so:
<programlisting lang="en">
sigc::signal<void, bool, int> signal_something;
</programlisting>
</para>
<para lang="en">
You could just declare that signal as a public member variable, but
some people find that distasteful and prefer to make it available via
an accessor method, like so:
<programlisting lang="en">
class Server
{
public:
//signal accessor:
typedef sigc::signal<void, bool, int> type_signal_something;
type_signal_something signal_something();
protected:
type_signal_something m_signal_something;
};
Server::type_signal_something Server::signal_something()
{
return m_signal_something;
}
</programlisting>
</para>
<para lang="en">
You can then connect to the signal using the same syntax used when
connecting to <application>gtkmm</application> signals. For instance,
<programlisting lang="en">
server.signal_something().connect(
sigc::mem_fun(client, &Client::on_server_something) );
</programlisting>
</para>
<sect1 id="chapter-custom-signals-example"><title>Ejemplo</title>
<para>Este es un ejemplo funcional completo que define y usa señales personalizadas.</para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/signals/custom/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>server.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_SERVER_H
#define GTKMM_EXAMPLE_SERVER_H
#include <sigc++/sigc++.h>
class Server
{
public:
Server();
virtual ~Server();
void do_something();
//signal accessor:
typedef sigc::signal<void, bool, int> type_signal_something;
type_signal_something signal_something();
protected:
type_signal_something m_signal_something;
};
#endif //GTKMM_EXAMPLE_SERVER_H
</programlisting>
<para lang="en">File: <filename>client.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_CLIENT_H
#define GTKMM_EXAMPLE_CLIENT_H
#include <sigc++/sigc++.h>
//Client must inherit from sigc::trackable.
//because libsigc++ needs to keep track of the lifetime of signal handlers.
class Client : public sigc::trackable
{
public:
Client();
virtual ~Client();
//Signal handler:
void on_server_something(bool a, int b);
};
#endif //GTKMM_EXAMPLE_CLIENT_H
</programlisting>
<para lang="en">File: <filename>client.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "client.h"
#include <iostream>
Client::Client()
{
}
Client::~Client()
{
}
void Client::on_server_something(bool a, int b)
{
std::cout << "Client::on_server_something() called with these parameters: "
<< a << ", " << b << std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "server.h"
#include "client.h"
#include <iostream>
int main(int, char**)
{
Server server;
Client client;
//Connect a Server signal to the signal handler in Client.
server.signal_something().connect(sigc::mem_fun(client,
&Client::on_server_something) );
std::cout << "Before Server::do_something()" << std::endl;
//Tell the server to do something that will eventually cause it to emit the
//"something" signal.
server.do_something(); // Client::on_server_something() will run before
// Server::do_something() has completed.
std::cout << "After Server::do_something()" << std::endl;
return 0;
}
</programlisting>
<para lang="en">File: <filename>server.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "server.h"
#include <iostream>
Server::Server()
{
}
Server::~Server()
{
}
Server::type_signal_something Server::signal_something()
{
return m_signal_something;
}
void Server::do_something()
{
m_signal_something.emit(false, 5);
}
</programlisting>
<!-- end inserted example code -->
</sect1>
</appendix>
<appendix id="sec-signals-comparison">
<title>Comparación con otros sistemas de señales</title>
<para>(Nota aparte: <application>GTK+</application> llama a este esquema «señalización»; el lector perspicaz con experiencia en kits de herramientas de IGU notará que este mismo diseño se ve a menudo bajo el nombre de «emisor-receptor» (por ejemplo, en la plataforma de Metrowerks PowerPlant para los Macintosh). Funciona casi de la misma manera: uno establece <literal>emisores</literal>, y después les conecta <literal>receptores</literal>; el emisor tiene una lista de los objetos que lo están recibiendo, y cuando alguien le envía un mensaje al emisor, llama a todos sus objetos en su lista con el mensaje. En <application>gtkmm</application>, los objetos de señales hacen de emisores, y los «slots» de receptores, o algo así. Se hablará de este tema más adelante).</para>
<para>Los manejadores de señales de <application>gtkmm</application> son de «tipado fuerte», mientras que el código C de <application>GTK+</application> le permite conectar un retorno de llamada con el número y tipo incorrecto de argumentos, llevando a una violación de acceso en tiempo de ejecución. Y, a diferencia de <application>Qt</application>, <application>gtkmm</application> logra esto sin modificar el lenguaje C++.</para>
<para>Acerca de reemplazar manejadores de señales: puede hacer esto en el mundo de C plano de GTK+, también; para eso existe el sistema de objetos de GTK+. Pero en GTK+, hay que realizar algunos procedimientos complicados para obtener características orientadas a objetos como herencia y sobrecarga. En C++, es simple, dado que esas características se soportan en el lenguaje en sí; puede dejarle el trabajo pesado al compilador.</para>
<para>Este es uno de los lugares en los que se muestra realmente la belleza de C++. Uno no consideraría heredar un widget de GTK+ simplemente para reemplazar a su método de acción; es mucho problema. En GTK+, casi siempre se usan señales para realizar las tareas, a menos que se estuviera escribiendo un widget nuevo. Pero, dado que reemplazar métodos es tan fácil en C++, es enteramente práctico (y razonable) heredar de un botón para ese propósito.</para>
</appendix>
<appendix id="sec-windows-installation">
<title><application>gtkmm</application> y Win32</title>
<para>Una de las mayores ventajas de <application>gtkmm</application> es que es multiplataforma. Los programas de <application>gtkmm</application> escritos en otras plataformas como GNU/Linux generalmente pueden transferirse a Windows (y viceversa) con pocas modificaciones al código fuente.</para>
<para lang="en">
<application>gtkmm</application> currently works with the <ulink url="http://mingw.org/">MingW/GCC3.4 compiler</ulink> and Microsoft
Visual C++ 2005 or later (including the freely available express
editions) on the Windows platform. There is an
<ulink url="ftp://ftp.gnome.org/pub/GNOME/binaries/win32/gtkmm">
installer</ulink> available for gtkmm on Microsoft Windows. Refer to
<ulink url="https://wiki.gnome.org/Projects/gtkmm/MSWindows/">
https://wiki.gnome.org/Projects/gtkmm/MSWindows</ulink> for instructions how to
use it.
</para>
<sect1 id="sec-building-on-win32">
<title>Construir aplicaciones <application>gtkmm</application> en Win32</title>
<para lang="en">Please see <ulink url="https://wiki.gnome.org/Projects/gtkmm/MSWindows/BuildingGtkmm">
https://wiki.gnome.org/Projects/gtkmm/MSWindows/BuildingGtkmm</ulink> for instructions on how to build gtkmm on Windows.
</para>
</sect1>
</appendix>
<appendix id="chapter-working-with-source">
<title>Trabajar con el código fuente de gtkmm</title>
<para>Si está interesado o interesada en ayudar con el desarrollo de <application>gtkmm</application>, o arreglar un error en <application>gtkmm</application>, probablemente necesite construir la versión de desarrollo de <application>gtkmm</application>. Sin embargo, no debe instalar una versión de desarrollo sobre su versión estable. En su lugar, debe instalarla junto a su instalación de <application>gtkmm</application> existente, en una ruta separada.</para>
<para lang="en">
The easiest way to do this is using <ulink url="https://wiki.gnome.org/Projects/Jhbuild">jhbuild</ulink>.
<application>jhbuild</application> is a program that makes building GNOME
software much easier by calculating dependencies and building things in the
correct order. This section will give a brief explanation of how to set up
<application>jhbuild</application> to build and install <application>gtkmm</application> from the
source repository (git). For up-to-date information
on <application>jhbuild</application>, please refer to the <ulink url="http://developer.gnome.org/jhbuild/unstable/">jhbuild manual</ulink>.
If you need assistance using <application>jhbuild</application>, you should
ask for help on the <ulink url="http://mail.gnome.org/mailman/listinfo/gnome-love">gnome-love
mailing list</ulink>.
</para>
<note>
<para lang="en">
Note that to build <application>gtkmm</application> from git, you'll often need to build many of its
dependencies from git as well. <application>jhbuild</application> makes
this easier than it would normally be, but it will take quite a while to
build and install them all. You will probably encounter build problems,
though these will usually be corrected quickly if you report them.
</para>
</note>
<sect1 id="sec-setting-up-jhbuild">
<title>Configurar JHBuild</title>
<para lang="en">
To set up <application>jhbuild</application>, follow the basic
installation instructions from the <ulink url="http://developer.gnome.org/jhbuild/unstable/">jhbuild manual</ulink>.
After you have installed <application>jhbuild</application>, you
should copy the sample <application>jhbuild</application> configuration
file into your home directory by executing the following command from the
<application>jhbuild</application> directory:
<screen lang="en">$ cp examples/sample.jhbuildrc ~/.jhbuildrc</screen>
</para>
<para lang="en">
The <application>gtkmm</application> module is defined in the
<filename>gnome-suites-core-deps-3.x.modules</filename> moduleset, so edit your
<filename>.jhbuildrc</filename> file and set your moduleset setting to the
latest version e.g. like so:
<programlisting lang="en">moduleset = 'gnome-suites-core-deps-3.12'</programlisting>
</para>
<para lang="en">
After setting the correct moduleset, you need to tell
<application>jhbuild</application> which module or modules to build. To
build <application>gtkmm</application> and all of its dependencies, set <varname>modules</varname>
like so:
<programlisting lang="en">modules = [ 'gtkmm' ]</programlisting>
</para>
<para>Puede construir varios módulos estableciendo la variable <varname>modules</varname> a un metapaquete, como por ejemplo <literal>meta-gnome-core</literal>, o listando más de un nombre de módulo. La variable <varname>modules</varname> especifica qué módulos se construirán cuando no especifique explícitamente nada en la línea de comandos. Puede construir un conjunto de módulos diferente más tarde especificándolo en la línea de comandos (por ejemplo, <command>jhbuild build gtkmm</command>).</para>
<important>
<title>Establecer un prefijo</title>
<para>De manera predeterminada, <application>jhbuild</application> está configurado para instalar todo el software construido con <application>jhbuild</application> bajo el prefijo <filename>/opt/gnome</filename>. Puede elegir un prefijo diferente, pero se recomienda que lo mantenga diferente de otro software que haya instalado (no lo establezca a <filename>/usr</filename>). Si ha seguido las instrucciones de jhbuild, entonces este prefijo le corresponde a su usuario, por lo que no necesitará ejecutar jhbuild como <literal>root</literal>.</para>
</important>
<para>Cuando descarga <application>jhbuild</application> desde el repositorio git, obtiene varios archivos <filename>.module</filename>, especificando las dependencias entre módulos. De manera predeterminada, <application>jhbuild</application> no usa las versiones descargadas de estos archivos, sino que lee las últimas en el repositorio git. Esto generalmente es lo que quiere. Si no es así, use la variable <varname>use_local_modulesets</varname> en <filename>.jhbuildrc</filename>.</para>
</sect1>
<sect1 id="sec-installing-jhbuild">
<title>Instalar y utilizar la versión de git de <application>gtkmm</application></title>
<para lang="en">
Once you've configured <application>jhbuild</application> as described
above, building <application>gtkmm</application> should be relatively straightforward. The first
time you run <application>jhbuild</application>, you should run the
following sequence of commands to ensure that
<application>jhbuild</application> has the required tools and verify that
it is set up correctly:
<screen lang="en">$ jhbuild bootstrap
$ jhbuild sanitycheck</screen>
</para>
<sect2 id="jhbuild-installing-gtkmm">
<title>Instalar <application>gtkmm</application> con <application>jhbuild</application></title>
<para>Si todo funcionó correctamente, podrá construir <application>gtkmm</application> y a todas sus dependencias desde git ejecutando <command>jhbuild build</command> (o, si no especificó <application>gtkmm</application> en la variable <varname>modules</varname>, con el comando <command>jhbuild build gtkmm</command>).</para>
<para>Este comando construirá e instalará una serie de módulos y probablemente tarde mucho tiempo la primera vez. Después de la primera vez, sin embargo, debería ir mucho más rápido dado que sólo tendrá que reconstruir los archivos que han cambiado desde la última vez. Alternativamente, después de haber construido e instalado <application>gtkmm</application> por primera vez, lo podrá reconstruir por sí mismo (sin reconstruir todas sus dependencias) con el comando <command>jhbuild buildone gtkmm</command>.</para>
</sect2>
<sect2 id="jhbuild-using-gtkmm">
<title>Usar la versión de git de <application>gtkmm</application></title>
<para>Después de que haya instalado la versión de git de <application>gtkmm</application>, ya estará listo para comenzar a usarlo y a experimentar con él. Para usar la versión nueva de <application>gtkmm</application> que ha acabado de instalar, necesitará establecer algunas variables de entorno para que su script <filename>configure</filename> sepa dónde encontrar las bibliotecas nuevas. Afortunadamente, <application>jhbuild</application> ofrece una solución fácil a este problema. Ejecutar el comando <command>jhbuild shell</command> arrancará un intérprete nuevo con todas las variables de entorno correctas establecidas. Ahora, si reconfigura y construye su proyecto como hace siempre, debería enlazarse con las bibliotecas recientemente instaladas. Para volver a su entorno previo, simplemente salga del intérprete de <application>jhbuild</application>.</para>
<para>Una vez que haya construido su software, también necesitará ejecutar su programa dentro del entorno de jhbuild. Para hacerlo, puede usar de nuevo el comando <command>jhbuild shell</command> para arrancar un intérprete nuevo con el entorno de <application>jhbuild</application> configurado. Alternativamente, puede ejecutar un solo comando en el entorno de <application>jhbuild</application> usando el siguiente comando: <command>jhbuild run nombre-de-comando</command>. En este caso, el comando se ejecutará con las variables de entorno correctas establecidas, pero retornará a su entorno previo después de que el programa salga.</para>
</sect2>
</sect1>
</appendix>
<appendix id="chapter-wrapping-c-libraries">
<title>Envolver bibliotecas C con gmmproc</title>
<para><application>gtkmm</application> usa la herramienta <command>gmmproc</command> para generar la mayor parte de su código fuente, usando archivos .defs que definen las API de las bibliotecas basadas en <classname>GObject</classname>. Es por esto que es bastante fácil crear envoltorios con el estilo de gtkmm adicionales de otras bibliotecas basadas en glib/GObject.</para>
<para>Esto involucra una variedad de herramientas, algunas de ellas obsoletas, pero que al menos funcionan, y que varios proyectos han usado exitosamente.</para>
<sect1 id="sec-wrapping-build-structure">
<title>La estructura de construcción</title>
<para>La generación del código fuente para una API envoltorio del estilo de gtkmm requiere el uso de herramientas como <command>gmmproc</command> y <filename>generate_wrap_init.pl</filename>. En teoría, podría escribir sus propios archivos de construcción para usarlas apropiadamente, pero una opción mucho mejor es hacer uso de la infraestructura de construcción proporcionada por el módulo mm-common. Para empezar, ayuda mucho escoger un módulo de enlace existente como un ejemplo para consultar.</para>
<para lang="en">For instance, let's pretend that we are wrapping a C library called
libsomething. It provides a <classname>GObject</classname>-based API with
types named, for instance, <classname>SomeWidget</classname> and
<classname>SomeStuff</classname>.</para>
<sect2 id="copying-skeleton-project">
<title>Copiar el esqueleto del proyecto</title>
<para lang="en">Typically our wrapper library would be called libsomethingmm. We can start by
copying the <ulink url="http://git.gnome.org/browse/mm-common/tree/skeletonmm">skeleton
source tree</ulink> from the mm-common module.
<programlisting lang="en">
$ git clone git://git.gnome.org/mm-common
$ cp -a mm-common/skeletonmm libsomethingmm
</programlisting>
</para>
<para lang="en">This provides a directory structure for the source .hg and .ccg files and the generated .h
and .cc files, with <filename>filelist.am</filename> Automake include files that can specify the
various files in use, in terms of generic Automake variables. The directory structure usually
looks like this, after we have renamed the directories appropriately:
<itemizedlist>
<listitem><para lang="en"><filename>libsomethingmm</filename>: The top-level directory.</para>
<itemizedlist>
<listitem><para lang="en"><filename>libsomething</filename>: Contains the main include file and the pkg-config .pc file.</para>
<itemizedlist>
<listitem><para lang="en"><filename>src</filename>: Contains .hg and .ccg source files.</para></listitem>
<listitem><para lang="en"><filename>libsomethingmm</filename>: Contains generated and hand-written .h and .cc files.</para>
<itemizedlist>
<listitem><para lang="en"><filename>private</filename>: Contains generated <filename>*_p.h</filename> files.</para></listitem>
</itemizedlist>
</listitem>
</itemizedlist>
</listitem>
</itemizedlist>
</listitem>
</itemizedlist>
</para>
<para lang="en">As well as renaming the directories, we should rename some of the source
files. For instance:
<programlisting lang="en">
$ for f in $(find libsomethingmm -depth -name '*skeleton*'); do \
d="${f%/*}"; b="${f##*/}"; mv "$f" "$d/${b//skeleton/libsomething}"; \
done
</programlisting>
A number of the skeleton files must still be filled in with project-specific content later.
</para>
<para>Tenga en cuenta que los archivos que terminan en <filename>.in</filename> se utilizan para generar archivos con el mismo nombre pero sin el sufijo <filename>.in</filename>, mediante la sustitución de algunas variables con valores reales durante la fase de configuración.</para>
</sect2>
<sect2 id="modifying-build-files">
<title>Modificar archivos de construcción</title>
<para>Ahora se editan los archivos para adaptarlos a las necesidades. Tal vez prefiera usar una utilidad para buscar y reemplazar múltiples archivos, como <command>regexxer</command>. Tenga en cuenta que casi todos los archivos proporcionados con el esqueleto del árbol de fuentes contienen texto con marcadores de posición. Es por esto que las sustituciones se deben hacer globalmente, y no limitarse a los archivos de Automake y Autoconf.</para>
<para>Todas las menciones de <varname>skeleton</varname> deben reemplazarse por el nombre correcto de la biblioteca de C que está envolviendo, como «something» o «libsomething». De la misma manera, todas las instancias de <varname>SKELETON</varname> deben reemplazarse por «SOMETHING» o «LIBSOMETHING», y todas las apariciones de <varname>Skeleton</varname> deben cambiarse por «Something».</para>
<para>De la misma manera, reemplace todas las instancias de <varname>Joe Hacker</varname> por el nombre del titular de los derechos de autor, quien probablemente sea usted. Haga lo mismo para la dirección de correo-e <varname>joe@example.com</varname>.</para>
<sect3 id="modifying-configure.ac">
<title>configure.ac</title>
<para lang="en">In <filename>configure.ac</filename>,
<itemizedlist>
<listitem><para lang="en">The <function>AC_CONFIG_SRCDIR()</function> line must mention a file
in our source tree. We can edit this later if we don't yet know the
names of any of the files that we will create.</para></listitem>
<listitem><para lang="en">It is common for binding modules to track the version number
of the library they are wrapping. So, for instance, if the C library is
at version 1.23.4, then the initial version of the binding module would
be 1.23.0. However, avoid starting with an even minor version number as
that usually indicates a stable release.</para></listitem>
<listitem><para lang="en">The <function>AC_CONFIG_HEADERS()</function> line is used to
generate two or more configuration header files. The first header file
in the list contains all configuration macros which are set during the
configure run. The remaining headers in the list contain only a subset
of configuration macros and their corresponding <filename>config.h.in</filename>
file will not be autogenerated. The reason for this separation is that
the namespaced configuration headers are installed with your library and
define publically visible macros.</para></listitem>
<listitem><para lang="en">The <function>AC_SUBST([SOMETHINGMM_MODULES], ['...'])</function>
line may need to be modified to check for the correct dependencies.</para></listitem>
<listitem><para lang="en">The <function>AC_CONFIG_FILES()</function> block must mention
the correct directory names, as described above.</para></listitem>
</itemizedlist>
</para>
</sect3>
<sect3 id="modifying-makefile.am">
<title>Archivos Makefile.am</title>
<para lang="en">Next we must adapt the various <filename>Makefile.am</filename> files:
<itemizedlist>
<listitem><para lang="en">In <filename>skeleton/src/Makefile.am</filename> we
must mention the correct values for the generic variables that are used
elsewhere in the build system:</para>
<variablelist>
<varlistentry>
<term lang="en"><varname>binding_name</varname></term>
<listitem><para lang="en">The name of the library, such as
libsomethingmm.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><varname>wrap_init_flags</varname></term>
<listitem><para lang="en">Additional command-line flags passed to the
<filename>generate_wrap_init.pl</filename> script, such
as the C++ namespace and the parent directory prefix of
include files.</para></listitem>
</varlistentry>
</variablelist>
</listitem>
<listitem><para lang="en">In <filename>skeleton/skeletonmm/Makefile.am</filename> we
must mention the correct values for the generic variables that are used
elsewhere in the build system:</para>
<variablelist>
<varlistentry>
<term lang="en"><varname>lib_LTLIBRARIES</varname></term>
<listitem><para lang="en">This variable must mention the correct library
name, and this library name must be used to form the
<varname>_SOURCES</varname>, <varname>_LDFLAGS</varname>, and
<varname>_LIBADD</varname> variable names. It is permissible to
use variables substituted by <filename>configure</filename> like
<varname>@SOMETHINGMM_API_VERSION@</varname> as part of the
variable names.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><varname>AM_CPPFLAGS</varname></term>
<listitem><para lang="en">The command line options passed to the C
preprocessor.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><varname>AM_CXXFLAGS</varname></term>
<listitem><para lang="en">The command line options passed to the C++
compiler.</para></listitem>
</varlistentry>
</variablelist>
</listitem>
</itemizedlist>
</para>
</sect3>
<sect3 id="creating-hg-ccg">
<title>Crear archivos .hg y .ccg</title>
<para>Ahora se deben crear los primeros archivos <filename>.hg</filename> y <filename>.ccg</filename>, para envolver uno de los objetos en la biblioteca de C. Ya existen un par de archivos de fuentes de ejemplo: <filename>skeleton.ccg</filename> y <filename>skeleton.hg</filename>. Cree copias de estos archivos si es necesario.</para>
<para>Se deben mencionar todos los archivos <filename>.hg</filename> y <filename>.ccg</filename> en el archivo <filename>skeleton/src/filelist.am</filename>, típicamente en la variable <varname>files_hg</varname>.</para>
<para>Cualquier archivo de fuentes <filename>.h</filename> y <filename>.cc</filename> adicional no generado se puede poner en <filename>skeleton/skeletonmm/</filename> y listar en <filename>skeleton/skeletonmm/filelist.am</filename>, típicamente en las variables <varname>files_extra_h</varname> y <varname>files_extra_cc</varname>.</para>
<para>En la sección <link linkend="sec-wrapping-hg-files">archivos .hg y .ccg</link> puede aprender acerca de la sintaxis usada en estos archivos.</para>
</sect3>
</sect2>
</sect1>
<sect1 id="sec-wrapping-defs-files">
<title>Generar los archivos .defs.</title>
<para lang="en">The <filename>.defs</filename> files are text files, in a lisp format, that describe the API
of a C library, including its
<itemizedlist>
<listitem><para lang="en">objects (GObjects, widgets, interfaces, boxed-types and plain structs)</para></listitem>
<listitem><para lang="en">functions</para></listitem>
<listitem><para lang="en">enums</para></listitem>
<listitem><para lang="en">signals</para></listitem>
<listitem><para lang="en">properties</para></listitem>
<listitem><para lang="en">vfuncs</para></listitem>
</itemizedlist>
</para>
<para lang="en">At the moment, we have separate tools for generating different parts of
these <filename>.defs</filename>, so we split them up into separate files.
For instance, in the <filename>gtk/src</filename> directory of the <application>gtkmm</application>
sources, you will find these files:
<variablelist>
<varlistentry>
<term lang="en"><filename>gtk.defs</filename></term>
<listitem><para lang="en">Includes the other files.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><filename>gtk_methods.defs</filename></term>
<listitem><para lang="en">Objects and functions.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><filename>gtk_enums.defs</filename></term>
<listitem><para lang="en">Enumerations.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><filename>gtk_signals.defs</filename></term>
<listitem><para lang="en">Signals and properties.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><filename>gtk_vfuncs.defs</filename></term>
<listitem><para lang="en">vfuncs (function pointer member fields in structs), written by hand.</para></listitem>
</varlistentry>
</variablelist>
</para>
<para lang="en">The <filename>skeletonmm/codegen/generate_defs_and_docs.sh</filename> script
generates all <filename>.defs</filename> files and the <filename>*_docs.xml</filename> file,
described in the <link linkend="sec-wrapping-documentation">Documentation</link> section.
</para>
<sect2 id="generating-defs-methods">
<title>Generar los .defs de métodos</title>
<para lang="en">This <filename>.defs</filename> file describes objects and their functions.
It is generated by the <command>h2def.py</command> script which you can find in
glibmm's <filename>tools/defs_gen</filename> directory. For instance,
<programlisting lang="en">
$ ./h2def.py /usr/include/gtk-3.0/gtk/*.h > gtk_methods.defs
</programlisting>
</para>
</sect2>
<sect2 id="generating-defs-enums">
<title>Generar los .defs de enumeraciones</title>
<para lang="en">This <filename>.defs</filename> file describes enum types and their possible
values. It is generated by the <filename>enum.pl</filename> script which you can
find in glibmm's <filename>tools</filename> directory. For instance,
<programlisting lang="en">
$ ./enum.pl /usr/include/gtk-3.0/gtk/*.h > gtk_enums.defs
</programlisting>
</para>
</sect2>
<sect2 id="generating-defs-signals-properties">
<title>Generar los .defs de señales y propiedades</title>
<para lang="en">This <filename>.defs</filename> file describes signals and properties. It is
generated by the special <filename>generate_extra_defs</filename> utility that is in every
wrapping project, such as <filename>gtkmm/tools/extra_defs_gen/</filename>.
For instance
<programlisting lang="en">
$ cd tools/extra_defs_gen
$ ./generate_extra_defs > gtk_signals.defs
</programlisting>
</para>
<para>Debe editar el código fuente de su herramienta <filename>generate_extra_defs</filename> para generar los <filename>.defs</filename> para los tipos GObject de C que desea envolver. En el árbol de fuentes esqueleto, el archivo de fuentes se llama <filename>codegen/extradefs/generate_extra_defs_skeleton.cc</filename>. Si no lo ha hecho todavía, debe renombrar el archivo, con el nombre de base de su enlace nuevo sustituyendo a la marca de posición <varname>skeleton</varname>. El archivo <filename>codegen/Makefile.am</filename> también debe mencionar el nombre del archivo de fuentes nuevo.</para>
<para lang="en">Then edit the <filename>.cc</filename> file to specify the correct types.
For instance, your <function>main()</function> function might look like this:
<programlisting lang="en">
#include <libsomething.h>
int main(int, char**)
{
something_init();
std::cout << get_defs(SOME_TYPE_WIDGET)
<< get_defs(SOME_TYPE_STUFF);
return 0;
}
</programlisting>
</para>
</sect2>
<sect2 id="writing-defs-vfuncs">
<title>Escribir los .defs de las «vfuncs»</title>
<para lang="en">
This <filename>.defs</filename> file describes virtual functions (vfuncs).
It must be written by hand. There is the skeleton file
<filename>skeleton/src/skeleton_vfunc.defs</filename> to start from. You can also look
at <application>gtkmm</application>'s <filename>gtk/src/gtk_vfuncs.defs</filename> file.
</para>
</sect2>
</sect1>
<sect1 id="sec-wrapping-hg-files">
<title>Los archivos .hg y .ccg</title>
<para>Los archivos de fuentes .hg y .ccg se parecen mucho a los archivos de fuentes .h y .cc de C++, pero contienen macros adicionales, como <function>_CLASS_GOBJECT()</function> y <function>_WRAP_METHOD()</function>, desde las que <command>gmmproc</command> genera código fuente de C++ apropiado, generalmente en la misma posición en la cabecera. Cualquier código fuente adicional de C++ se copiará tal cual en el archivo .h o .cc correspondiente.</para>
<para lang="en">A .hg file will typically include some headers
and then declare a class, using some macros to add API or behaviour to
this class. For instance, <application>gtkmm</application>'s <filename>button.hg</filename> looks
roughly like this:
<programlisting lang="en">
#include <gtkmm/bin.h>
#include <gtkmm/activatable.h>
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/bin_p.h)
namespace Gtk
{
class Button
: public Bin,
public Activatable
{
_CLASS_GTKOBJECT(Button,GtkButton,GTK_BUTTON,Gtk::Bin,GtkBin)
_IMPLEMENTS_INTERFACE(Activatable)
public:
_CTOR_DEFAULT
explicit Button(const Glib::ustring& label, bool mnemonic = false);
_WRAP_METHOD(void set_label(const Glib::ustring& label), gtk_button_set_label)
...
_WRAP_SIGNAL(void clicked(), "clicked")
...
_WRAP_PROPERTY("label", Glib::ustring)
};
} // namespace Gtk
</programlisting>
</para>
<para lang="en">The macros in this example do the following:
<variablelist>
<varlistentry>
<term lang="en"><function>_DEFS()</function></term>
<listitem><para lang="en">Specifies the destination directory for generated sources, and the name of the main .defs file that <command>gmmproc</command> should parse.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><function>_PINCLUDE()</function></term>
<listitem><para lang="en">Tells <command>gmmproc</command> to include a header in the generated private/button_p.h file.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><function>_CLASS_GTKOBJECT()</function></term>
<listitem><para lang="en">Tells <command>gmmproc</command> to add some typedefs, constructors, and standard methods to this class, as appropriate when wrapping a widget.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><function>_IMPLEMENTS_INTERFACE()</function></term>
<listitem><para lang="en">Tells <command>gmmproc</command> to add initialization code for the interface.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><function>_CTOR_DEFAULT</function></term>
<listitem><para lang="en">Add a default constructor.</para></listitem>
</varlistentry>
<varlistentry>
<term lang="en"><function>_WRAP_METHOD()</function>,
<function>_WRAP_SIGNAL()</function>, and
<function>_WRAP_PROPERTY()</function></term>
<listitem><para lang="en">Add methods to wrap parts of the C API.</para></listitem>
</varlistentry>
</variablelist>
</para>
<para lang="en">The .h and .cc files will be generated from the .hg and .ccg files by
processing them with <command>gmmproc</command> like so, though this happens
automatically when using the above build structure:
<programlisting lang="en">
$ cd gtk/src
$ /usr/lib/glibmm-2.4/proc/gmmproc -I ../../tools/m4 --defs . button . ./../gtkmm
</programlisting>
</para>
<para>Tenga en cuenta que se le proporcionó a <command>gmmproc</command> la ruta de los archivos de conversión .m4, la ruta del archivo .defs, el nombre de un archivo .hg, la carpeta de las fuentes, y la carpeta de destino.</para>
<para>Debe evitar incluir la cabecera de C desde su cabecera de C++, para evitar contaminar el espacio de nombres global, y para evitar exportar API pública innecesaria. Pero necesitará incluir las cabeceras de C desde su archivo .ccg.</para>
<para>Las macros se explican en mayor detalle en las secciones siguientes.</para>
<sect2 id="gmmproc-m4-conversions">
<title>Conversiones m4</title>
<para lang="en">The macros that you use in the .hg and .ccg files often need to know how
to convert a C++ type to a C type, or vice-versa. gmmproc takes this information
from an .m4 file in your <literal>tools/m4/</literal> directory. This allows it
to call a C function in the implementation of your C++ method, passing the
appropriate parameters to that C functon. For instance, this
tells gmmproc how to convert a GtkTreeView pointer to a Gtk::TreeView pointer:
<programlisting lang="en">
_CONVERSION(`GtkTreeView*',`TreeView*',`Glib::wrap($3)')
</programlisting>
</para>
<para><literal>$3</literal> se reemplazará por el nombre del parámetro cuando gmmproc use esta conversión.</para>
<para lang="en">
Some extra macros make this easier and consistent. Look in gtkmm's .m4 files
for examples. For instance:
<programlisting lang="en">
_CONVERSION(`PrintSettings&',`GtkPrintSettings*',__FR2P)
_CONVERSION(`const PrintSettings&',`GtkPrintSettings*',__FCR2P)
_CONVERSION(`const Glib::RefPtr<Printer>&',`GtkPrinter*',__CONVERT_REFPTR_TO_P($3))
</programlisting>
</para>
</sect2>
<sect2 id="gmmproc-m4-initializations">
<title>Inicializaciones de m4</title>
<para>Cuando se envuelven métodos, a menudo es deseable almacenar el valor que devuelve una función de C en lo que se conoce como parámetro de salida. En este caso, el método de C++ devuelve <type>void</type> pero se incluye en su lista de argumentos un parámetro de salida en el que se almacena el valor de la función de C. gmmproc permite esta funcionalidad, pero deben incluirse macros de inicialización apropiadas para decirle a gmmproc cómo inicializar el parámetro de C++ desde el valor de devolución de la función de C.</para>
<para lang="en">
For example, if there was a C function that returned a
<type>GtkWidget*</type> and for some reason, instead of having the C++ method
also return the widget, it was desirable to have the C++ method place the
widget in a specified output parameter, an initialization macro such as the
following would be necessary:
<programlisting lang="en">
_INITIALIZATION(`Gtk::Widget&',`GtkWidget*',`$3 = Glib::wrap($4)')
</programlisting>
</para>
<para><literal>$3</literal> se reemplazará por el nombre del parámetro de salida del método de C++ y <literal>$4</literal> se reemplazará por el valor de retorno de la función de C cuando gmmproc use esta inicialización. Por conveniencia, <literal>$1</literal> también se reemplazará por el tipo de C++ sin el «et» (&) y <literal>$2</literal> se reemplazará por el tipo de C.</para>
</sect2>
<sect2 id="gmmproc-class-macros">
<title>Macros de clases</title>
<para>Las macros de clases declaran la clase en sí y su relación con el tipo de C subyacente. Generan algunos constructores internos, el miembro <varname>gobject_</varname>, «typedefs», los <function>gobj()</function> de acceso, registro de tipos, y el método <function>Glib::wrap()</function>, entre otras cosas.</para>
<para>Otras macros, como <function>_WRAP_METHOD()</function> y <function>_WRAP_SIGNAL()</function> sólo pueden usarse después de una llamada a una macro <function>_CLASS_*</function>.</para>
<sect3 id="gmmproc-class-gobject">
<title>_CLASS_GOBJECT</title>
<para>Esta macro declara un envoltorio de un tipo que deriva de <classname>GObject</classname>, pero cuyo envoltorio no deriva de <classname>Gtk::Object</classname>.</para>
<para lang="en"><function>_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function></para>
<para lang="en">For instance, from <filename>accelgroup.hg</filename>:
<programlisting lang="en">
_CLASS_GOBJECT(AccelGroup, GtkAccelGroup, GTK_ACCEL_GROUP, Glib::Object, GObject)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-class-gtkobject">
<title>_CLASS_GTKOBJECT</title>
<para>Esta macro declara un envoltorio para un tipo cuyo envoltorio deriva de <classname>Gtk::Object</classname>, como un widget o un diálogo.</para>
<para lang="en"><function>_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Bin, GtkBin)
</programlisting>
</para>
<para>Típicamente usará esta macro cuando la clase ya derive de Gtk::Object. Por ejemplo, la usará cuando envuelva un widget de GTK+, porque Gtk::Widget deriva de Gtk::Object.</para>
<para>También podrá derivar clases que no sean widgets de Gtk::Object para que puedan usarse sin <classname>Glib::RefPtr</classname>. Por ejemplo, podrían instanciarse con <function>Gtk::manage()</function> o en la pila como una variable miembro. Esto es cómodo, pero sólo debe usarlo cuando esté seguro de que no se necesita conteo de referencias real. Se considera de utilidad para los widgets.</para>
</sect3>
<sect3 id="gmmproc-class-boxedtype">
<title>_CLASS_BOXEDTYPE</title>
<para>Esta macro declara un envoltorio para una estructura que no es <classname>GObject</classname>, registrada con <function>g_boxed_type_register_static()</function>.</para>
<para lang="en"><function>_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )</function></para>
<para lang="en">For instance, from <classname>Gdk::RGBA</classname>:
<programlisting lang="en">
_CLASS_BOXEDTYPE(RGBA, GdkRGBA, NONE, gdk_rgba_copy, gdk_rgba_free)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-class-boxedtype-static">
<title>_CLASS_BOXEDTYPE_STATIC</title>
<para>Esta macro declara un envoltorio para una estructura asignable simple como <classname>GdkRectangle</classname>. Es similar a <function>_CLASS_BOXEDTYPE</function>, pero la estructura de C no se asigna dinámicamente.</para>
<para lang="en"><function>_CLASS_BOXEDTYPE_STATIC( C++ class, C class )</function></para>
<para lang="en">For instance, for <classname>Gdk::Rectangle</classname>:
<programlisting lang="en">
_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-class-opaque-copyable">
<title>_CLASS_OPAQUE_COPYABLE</title>
<para>Esta macro declara un envoltorio para una estructura opaca que tiene funciones «copy» y «free». Las funciones «new», «copy» y «free» se usarán para instanciar el constructor predeterminado, copiar el constructor y el destructor.</para>
<para lang="en"><function>_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )</function></para>
<para lang="en">For instance, from <classname>Glib::Checksum</classname>:
<programlisting lang="en">
_CLASS_OPAQUE_COPYABLE(Checksum, GChecksum, NONE, g_checksum_copy, g_checksum_free)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-class-opaque-refcounted">
<title>_CLASS_OPAQUE_REFCOUNTED</title>
<para>Esta macro declara un envoltorio para una estructura opaca con conteo de referencias. El envoltorio de C++ no puede instanciarse directamente y sólo lo puede usar <classname>Glib::RefPtr</classname>.</para>
<para lang="en"><function>_CLASS_OPAQUE_REFCOUNTED( C++ class, C class, new function, ref function, unref function )</function></para>
<para lang="en">For instance, for <classname>Pango::Coverage</classname>:
<programlisting lang="en">
_CLASS_OPAQUE_REFCOUNTED(Coverage, PangoCoverage, pango_coverage_new, pango_coverage_ref, pango_coverage_unref)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-class-generic">
<title>_CLASS_GENERIC</title>
<para>Esta macro puede usarse para envolver estructuras que no se ajustan a ninguna categoría especializada.</para>
<para lang="en"><function>_CLASS_GENERIC( C++ class, C class )</function></para>
<para lang="en">For instance, for <classname>Pango::AttrIter</classname>:
<programlisting lang="en">
_CLASS_GENERIC(AttrIter, PangoAttrIterator)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-class-interface">
<title>_CLASS_INTERFACE</title>
<para>Esta macro declara un envoltorio para un tipo que deriva de <classname>GTypeInterface</classname>.</para>
<para lang="en"><function>_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )</function></para>
<para lang="en">
For instance, from <filename>celleditable.hg</filename>:
<programlisting lang="en">
_CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)
</programlisting>
</para>
<para lang="en">Two extra parameters are optional, for the case that the interface derives from another interface,
which should be the case when the GInterface has another GInterface as a prerequisite.
For instance, from <filename>loadableicon.hg</filename>:
<programlisting lang="en">
_CLASS_INTERFACE(LoadableIcon, GLoadableIcon, G_LOADABLE_ICON, GLoadableIconIface, Icon, GIcon)
</programlisting>
</para>
</sect3>
</sect2>
<sect2 id="gmmproc-constructor-macros">
<title>Macros de constructores</title>
<para>Las macros <function>_CTOR_DEFAULT()</function> y <function>_WRAP_CTOR()</function> añaden constructores, envolviendo las funciones de C <function>*_new()</function> especificadas. Estas macros asumen que el objeto de C tiene propiedades con los mismos nombres que los parámetros de función, como es usual, para que pueda proporcionar los parámetros directamente a una llamada de <function>g_object_new()</function>. Estos constructores nunca llaman realmente a funciones de C <function>*_new()</function>, porque gtkmm debe en realidad instanciar «GTypes» derivados, y las funciones <function>*_new()</function> de C sólo están pensadas como funciones cómodas para programadores de C.</para>
<para lang="en">When using <function>_CLASS_GOBJECT()</function>, the constructors should
be protected (rather than public) and each constructor should have a
corresponding <function>_WRAP_CREATE()</function> in the public section.
This prevents the class from being instantiated without using a
<classname>RefPtr</classname>. For instance:
<programlisting lang="en">
class TextMark : public Glib::Object
{
_CLASS_GOBJECT(TextMark, GtkTextMark, GTK_TEXT_MARK, Glib::Object, GObject)
protected:
_WRAP_CTOR(TextMark(const Glib::ustring& name, bool left_gravity = true), gtk_text_mark_new)
public:
_WRAP_CREATE(const Glib::ustring& name, bool left_gravity = true)
</programlisting>
</para>
<sect3 id="gmmproc-ctor-default">
<title>_CTOR_DEFAULT</title>
<para>Esta macro crea un constructor predeterminado sin argumentos.</para>
</sect3>
<sect3 id="gmmproc-wrap-ctor">
<title>_WRAP_CTOR</title>
<para>Esta macro crea un constructor con argumentos, equivalente a una función de C <function>*_new()</function>. En realidad no llamará a la función <function>*_new()</function>, sino que simplemente creará un constructor equivalente con los mismos tipos de argumentos. Toma una firma de constructor de C++ y un nombre de función de C.</para>
<para lang="en">It also takes an optional extra argument:
<variablelist>
<varlistentry>
<term lang="en">errthrow</term>
<listitem>
<para lang="en">This tells gmmproc that the C <function>*_new()</function> has
a final GError** parameter which should be ignored.</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect3>
<sect3 id="gmmproc-ctor-manual">
<title>Escribir constructores a mano</title>
<para lang="en">When a constructor must be partly hand written because, for instance, the
<function>*_new()</function> C function's parameters do not correspond
directly to object properties, or because the <function>*_new()</function> C
function does more than call <function>g_object_new()</function>, the
<function>_CONSTRUCT()</function> macro may be used in the
.ccg file to save some work. The <function>_CONSTRUCT</function> macro takes
a series of property names and values. For instance, from
<filename>button.ccg</filename>:
<programlisting lang="en">
Button::Button(const Glib::ustring& label, bool mnemonic)
:
_CONSTRUCT("label", label.c_str(), "use_underline", gboolean(mnemonic))
{}
</programlisting>
</para>
</sect3>
</sect2>
<sect2 id="gmmproc-method-macros">
<title>Macros de métodos</title>
<sect3 id="gmmproc-wrap-method">
<title>_WRAP_METHOD</title>
<para>Esta macro genera el método de C++ para envolver una función de C.</para>
<para lang="en"><function>_WRAP_METHOD( C++ method signature, C function name)</function></para>
<para lang="en">For instance, from <filename>entry.hg</filename>:
<programlisting lang="en">
_WRAP_METHOD(void set_text(const Glib::ustring& text), gtk_entry_set_text)
</programlisting>
</para>
<para>La función de C (por ejemplo, <function>gtk_entry_set_text</function>) se describe en mayor detalle en el archivo .defs, y los archivos <filename>convert*.m4</filename> contienen la conversión necesaria del tipo de parámetro de C++ al tipo de C. Esta macro también genera comentarios de documentación de Doxygen basados en los archivos <filename>*_docs.xml</filename> y <filename>*_docs_override.xml</filename>.</para>
<para lang="en">There are some optional extra arguments:
<variablelist>
<varlistentry>
<term lang="en">refreturn</term>
<listitem>
<para lang="en">Do an extra <function>reference()</function> on the return value,
in case the C function does not provide a reference.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">errthrow</term>
<listitem>
<para lang="en">Use the last GError** parameter of the C function to
throw an exception.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">deprecated</term>
<listitem>
<para lang="en">Puts the generated code in #ifdef blocks. Text about the
deprecation can be specified as an optional
parameter.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">constversion</term>
<listitem>
<para lang="en">Just call the non-const version of the same function,
instead of generating almost duplicate code.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">ifdef</term>
<listitem>
<para lang="en">Puts the generated code in #ifdef blocks.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">slot_name</term>
<listitem>
<para lang="en">Specifies the name of the slot parameter of the method, if it
has one. This enables <command>gmmproc</command> to generate code
to copy the slot and pass the copy on to the C function in its
final <literal>gpointer user_data</literal> parameter. The
<literal>slot_callback</literal> option must also be used to
specify the name of the glue callback function to also pass on to
the C function.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">slot_callback</term>
<listitem>
<para lang="en">Used in conjunction with the <literal>slot_name</literal>
option to specify the name of the glue callback function that
handles extracting the slot and then calling it. The address of
this callback is also passed on to the C function that the method
wraps.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">no_slot_copy</term>
<listitem>
<para lang="en">Tells <command>gmmproc</command> not to pass a copy of the slot
to the C function, if the method has one. Instead the slot itself
is passed. The slot parameter name and the glue callback function
must have been specified with the <literal>slot_name</literal> and
<literal>slot_callbback</literal> options respectively.</para>
</listitem>
</varlistentry>
</variablelist>
</para>
<para lang="en">Selecting which C++ types should be used is also important when wrapping
C API. Though it's usually obvious what C++ types should be used in the C++
method, here are some hints:
<itemizedlist>
<listitem><para lang="en">Objects used via <classname>RefPtr</classname>: Pass the
<classname>RefPtr</classname> as a const reference. For instance,
<code>const Glib::RefPtr<Gtk::FileFilter>&
filter</code>.</para></listitem>
<listitem><para lang="en">Const Objects used via <classname>RefPtr</classname>: If the
object should not be changed by the function, then make sure that
the object is const, even if the <classname>RefPtr</classname> is
already const. For instance, <code>const Glib::RefPtr<const
Gtk::FileFilter>& filter</code>.</para></listitem>
<listitem><para lang="en">Wrapping <classname>GList*</classname> and
<classname>GSList*</classname> parameters: First, you need to discover
what objects are contained in the list's data field for each item,
usually by reading the documentation for the C function. The list can
then be wrapped by a <classname>std::vector</classname> type.
For instance, <code>std::vector<
Glib::RefPtr<Gdk::Pixbuf> ></code>.
You may need to define a Traits type to specify how the C
and C++ types should be converted.</para></listitem>
<listitem><para lang="en">Wrapping <classname>GList*</classname> and
<classname>GSList*</classname> return types: You must discover whether
the caller should free the list and whether it should release the items
in the list, again by reading the documentation of the C function. With
this information you can choose the ownership (none, shallow or deep)
for the m4 conversion rule, which you should probably put directly into
the .hg file because the ownership depends on the
function rather than the type. For instance:
<programlisting lang="en">#m4 _CONVERSION(`GSList*',`std::vector<Widget*>',`Glib::SListHandler<Widget*>::slist_to_vector($3, Glib::OWNERSHIP_SHALLOW)')</programlisting></para></listitem>
</itemizedlist>
</para>
</sect3>
<sect3 id="gmmproc-wrap-method-docs-only">
<title>_WRAP_METHOD_DOCS_ONLY</title>
<para>Esta macro es similar a <function>_WRAP_METHOD()</function>, pero sólo genera la documentación de un método de C++ que envuelve una función de C. Úsela cuando debe escribir el método a mano, pero quiere usar la documentación que se crearía si el método se generara.</para>
<para lang="en"><function>_WRAP_METHOD_DOCS_ONLY(C function name)</function></para>
<para lang="en">For instance, from <filename>container.hg</filename>:
<programlisting lang="en">
_WRAP_METHOD_DOCS_ONLY(gtk_container_remove)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-ignore">
<title>_IGNORE / _IGNORE_SIGNAL</title>
<para><command>gmmproc</command> le advertirá en stdout de funciones y señales que haya olvidado envolver, ayudándole a asegurarse que está envolviendo la API completa. Pero si no quiere envolver algunas funciones o señales, o si elige escribir a mano algunos métodos entonces puede usar las macros _IGNORE() o _IGNORE_SIGNAL() para hacer que <command>gmmproc</command> deje de quejarse.</para>
<para lang="en"><function>_IGNORE(C function name 1, C function name2, etc)</function></para>
<para lang="en"><function>_IGNORE_SIGNAL(C signal name 1, C signal name2, etc)</function></para>
<para lang="en">For instance, from <filename>buttonbox.hg</filename>:
<programlisting lang="en">
_IGNORE(gtk_button_box_set_spacing, gtk_button_box_get_spacing)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-wrap-signal">
<title>_WRAP_SIGNAL</title>
<para>Esta macro genera la señal de C++ con el estilo de libsigc++ para envolver una señal GObject de C. En realidad genera un método de acceso público, como <function>signal_clicked()</function>, que devuelve un objeto sustituto. <function>gmmproc</function> usa el archivo .defs para descubrir los tipos de parámetro de C y los archivos de conversión .m4 para descubrir conversiones de tipo adecuadas.</para>
<para lang="en"><function>_WRAP_SIGNAL( C++ signal handler signature, C signal name)</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_WRAP_SIGNAL(void clicked(),"clicked")
</programlisting>
</para>
<para>Las señales generalmente tienen punteros de funciones en la estructura de GTK, con un valor de enum correspondiente y un <function>g_signal_new()</function> en el archivo .c.</para>
<para lang="en">There are some optional extra arguments:
<variablelist>
<varlistentry>
<term lang="en">no_default_handler</term>
<listitem>
<para lang="en">Do not generate an <function>on_something()</function> virtual
method to allow easy overriding of the default signal handler.
Use this when adding a signal with a default signal handler
would break the ABI by increasing the size of the class's
virtual function table.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">custom_default_handler</term>
<listitem>
<para lang="en">Generate a declaration of the <function>on_something()</function>
virtual method in the <filename>.h</filename> file, but do not
generate a definition in the <filename>.cc</filename> file.
Use this when you must generate the definition by hand.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">custom_c_callback</term>
<listitem>
<para lang="en">Do not generate a C callback function for the signal.
Use this when you must generate the callback function by hand.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">refreturn</term>
<listitem>
<para lang="en">Do an extra <function>reference()</function> on the return value
of the <function>on_something()</function> virtual method, in
case the C function does not provide a reference.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">ifdef</term>
<listitem>
<para lang="en">Puts the generated code in #ifdef blocks.</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect3>
<sect3 id="gmmproc-wrap-property">
<title>_WRAP_PROPERTY</title>
<para>Esta macro genera el método de C++ que envuelve una propiedad GObject de C. Debe especificar el nombre de la propiedad y el tipo de C++ que quiere para la propiedad. <command>gmmproc</command> usa el archivo .defs para descubrir el tipo de C y el archivo de conversión .m4 para descubrir conversiones de tipo apropiadas.</para>
<para lang="en"><function>_WRAP_PROPERTY(C property name, C++ type)</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_WRAP_PROPERTY("label", Glib::ustring)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-wrap-vfunc">
<title>_WRAP_VFUNC</title>
<para>Esta macro genera el método de C++ que envuelve una función virtual de C.</para>
<para lang="en"><function>_WRAP_VFUNC( C++ method signature, C function name)</function></para>
<para lang="en">For instance, from <filename>widget.hg</filename>:
<programlisting lang="en">
_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)
</programlisting>
</para>
<para>La función de C (por ejemplo, <function>get_request_mode</function>) se describe en mayor detalle en el archivo <filename>*_vfuncs.defs</filename>, y los archivos <filename>convert*.m4</filename> contienen las conversiones necesarias del tipo de parámetro de C++ al tipo de parámetro de C.</para>
<para lang="en">There are some optional extra arguments:
<variablelist>
<varlistentry>
<term lang="en">refreturn</term>
<listitem>
<para lang="en">Do an extra <function>reference()</function> on the return value
of the <function>something_vfunc()</function> function,
in case the virtual C function does not provide a reference.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">refreturn_ctype</term>
<listitem>
<para lang="en">Do an extra <function>reference()</function> on the return value
of an overridden <function>something_vfunc()</function> function
in the C callback function, in case the calling C function
expects it to provide a reference.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">errthrow</term>
<listitem>
<para lang="en">Use the last GError** parameter of the C virtual function (if
there is one) to throw an exception.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">custom_vfunc</term>
<listitem>
<para lang="en">Do not generate a definition of the vfunc in the
<filename>.cc</filename> file. Use this when you must generate
the vfunc by hand.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">custom_vfunc_callback</term>
<listitem>
<para lang="en">Do not generate a C callback function for the vfunc.
Use this when you must generate the callback function by hand.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">ifdef</term>
<listitem>
<para lang="en">Puts the generated code in #ifdef blocks.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">slot_name</term>
<listitem>
<para lang="en">Specifies the name of the slot parameter of the method, if it
has one. This enables <command>gmmproc</command> to generate code
to copy the slot and pass the copy on to the C function in its
final <literal>gpointer user_data</literal> parameter. The
<literal>slot_callback</literal> option must also be used to
specify the name of the glue callback function to also pass on to
the C function.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">slot_callback</term>
<listitem>
<para lang="en">Used in conjunction with the <literal>slot_name</literal>
option to specify the name of the glue callback function that
handles extracting the slot and then calling it. The address of
this callback is also passed on to the C function that the method
wraps.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en">no_slot_copy</term>
<listitem>
<para lang="en">Tells <command>gmmproc</command> not to pass a copy of the slot
to the C function, if the method has one. Instead the slot itself
is passed. The slot parameter name and the glue callback function
must have been specified with the <literal>slot_name</literal> and
<literal>slot_callbback</literal> options respectively.</para>
</listitem>
</varlistentry>
</variablelist>
</para>
<para>Una regla para la cual puede haber excepciones: si la función virtual de C devuelve un puntero a un objeto derivado de <classname>GObject</classname>, es decir un objeto cuyas referencias se cuentan, entonces la función virtual de C++ deberá devolver un objeto <classname>Glib::RefPtr<></classname>. Se requiere uno de los argumentos adicionales <parameter>refreturn</parameter> o <parameter>refreturn_ctype</parameter>.</para>
</sect3>
</sect2>
<sect2 id="gmmproc-other-macros">
<title>Otras macros</title>
<sect3 id="gmmproc-implements-interface">
<title>_IMPLEMENTS_INTERFACE</title>
<para>Esta macro genera código de inicialización para la interfaz.</para>
<para lang="en"><function>_IMPLEMENTS_INTERFACE(C++ interface name)</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_IMPLEMENTS_INTERFACE(Activatable)
</programlisting>
</para>
<para lang="en">There is one optional extra argument:
<variablelist>
<varlistentry>
<term lang="en">ifdef</term>
<listitem>
<para lang="en">Puts the generated code in #ifdef blocks.</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect3>
<sect3 id="gmmproc-wrap-enum">
<title>_WRAP_ENUM</title>
<para>Esta macro genera una enum de C++ para envolver una enum de C. Debe especificar el nombre de C++ que quiere y el nombre de la enum de C subyacente.</para>
<para lang="en">For instance, from <filename>enums.hg</filename>:
<programlisting lang="en">
_WRAP_ENUM(WindowType, GtkWindowType)
</programlisting>
</para>
<para>Si la enum no es un <classname>GType</classname>, debe pasar un tercer parámetro «NO_GTYPE». Este es el caso cuando no hay una función <function>*_get_type()</function> para la enum de C, pero tenga cuidado: no sólo necesita incluir una cabecera adicional para esa función, también debe enviar un informe de error de la API de C porque todas las enums deben registrarse como GTypes.</para>
<para lang="en">For example, from <filename>icontheme.hg</filename>:
<programlisting lang="en">
_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-wrap-enum-docs-only">
<title>_WRAP_ENUM_DOCS_ONLY</title>
<para lang="en">This macro just generates a Doxygen documentationn block for the enum.
This is useful for enums that can't be wrapped with
<function>_WRAP_ENUM()</function> because they are complexly defined (maybe
using C macros) but including the generated enum documentation is still
desired. It is used with the same syntax as
<function>_WRAP_ENUM()</function> and also process the same options (though
NO_GTYPE is just ignored because it makes no difference when just generating
the enum's documentation).
</para>
</sect3>
<sect3 id="gmmproc-wrap-gerror">
<title>_WRAP_GERROR</title>
<para>Esta macro genera una clase de excepción de C++, derivada de Glib::Error, con una enum Code y un método code(). Debe especificar el nombre de C++ que quiere, el nombre de la enum de C correspondiente, y el prefijo de los valores de la enum de C.</para>
<para>Los métodos generados desde _WRAP_METHOD() podrán entonces lanzar esta excepción con la opción «errthrow».</para>
<para lang="en">For instance, from <filename>pixbuf.hg</filename>:
<programlisting lang="en">
_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-member-set-get">
<title>_MEMBER_GET / _MEMBER_SET</title>
<para>Use estas macros si está envolviendo una estructura simple o un tipo en caja que proporciona acceso directo a sus miembros de datos, para crear métodos de acceso y modificación para estos.</para>
<para lang="en"><function>_MEMBER_GET(C++ name, C name, C++ type, C type)</function></para>
<para lang="en"><function>_MEMBER_SET(C++ name, C name, C++ type, C type)</function></para>
<para lang="en">
For example, in <filename>rectangle.hg</filename>:
<programlisting lang="en">_MEMBER_GET(x, x, int, int)</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-member-get-set-ptr">
<title>_MEMBER_GET_PTR / _MEMBER_SET_PTR</title>
<para>Use estas macros para proporcionar métodos de acceso y modificación para un miembro de datos que es de tipo puntero automáticamente. Para la función de acceso, creará dos métodos, uno constante y otro no constante.</para>
<para lang="en"><function>_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)</function></para>
<para lang="en"><function>_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)</function></para>
<para lang="en">For example, for <classname>Pango::Analysis</classname> in <filename>item.hg</filename>:
<programlisting lang="en">
// _MEMBER_GET_PTR(engine_lang, lang_engine, EngineLang*, PangoEngineLang*)
// It's just a comment. It's difficult to find a real-world example.
</programlisting>
</para>
</sect3>
<sect3 id="gmmproc-member-get-set-gobject">
<title>_MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT</title>
<para>Use estas macros para proporcionar métodos de acceso y modificación para un miembro de datos que es de tipo <classname>GObject</classname> que debe referenciarse antes de devolverse.</para>
<para lang="en"><function>_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)</function></para>
<para lang="en"><function>_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)</function></para>
<para lang="en">For example, in Pangomm, <filename>layoutline.hg</filename>:
<programlisting lang="en">
_MEMBER_GET_GOBJECT(layout, layout, Pango::Layout, PangoLayout*)
</programlisting>
</para>
</sect3>
</sect2>
<sect2 id="gmmproc-parameter-processing">
<title>Procesado de parámetros de gmmproc</title>
<para lang="en"><command>gmmproc</command> allows processing the parameters in a method
signature for the macros that process method signatures (like
<function>_WRAP_METHOD()</function>, <function>_WRAP_CTOR()</function> and
<function>_WRAP_CREATE()</function>) in a variety of ways:
</para>
<sect3 id="gmmproc-parameter-reordering">
<title>Reordenación de parámetros</title>
<para lang="en">
For all the macros that process method signatures, it is possible to
specify a different order for the C++ parameters than the existing order
in the C function, virtual function or signal. For example, say that the
following C function were being wrapped as a C++ method for the
<classname>Gtk::Widget</classname> class:
<programlisting lang="en">
void gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
GdkEventMask events);
</programlisting>
However, changing the order of the C++ method's two parameters is
necessary. Something like the following would wrap the function as a C++
method with a different order for the two parameters:
<programlisting lang="en">
_WRAP_METHOD(void set_device_events(Gdk::EventMask events{events},
const Glib::RefPtr<const Gdk::Device>& device{device}),
gtk_widget_set_device_events)
</programlisting>
The <literal>{c_param_name}</literal> following the method parameter
names tells <command>gmmproc</command> to map the C++ parameter to the
specified C parameter within the <literal>{}</literal>. Since the C++
parameter names correspond to the C ones, the above could be re-written
as:
<programlisting lang="en">
_WRAP_METHOD(void set_device_events(Gdk::EventMask events{.}, const
Glib::RefPtr<const Gdk::Device>& device{.}),
gtk_widget_set_device_events)
</programlisting>
</para>
<warning>
<para lang="en">
Please note that when reordering parameters for a
<function>_WRAP_SIGNAL()</function> method signature, the C parameter
names would always be <literal>p0</literal>, <literal>p1</literal>,
etc. because the <filename>generate_extra_defs</filename> utility uses those
parameter names no matter what the C API's parameter names may be.
It's how the utility is written presently.
</para>
</warning>
</sect3>
<sect3 id="gmmproc-optional-parameter-processing">
<title>Procesado de parámetros opcionales</title>
<para lang="en">
For all macros processing method signatures except
<function>_WRAP_SIGNAL()</function> and
<function>_WRAP_VFUNC()</function> it is also possible to make the
parameters optional so that extra C++ methods are generated without the
specified optional parameter. For example, say that the following
<function>*_new()</function> function were being wrapped as a constructor
in the <classname>Gtk::ToolButton</classname> class:
<programlisting lang="en">
GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar*
label);
</programlisting>
Also, say that the C API allowed NULL for the function's
<parameter>label</parameter> parameter so that that parameter is optional.
It would be possible to have <command>gmmproc</command> generate the
original constructor (with all the parameters) along with an additional
constructor without that optional parameter by appending a
<literal>{?}</literal> to the parameter name like so:
<programlisting lang="en">
_WRAP_CTOR(ToolButton(Widget& icon_widget, const Glib::ustring&
label{?}), gtk_tool_button_new)
</programlisting>
In this case, two constructors would be generated: One with the optional
parameter and one without it.
</para>
</sect3>
<sect3 id="gmmproc-output-parameter-processing">
<title>Procesado de parámetros de salida</title>
<para lang="en">
With <function>_WRAP_METHOD()</function> it is also possible for the
return of the wrapped C function (if it has one) to be placed in an
output parameter of the C++ method instead of having the C++ method also
return a value like the C function does. To do that, simply include the
output parameter in the C++ method parameter list appending a
<literal>{OUT}</literal> to the output parameter name. For example, if
<function>gtk_widget_get_request_mode()</function> is declared as the
following:
<programlisting lang="en">
GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);
</programlisting>
And having the C++ method set an output parameter is desired instead of
returning a <type>SizeRequestMode</type>, something like the following
could be used:
<programlisting lang="en">
_WRAP_METHOD(void get_request_mode(SizeRequestMode& mode{OUT})
const, gtk_widget_get_request_mode)
</programlisting>
The <literal>{OUT}</literal> appended to the name of the
<parameter>mode</parameter> output parameter tells
<command>gmmproc</command> to place the return of the C function in that
output parameter. In this case, however, a necessary initialization
macro like the following would also have to be specified:
<programlisting lang="en">
_INITIALIZATION(`SizeRequestMode&',`GtkSizeRequestMode',`$3 =
(SizeRequestMode)($4)')
</programlisting>
Which could also be written as:
<programlisting lang="en">
_INITIALIZATION(`SizeRequestMode&',`GtkSizeRequestMode',`$3 =
($1)($4)')
</programlisting>
</para>
<para lang="en">
<function>_WRAP_METHOD()</function> also supports setting C++ output
parameters from C output parameters if the C function being wrapped has
any. Suppose, for example, that we want to wrap the following C function
that returns a value in its C output parameter
<parameter>rect</parameter>:
<programlisting lang="en">
gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);
</programlisting>
To have <command>gmmproc</command> place the value returned in the C++
<parameter>rect</parameter> output parameter, something like the
following <function>_WRAP_METHOD()</function> directive could be used:
<programlisting lang="en">
_WRAP_METHOD(bool get_cell_rect(const TreeModel::Path& path, const
CellRenderer& cell, Gdk::Rectangle& rect{>>}) const,
gtk_icon_view_get_cell_rect)
</programlisting>
The <literal>{>>}</literal> following the <parameter>rect</parameter>
parameter name indicates that the C++ output parameter should be set from
the value returned in the C parameter from the C function.
<command>gmmproc</command> will generate a declaration of a temporary
variable in which to store the value of the C output parameter and a
statement that sets the C++ output parameter from the temporary variable.
In this case it may be necessary to have an
<function>_INITIALIZATION()</function> describing how to set a
<classname>Gdk::Rectangle&</classname> from a
<classname>GdkRectangle*</classname> such as the following:
<programlisting lang="en">
_INITIALIZATION(`Gdk::Rectangle&',`GdkRectangle', `$3 =
Glib::wrap(&($4))')
</programlisting>
</para>
</sect3>
</sect2>
<sect2 id="gmmproc-basic-types">
<title>Tipos básicos</title>
<para>Algunos de los tipos básicos que se usan en las API de C tienen alternativas mejores en C++. Por ejemplo, no hay necesidad de un tipo <type>gboolean</type> dado que C++ tiene el <type>bool</type>. La siguiente lista muestra algunos tipos comúnmente usados en API de C y en qué los puede convertir en una biblioteca envoltorio de C++</para>
<segmentedlist><title>Tipos básicos equivalentes</title>
<?dbhtml list-presentation="table"?>
<segtitle>Tipo de C</segtitle>
<segtitle>Tipo de C++</segtitle>
<seglistitem><seg lang="en"><type>gboolean</type></seg><seg lang="en"><type>bool</type></seg></seglistitem>
<seglistitem><seg lang="en"><type>gint</type></seg><seg lang="en"><type>int</type></seg></seglistitem>
<seglistitem><seg lang="en"><type>guint</type></seg><seg lang="en"><type>guint</type></seg></seglistitem>
<seglistitem><seg lang="en"><type>gdouble</type></seg><seg lang="en"><type>double</type></seg></seglistitem>
<seglistitem><seg lang="en"><type>gunichar</type></seg><seg lang="en"><type>gunichar</type></seg></seglistitem>
<seglistitem><seg lang="en"><type>gchar*</type></seg><seg lang="en"><classname>Glib::ustring</classname> (or <classname>std::string</classname> for filenames)</seg></seglistitem>
</segmentedlist>
</sect2>
</sect1>
<sect1 id="sec-wrapping-hand-coded-files">
<title>Archivos de código fuente programados a mano</title>
<para>Tal vez quiera incluir archivos de código fuente adicionales que <command>gmmproc</command> no generará desde archivos <filename>.hg</filename> y <filename>.ccg</filename>. Puede simplemente ponerlos en su carpeta <filename>libsomething/libsomethingmm</filename> y mencionarlos en el <filename>Makefile.am</filename> en las variables <varname>files_extra_h</varname> y <varname>files_extra_cc</varname>.</para>
</sect1>
<sect1 id="sec-wrapping-initialization">
<title>Inicialización</title>
<para lang="en">Your library must be initialized before it can be used, to register the
new types that it makes available. Also, the C library that you are wrapping
might have its own initialization function that you should call. You can do
this in an <function>init()</function> function that you can place in
hand-coded <filename>init.h</filename> and <filename>init.cc</filename>
files. This function should initialize your dependencies (such as the C
function, and <application>gtkmm</application>) and call your generated
<function>wrap_init()</function> function. For instance:
<programlisting lang="en">
void init()
{
Gtk::Main::init_gtkmm_internals(); //Sets up the g type system and the Glib::wrap() table.
wrap_init(); //Tells the Glib::wrap() table about the libsomethingmm classes.
}
</programlisting>
</para>
<para><filename>generate_wrap_init.pl</filename> genera la implementación del método <function>wrap_init()</function> en <filename>wrap_init.cc</filename>, pero la declaración en <filename>wrap_init.h</filename> se programa a mano, por lo que necesitará ajustar <filename>wrap_init.h</filename> de manera tal que la función <function>wrap_init()</function> aparezca en el espacio de nombres de C++ correcto.</para>
</sect1>
<sect1 id="sec-wrapping-problems">
<title>Problemas en la API de C.</title>
<para>Es probable que encuentre algunos problemas en la biblioteca que está envolviendo, particularmente si es un proyecto nuevo. Aquí hay algunos problemas comunes, con soluciones.</para>
<sect2 id="wrapping-predeclare-structs">
<title>No se pueden predeclarar estructuras</title>
<para lang="en">By convention, structs are declared in glib/GTK+-style headers like so:
<programlisting lang="en">
typedef struct _ExampleWidget ExampleWidget;
struct _ExampleWidget
{
...
};
</programlisting>
</para>
<para>El «typedef» adicional le permite usar la estructura en una cabecera sin incluir su definición completa, simplemente predeclarándola repitiendo ese «typedef». Esto significa que no tiene que incluir la cabecera de la biblioteca de C en su cabecera de C++, por lo tanto la dejará fuera de su API pública. <command>gmmproc</command> asume que se usó esta técnica, por lo que verá errores de compilación si ese no es el caso.</para>
<para lang="en">
This compiler error might look like this:
<programlisting lang="en">
example-widget.h:56: error: using typedef-name 'ExampleWidget' after 'struct'
../../libexample/libexamplemm/example-widget.h:34: error: 'ExampleWidget' has a previous declaration here
make[4]: *** [example-widget.lo] Error 1
</programlisting>
or this:
<programlisting lang="en">
example-widget.h:60: error: '_ExampleWidget ExampleWidget' redeclared as different kind of symbol
../../libexample/libexamplemm/example-widget.h:34: error: previous declaration of 'typedef struct _ExampleWidget ExampleWidget'
</programlisting>
</para>
<para>Esto es fácil de corregir en la biblioteca de C, así que envíe un parche al mantenedor pertinentes.</para>
</sect2>
<sect2 id="wrapping-no-properties">
<title>Falta de propiedades</title>
<para lang="en">By convention, glib/GTK+-style objects have <function>*_new()</function>
functions, such as <function>example_widget_new()</function> that do nothing
more than call <function>g_object_new()</function> and return the result.
The input parameters are supplied to <function>g_object_new()</function>
along with the names of the properties for which they are values. For
instance,
<programlisting lang="en">
GtkWidget* example_widget_new(int something, const char* thing)
{
return g_object_new (EXAMPLE_TYPE_WIDGET, "something", something, "thing", thing, NULL);
}
</programlisting>
</para>
<para>Esto le permite a los enlaces entre lenguajes implementar sus propios equivalentes (como los constructores de C++), sin usar la función <function>*_new()</function>. Esto a menudo es necesario para poder instanciar realmente un GType derivado, para añadir sus propios ganchos para manejadores de señales y «vfuncs».</para>
<para>Como mínimo, la función <function>_new()</function> no debe usar ninguna API privada (funciones que sólo están en un archivo .c). Incluso cuando no hay funciones, a veces se pueden reimplementar 2 ó 3 líneas de código en una función <function>_new()</function> siempre que esas líneas de código usen una API que esté disponible.</para>
<para lang="en">Another workaround is to add a <function>*_construct()</function> function
that the C++ constructor can call after instantiating its own type. For
instance,
<programlisting lang="en">
GtkWidget* example_widget_new(int something, const char* thing)
{
ExampleWidget* widget;
widget = g_object_new (EXAMPLE_TYPE_WIDGET, NULL);
example_widget_construct(widget, "something", something, "thing", thing);
}
void example_widget_construct(ExampleWidget* widget, int something, const char* thing)
{
//Do stuff that uses private API:
widget->priv->thing = thing;
do_something(something);
}
</programlisting>
</para>
<para>Incorporar propiedades, y asegurar que interactúan con otras propiedades correctamente, es relativamente difícil de corregir en la biblioteca de C, pero es posible, por lo que rellene un informe de error e intente enviar un parche al mantenedor correspondiente.</para>
</sect2>
</sect1>
<sect1 id="sec-wrapping-documentation">
<title>Documentación</title>
<para>En general, los proyectos de gtkmm usan Doxygen, que lee comentarios de C++ con un formato específico y genera documentación HTML. Puede escribir estos comentarios de Doxygen directamente en los archivos de cabecera.</para>
<sect2 id="wrapping-reusing-c-documentation">
<title>Reutilizar la documentación de C</title>
<para>Tal vez quiera reutilizar documentación que exista para la biblioteca de C que está envolviendo. Las bibliotecas GTK de C típicamente usan gtk-doc y por lo tanto tienen comentarios en el código fuente en formato de gtk-doc y alguna documentación adicional en archivos .sgml y .xml. El script «docextract_to_xml.py», de la carpeta <filename>tools/defs_gen</filename> de glibmm, puede leer estos archivos y crear un archivo .xml que <command>gmmproc</command> puede usar para generar comentarios de doxygen. <command>gmmproc</command> incluso intentará transformar la documentación para hacerla más apropiada para una API de C++.</para>
<para lang="en">
For instance,
<programlisting lang="en">./docextract_to_xml.py -s ~/checkout/gnome/gtk+/gtk/ > gtk_docs.xml
</programlisting>
</para>
<para>Dado que esta transformación automática no es siempre apropiada, tal vez quiera proporcionar texto escrito a mano para un método particular. Puede hacer esto copiando el nodo XML para la función de su archivo <filename>something_docs.xml</filename> al archivo <filename>something_docs_override.xml</filename> y cambiando el contenido.</para>
</sect2>
<sect2 id="wrapping-documentation-build-structure">
<title>Estructura de construcción de la documentación</title>
<para>Si copió el esqueleto del árbol de fuentes en mm-common y sustituyó los marcadores de posición, entonces ya tendrá archivos <filename>Makefile.am</filename> y <filename>Doxyfile.in</filename> apropiados. Con la configuración de construcción de mm-common, la lista de los archivos de entrada de Doxygen no se define en el archivo de configuración de Doxygen, sino que se pasa desde <command>make</command> a la entrada estándar de <command>doxygen</command>. La variable <varname>doc_input</varname> define la lista de archivos de entrada en el archivo <filename>Makefile.am</filename>.</para>
</sect2>
</sect1>
</appendix>
</book>
<!-- some vim settings
vim:ts=2 sw=2 et
-->
|