Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 3771 lines (3455 sloc) 151.23 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770
// -*- mode:objc -*-
/*
** PTYTab.m
**
** Copyright (c) 2010
**
** Author: George Nachman
**
** Project: iTerm2
**
** Description: PTYTab abstracts the concept of a tab. This is
** attached to the tabview's identifier and is the owner of
** PTYSession.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#import "PTYTab.h"
#import "PTYSession.h"
#import "WindowControllerInterface.h"
#import "SessionView.h"
#import "FakeWindow.h"
#import "PreferencePanel.h"
#import "iTermGrowlDelegate.h"
#import "PTYScrollView.h"
#import "PSMTabBarControl.h"
#import "PSMTabStyle.h"
#import "ITAddressBookMgr.h"
#import "iTermApplicationDelegate.h"
#import "iTermController.h"
#import "TmuxLayoutParser.h"
#import "ProfileModel.h"
#import "IntervalMap.h"
#import "TmuxDashboardController.h"

//#define PTYTAB_VERBOSE_LOGGING
#ifdef PTYTAB_VERBOSE_LOGGING
#define PtyLog NSLog
#else
#define PtyLog(args...) \
do { \
if (gDebugLogging) { \
DebugLog([NSString stringWithFormat:args]); \
} \
} while (0)
#endif

// No growl output/idle alerts for a few seconds after a window is resized because there will be bogus bg activity
const int POST_WINDOW_RESIZE_SILENCE_SEC = 5;

static CGFloat WithGrainDim(BOOL isVertical, NSSize size);
static CGFloat AgainstGrainDim(BOOL isVertical, NSSize size);
static void SetWithGrainDim(BOOL isVertical, NSSize* dest, CGFloat value);
static void SetAgainstGrainDim(BOOL isVertical, NSSize* dest, CGFloat value);

@implementation PTYTab

// tab label attributes
static NSColor *normalStateColor;
static NSColor *chosenStateColor;
static NSColor *idleStateColor;
static NSColor *newOutputStateColor;
static NSColor *deadStateColor;

static NSImage *warningImage;

// Constants for saved window arrangement keys.
static NSString* TAB_ARRANGEMENT_ROOT = @"Root";
static NSString* TAB_ARRANGEMENT_VIEW_TYPE = @"View Type";
static NSString* VIEW_TYPE_SPLITTER = @"Splitter";
static NSString* VIEW_TYPE_SESSIONVIEW = @"SessionView";
static NSString* SPLITTER_IS_VERTICAL = @"isVertical";
static NSString* TAB_ARRANGEMENT_SPLIITER_FRAME = @"frame";
static NSString* TAB_ARRANGEMENT_SESSIONVIEW_FRAME = @"frame";
static NSString* TAB_WIDTH = @"width";
static NSString* TAB_HEIGHT = @"height";
static NSString* TAB_X = @"x";
static NSString* TAB_Y = @"y";
static NSString* SUBVIEWS = @"Subviews";
static NSString* TAB_ARRANGEMENT_SESSION = @"Session";
static NSString* TAB_ARRANGEMENT_IS_ACTIVE = @"Is Active";
static NSString* TAB_ARRANGEMENT_ID = @"ID"; // only for maximize/unmaximize
static NSString* TAB_ARRANGEMENT_IS_MAXIMIZED = @"Maximized";
static NSString* TAB_ARRANGEMENT_TMUX_WINDOW_PANE = @"tmux window pane";

static const BOOL USE_THIN_SPLITTERS = YES;

+ (void)initialize
{
    NSBundle *thisBundle;
    NSString *imagePath;

    thisBundle = [NSBundle bundleForClass:[self class]];
    imagePath = [thisBundle pathForResource:@"important"
                                     ofType:@"png"];
    if (imagePath) {
        warningImage = [[NSImage alloc] initByReferencingFile: imagePath];
    }

    normalStateColor = [NSColor blackColor];
    chosenStateColor = [NSColor blackColor];
    idleStateColor = [NSColor redColor];
    newOutputStateColor = [NSColor purpleColor];
    deadStateColor = [NSColor grayColor];
}

+ (BOOL)showTitlesPref
{
    return [[PreferencePanel sharedInstance] showPaneTitles];
}

- (BOOL)updatePaneTitles
{
    BOOL anyChange = NO;
    const BOOL showTitles = [PTYTab showTitlesPref];
    NSArray *sessions = [self sessions];
    for (PTYSession *aSession in sessions) {
        if ([[aSession view] setShowTitle:(showTitles && [sessions count] > 1)
                         adjustScrollView:![self isTmuxTab]]) {
            if (![self isTmuxTab]) {
                if ([self fitSessionToCurrentViewSize:aSession]) {
                    anyChange = YES;
                }
            } else {
                // Get the proper size and return yes if it should change.
                NSSize size = [self sessionSizeForViewSize:aSession];
                if (size.width != [aSession columns] ||
                    size.height != [aSession rows]) {
                    anyChange = YES;
                }
            }
        }
    }
    return anyChange;
}

- (void)numberOfSessionsDidChange
{
    if ([self updatePaneTitles] && [self isTmuxTab]) {
        [tmuxController_ windowDidResize:realParentWindow_];
    }
    [realParentWindow_ futureInvalidateRestorableState];
}

- (void)appendSessionViewToViewOrder:(SessionView*)sessionView
{
    NSNumber* n = [NSNumber numberWithInt:[sessionView viewId]];
    if ([viewOrder_ indexOfObject:n] == NSNotFound) {
        int i = currentViewIndex_ + 1;
        if (i > [viewOrder_ count]) {
            i = [viewOrder_ count];
        }
        [viewOrder_ insertObject:n atIndex:i];
    }
    [self numberOfSessionsDidChange];
}

- (void)appendSessionToViewOrder:(PTYSession*)session
{
    [self appendSessionViewToViewOrder:[session view]];
}

// init/dealloc
- (id)initWithSession:(PTYSession*)session
{
    self = [super init];
    PtyLog(@"PTYTab initWithSession %p", self);
    if (self) {
        activeSession_ = session;
        [session setLastActiveAt:[NSDate date]];
        [[session view] setDimmed:NO];
        [self setRoot:[[PTYSplitView alloc] init]];
                PTYTab *oldTab = [session tab];
                if (oldTab && [oldTab tmuxWindow] >= 0) {
                        tmuxWindow_ = [oldTab tmuxWindow];
                        tmuxController_ = [[oldTab tmuxController] retain];
                        parseTree_ = [oldTab->parseTree_ retain];
                        [tmuxController_ changeWindow:tmuxWindow_ tabTo:self];
                } else {
                        tmuxWindow_ = -1;
                }
        [session setTab:self];
        [root_ addSubview:[session view]];
        viewOrder_ = [[NSMutableArray alloc] init];
        [self appendSessionToViewOrder:session];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_refreshLabels:)
                                                 name:@"iTermUpdateLabels"
                                               object:nil];
    return self;
}

+ (void)_recursiveSetDelegateIn:(NSSplitView*)node to:(id)delegate
{
    [node setDelegate:delegate];
    for (NSView* subView in [node subviews]) {
        if ([subView isKindOfClass:[NSSplitView class]]) {
            [PTYTab _recursiveSetDelegateIn:(NSSplitView*)subView to:delegate];
        }
    }
}

// This is used when restoring a window arrangement. A tree of splits and
// sessionviews is passed in but the sessionviews don't have sessions yet.
- (id)initWithRoot:(NSSplitView*)root
{
    self = [super init];
    PtyLog(@"PTYTab initWithRoot %p", self);
    if (self) {
        activeSession_ = nil;
        [self setRoot:root];
        [PTYTab _recursiveSetDelegateIn:root_ to:self];
        viewOrder_ = [[NSMutableArray alloc] init];
        tmuxWindow_ = -1;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_refreshLabels:)
                                                 name:@"iTermUpdateLabels"
                                               object:nil];
    return self;
}

- (void)dealloc
{
    // Post a notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"iTermTabClosing"
                                                        object:self
                                                      userInfo:nil];
    PtyLog(@"PTYTab dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    for (PTYSession* aSession in [self sessions]) {
        [[aSession view] cancelTimers];
        [aSession setTab:nil];
    }
    [root_ release];

    for (id key in idMap_) {
        SessionView* aView = [idMap_ objectForKey:key];

        PTYSession* aSession = [aView session];
        [[aSession view] cancelTimers];
        [aSession cancelTimers];
        [aSession setTab:nil];
    }

    root_ = nil;
    [flexibleView_ release];
    flexibleView_ = nil;
    [viewOrder_ release];
    [fakeParentWindow_ release];
    [icon_ release];
    [idMap_ release];
    [savedArrangement_ release];
    [tmuxController_ release];
    [parseTree_ release];
    [super dealloc];
}

- (NSRect)absoluteFrame
{
    NSRect result;
    result.origin = [root_ convertPoint:NSMakePoint(0, 0) toView:nil];
    result.origin = [[root_ window] convertBaseToScreen:result.origin];
    result.size = [root_ frame].size;
    return result;
}

- (void)_refreshLabels:(id)sender
{
    [tabViewItem_ setLabel:[[self activeSession] name]];
    [parentWindow_ setWindowTitle];
}

- (NSTabViewItem *)tabViewItem
{
    return tabViewItem_;
}

- (void)setBell:(BOOL)flag
{
    PtyLog(@"setBell:%d", (int)flag);
    if (flag) {
        [self setIcon:warningImage];
    } else {
        [self setIcon:nil];
    }
}

- (void)nameOfSession:(PTYSession*)session didChangeTo:(NSString*)newName
{
    if ([self activeSession] == session) {
        [tabViewItem_ setLabel:newName];
    }
}

- (BOOL)isForegroundTab
{
    return [[tabViewItem_ tabView] selectedTabViewItem] == tabViewItem_;
}

- (void)sessionInitiatedResize:(PTYSession*)session width:(int)width height:(int)height
{
    [parentWindow_ sessionInitiatedResize:session width:width height:height];
}

- (PTYSession*)activeSession
{
    return activeSession_;
}

- (void)setActiveSessionPreservingViewOrder:(PTYSession*)session
{
    ++preserveOrder_;
    PtyLog(@"PTYTab setActiveSession:%p", session);
    if (activeSession_ && activeSession_ != session && [activeSession_ dvr]) {
        [realParentWindow_ closeInstantReplay:self];
    }
    BOOL changed = session != activeSession_;
    activeSession_ = session;
    [session setLastActiveAt:[NSDate date]];
    if (activeSession_ == nil) {
        --preserveOrder_;
        return;
    }
    if (changed) {
        [parentWindow_ setWindowTitle];
        [tabViewItem_ setLabel:[[self activeSession] name]];
        if ([realParentWindow_ currentTab] == self) {
            // If you set a textview in a non-current tab to the first responder and
            // then close that tab, it crashes with NSTextInput caling
            // -[PTYTextView respondsToSelector:] on a deallocated instance of the
            // first responder. This kind of hacky workaround keeps us from making
            // a invisible textview the first responder.
            [[realParentWindow_ window] makeFirstResponder:[session TEXTVIEW]];
        }
                [realParentWindow_ setDimmingForSessions];
    }
    for (PTYSession* aSession in [self sessions]) {
        [[aSession TEXTVIEW] refresh];
        [[aSession TEXTVIEW] setNeedsDisplay:YES];
    }
    [self setLabelAttributes];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"iTermSessionBecameKey"
                                                        object:activeSession_];
    // If the active session changed in the active tab in the key window then update the
    // focused state of all sessions in that window.
    if ([[self realParentWindow] currentTab] == self &&
        [[[self realParentWindow] window] isKeyWindow]) {
      for (PTYSession *aSession in [[self realParentWindow] sessions]) {
        [aSession setFocused:(aSession == session)];
      }
    }

    NSUInteger i = [viewOrder_ indexOfObject:[NSNumber numberWithInt:[[session view] viewId]]];
    if (i != NSNotFound) {
        currentViewIndex_ = i;
    }

    --preserveOrder_;
    [realParentWindow_ futureInvalidateRestorableState];
}

- (void)setActiveSession:(PTYSession*)session
{
    if (preserveOrder_) {
        return;
    }
    [self setActiveSessionPreservingViewOrder:session];
    [viewOrder_ removeObject:[NSNumber numberWithInt:[[session view] viewId]]];
    [viewOrder_ addObject:[NSNumber numberWithInt:[[session view] viewId]]];
    currentViewIndex_ = [viewOrder_ count] - 1;

    [self recheckBlur];
}

// Do a depth-first search for a leaf with viewId==requestedId. Returns nil if not found under 'node'.
- (SessionView*)_recursiveSessionViewWithId:(int)requestedId atNode:(NSSplitView*)node
{
    for (NSView* v in [node subviews]) {
        if ([v isKindOfClass:[NSSplitView class]]) {
            SessionView* sv = [self _recursiveSessionViewWithId:requestedId atNode:(NSSplitView*)v];
            if (sv) {
                return sv;
            }
        } else {
            SessionView* sv = (SessionView*) v;
            if ([sv viewId] == requestedId) {
                return sv;
            }
        }
    }
    return nil;
}

- (PTYSession *)sessionWithViewId:(int)viewId
{
    SessionView *sv = [self _recursiveSessionViewWithId:viewId atNode:root_];
    return [sv session];
}

- (SessionView *)_savedViewWithId:(int)i
{
    for (NSNumber *k in idMap_) {
        SessionView *cur = [idMap_ objectForKey:k];
        if ([cur viewId] == [[viewOrder_ objectAtIndex:i] intValue]) {
            return cur;
        }
    }
    return nil;
}

- (void)previousSession
{
    --currentViewIndex_;
    if (currentViewIndex_ < 0) {
        currentViewIndex_ = [viewOrder_ count] - 1;
    }
    SessionView *sv;
    if (isMaximized_) {
        sv = [self _savedViewWithId:currentViewIndex_];
        [root_ replaceSubview:[[root_ subviews] objectAtIndex:0]
                         with:sv];
    } else {
        sv = [self _recursiveSessionViewWithId:[[viewOrder_ objectAtIndex:currentViewIndex_] intValue]
                                        atNode:root_];
    }
    assert(sv);
    if (sv) {
        [self setActiveSessionPreservingViewOrder:[sv session]];
    }
}

- (void)nextSession
{
    ++currentViewIndex_;
    if (currentViewIndex_ >= [viewOrder_ count]) {
        currentViewIndex_ = 0;
    }
    SessionView *sv;
    if (isMaximized_) {
        sv = [self _savedViewWithId:currentViewIndex_];
        [root_ replaceSubview:[[root_ subviews] objectAtIndex:0]
                         with:sv];
    } else {
        sv = [self _recursiveSessionViewWithId:[[viewOrder_ objectAtIndex:currentViewIndex_] intValue]
                                        atNode:root_];
    }
    assert(sv);
    if (sv) {
        [self setActiveSessionPreservingViewOrder:[sv session]];
    }
}

- (int)indexOfSessionView:(SessionView*)sessionView
{
    return [[self sessionViews] indexOfObject:sessionView];
}

- (id<WindowControllerInterface>)parentWindow
{
    return parentWindow_;
}

- (PseudoTerminal*)realParentWindow
{
    return realParentWindow_;
}

- (NSColor *)flexibleViewColor
{
        if ([realParentWindow_ anyFullScreen]) {
                return [NSColor blackColor];
        } else {
                return [NSColor windowBackgroundColor];
        }
}

+ (NSSize)cellSizeForBookmark:(Profile *)bookmark
{
    NSFont *font;
    double hspace;
    double vspace;

    font = [ITAddressBookMgr fontWithDesc:[bookmark objectForKey:KEY_NORMAL_FONT]];
    hspace = [[bookmark objectForKey:KEY_HORIZONTAL_SPACING] doubleValue];
    vspace = [[bookmark objectForKey:KEY_VERTICAL_SPACING] doubleValue];
    return [PTYTextView charSizeForFont:font
                      horizontalSpacing:hspace
                        verticalSpacing:vspace];
}

- (void)updateFlexibleViewColors
{
    NSSize cellSize = [PTYTab cellSizeForBookmark:[PTYTab tmuxBookmark]];
    if (![realParentWindow_ anyFullScreen] &&
        flexibleView_.frame.size.width > root_.frame.size.width &&
        flexibleView_.frame.size.width - root_.frame.size.width < cellSize.width &&
        flexibleView_.frame.size.height > root_.frame.size.height &&
        flexibleView_.frame.size.height - root_.frame.size.height < cellSize.height) {
        // Root is just slightly smaller than flexibleView, by less than the size of a character.
        // Set flexible view's color to the default background color for tmux tabs.
        NSColor *bgColor;
        Profile *bm = [PTYTab tmuxBookmark];
        bgColor = [ITAddressBookMgr decodeColor:[bm objectForKey:KEY_BACKGROUND_COLOR]];
        [flexibleView_ setColor:bgColor];
    } else {
        // Fullscreen, overly large flexible view, or exact size flex view.
        [flexibleView_ setColor:[self flexibleViewColor]];
    }
}

- (void)setParentWindow:(PseudoTerminal*)theParent
{
    // Parent holds a reference to us (indirectly) so we mustn't reference it.
    parentWindow_ = realParentWindow_ = theParent;
    [self updateFlexibleViewColors];
}

- (void)setFakeParentWindow:(FakeWindow*)theParent
{
    [fakeParentWindow_ autorelease];
    parentWindow_ = fakeParentWindow_ = [theParent retain];
}

- (FakeWindow*)fakeWindow
{
    return fakeParentWindow_;
}

- (void)setLockedSession:(PTYSession*)lockedSession
{
    PtyLog(@"PTYTab setLockedSession:%p", lockedSession);
    lockedSession_ = lockedSession;
}

- (void)setTabViewItem:(NSTabViewItem *)theTabViewItem
{
    PtyLog(@"PTYTab setTabViewItem:%p", theTabViewItem);
    // The tab view item holds a refernece to us. So we don't hold a reference to it.
    tabViewItem_ = theTabViewItem;
    if (theTabViewItem != nil) {
        [tabViewItem_ setLabel:[[self activeSession] name]];
        [tabViewItem_ setView:tabView_];
    }
}

- (int)number
{
    return [[tabViewItem_ tabView] indexOfTabViewItem:tabViewItem_];
}

- (int)realObjectCount
{
    return objectCount_;
}

- (int)objectCount
{
    return [[PreferencePanel sharedInstance] useCompactLabel] ? 0 : objectCount_;
}

- (void)setObjectCount:(int)value
{
    objectCount_ = value;
}

- (NSImage *)icon
{
    return icon_;
}

- (void)setIcon:(NSImage *)anIcon
{
    [icon_ autorelease];
    icon_ = [anIcon retain];
}

- (BOOL)realIsProcessing
{
    return isProcessing_;
}

- (BOOL)isProcessing
{
    return ![[PreferencePanel sharedInstance] hideActivityIndicator] &&
        isProcessing_ &&
        ![realParentWindow_ disableProgressIndicators];
}

- (void)setIsProcessing:(BOOL)aFlag
{
    isProcessing_ = aFlag;
}

- (BOOL)isActiveSession
{
    return ([[[self tabViewItem] tabView] selectedTabViewItem] == [self tabViewItem]);
}

- (BOOL)anySessionHasNewOutput
{
    for (PTYSession* session in [self sessions]) {
        if ([session newOutput]) {
            return YES;
        }
    }
    return NO;
}

static void SwapSize(NSSize* size) {
    NSSize temp = *size;
    size->height = temp.width;
    size->width = temp.height;
}

static void SwapPoint(NSPoint* point) {
    NSPoint temp = *point;
    point->x = temp.y;
    point->y = temp.x;
}

static NSString* FormatRect(NSRect r) {
    return [NSString stringWithFormat:@"%lf,%lf %lfx%lf", r.origin.x, r.origin.y,
            r.size.width, r.size.height];
}

- (PTYSession*)_sessionAdjacentTo:(PTYSession*)session verticalDir:(BOOL)verticalDir after:(BOOL)after
{
    NSRect myRect = [root_ convertRect:[[session view] frame] fromView:[[session view] superview]];
    PtyLog(@"origin is %@", FormatRect(myRect));
    NSPoint targetPoint = myRect.origin;
    NSSize rootSize = [root_ frame].size;

    // Rearrange coordinates so that the rest of this function can be written to find the session
    // to the right or left (depending on 'after') of this one.
    if (verticalDir) {
        SwapSize(&myRect.size);
        SwapPoint(&myRect.origin);
        SwapPoint(&targetPoint);
        SwapSize(&rootSize);
    }

    int sign = after ? 1 : -1;
    if (after) {
        targetPoint.x += myRect.size.width;
    }
    targetPoint.x += sign * ([root_ dividerThickness] + 1);
    const CGFloat maxAllowed = after ? rootSize.width : 0;
    if (sign * targetPoint.x > maxAllowed) {
        targetPoint.x -= sign * rootSize.width;
    }
    int offset = 0;
    int defaultOffset = myRect.size.height / 2;
    NSPoint origPoint = targetPoint;
    PtyLog(@"OrigPoint is %lf,%lf", origPoint.x, origPoint.y);
    PTYSession* bestResult = nil;
    PTYSession* defaultResult = nil;
    NSDate* bestDate = nil;
    // Iterate over every possible adjacent session and select the most recently active one.
    while (offset < myRect.size.height) {
        targetPoint = origPoint;
        targetPoint.y += offset;
        PTYSession* result;

        // First, get the session at the target point.
        if (verticalDir) {
            SwapPoint(&targetPoint);
        }
        PtyLog(@"Check session at %lf,%lf", targetPoint.x, targetPoint.y);
        result = [self _recursiveSessionAtPoint:targetPoint relativeTo:root_];
        if (verticalDir) {
            SwapPoint(&targetPoint);
        }
        if (!result) {
            // Oops, targetPoint must have landed right on a divider. Advance by
            // one divider's width.
            targetPoint.y += [root_ dividerThickness];
            if (verticalDir) {
                SwapPoint(&targetPoint);
            }
            result = [self _recursiveSessionAtPoint:targetPoint relativeTo:root_];
            if (verticalDir) {
                SwapPoint(&targetPoint);
            }
            targetPoint.y -= [root_ dividerThickness];
        }
        if (!result) {
            // Maybe we fell off the end of the window? Try going the other direction.
            targetPoint.y -= [root_ dividerThickness];
            if (verticalDir) {
                SwapPoint(&targetPoint);
            }
            result = [self _recursiveSessionAtPoint:targetPoint relativeTo:root_];
            if (verticalDir) {
                SwapPoint(&targetPoint);
            }
            targetPoint.y += [root_ dividerThickness];
        }

        // Advance offset to next sibling's origin.
        NSRect rootRelativeResultRect = [root_ convertRect:[[result view] frame]
                                                  fromView:[[result view] superview]];
        PtyLog(@"Result is at %@", FormatRect(rootRelativeResultRect));
        if (verticalDir) {
            SwapPoint(&rootRelativeResultRect.origin);
            SwapSize(&rootRelativeResultRect.size);
        }
        offset = rootRelativeResultRect.origin.y - origPoint.y + rootRelativeResultRect.size.height;
        PtyLog(@"set offset to %d", offset);
        if (verticalDir) {
            SwapPoint(&rootRelativeResultRect.origin);
            SwapSize(&rootRelativeResultRect.size);
        }

        if ((!bestDate && [result lastActiveAt]) ||
            (bestDate && [[result lastActiveAt] isGreaterThan:bestDate])) {
            // Found a more recently used session.
            bestResult = result;
            bestDate = [result lastActiveAt];
        }
        if (!bestResult && offset > defaultOffset) {
            // Haven't found a used session yet but this one is centered so we might pick it.
            defaultResult = result;
        }
    }

    return bestResult ? bestResult : defaultResult;
}

- (PTYSession*)sessionLeftOf:(PTYSession*)session
{
    return [self _sessionAdjacentTo:session verticalDir:NO after:NO];
}

- (PTYSession*)sessionRightOf:(PTYSession*)session
{
    return [self _sessionAdjacentTo:session verticalDir:NO after:YES];
}

- (PTYSession*)sessionAbove:(PTYSession*)session
{
    return [self _sessionAdjacentTo:session verticalDir:YES after:NO];
}

- (PTYSession*)sessionBelow:(PTYSession*)session
{
    return [self _sessionAdjacentTo:session verticalDir:YES after:YES];
}

- (BOOL)setLabelAttributes
{
    PtyLog(@"PTYTab setLabelAttributes");
    struct timeval now;

    gettimeofday(&now, NULL);
    if ([[self activeSession] exited]) {
        // Session has terminated.
        [self _setLabelAttributesForDeadSession];
        return NO;
    } else if ([[tabViewItem_ tabView] selectedTabViewItem] != [self tabViewItem]) {
        // We are not the foreground tab.
        if (now.tv_sec > [[self activeSession] lastOutput].tv_sec+2) {
            // At least two seconds have passed since the last call.
            [self _setLabelAttributesForIdleBackgroundTabAtTime:now];
            return NO;
        } else {
            // Less than 2 seconds has passed since the last output in the session.
            if ([self anySessionHasNewOutput]) {
                [self _setLabelAttributesForActiveBackgroundTab];
            }
            return YES;
        }
    } else {
        // This tab is the foreground tab and the session hasn't exited.
        [self _setLabelAttributesForForegroundTab];
        return NO;
    }
}

- (void)closeSession:(PTYSession*)session;
{
    [[self parentWindow] closeSession:session];
}

- (void)terminateAllSessions
{
    [[self activeSession] terminate];
}

- (NSArray*)_recursiveSessions:(NSMutableArray*)sessions atNode:(NSSplitView*)node
{
    for (id subview in [node subviews]) {
        if ([subview isKindOfClass:[NSSplitView class]]) {
            [self _recursiveSessions:sessions atNode:(NSSplitView*)subview];
        } else {
            SessionView* sessionView = (SessionView*)subview;
            PTYSession* session = [sessionView session];
            if (session) {
                [sessions addObject:session];
            }
        }
    }
    return sessions;
}

- (NSArray*)_recursiveSessionViews:(NSMutableArray*)sessionViews
                            atNode:(NSSplitView*)node
{
    for (id subview in [node subviews]) {
        if ([subview isKindOfClass:[NSSplitView class]]) {
            [self _recursiveSessionViews:sessionViews atNode:(NSSplitView*)subview];
        } else {
            SessionView* sessionView = (SessionView*)subview;
            if (sessionView) {
                [sessionViews addObject:sessionView];
            }
        }
    }
    return sessionViews;
}

- (NSArray *)windowPanes
{
    NSArray *sessions = [self sessions];
    NSMutableArray *panes = [NSMutableArray array];
    for (PTYSession *session in sessions) {
        [panes addObject:[NSNumber numberWithInt:[session tmuxPane]]];
    }
    return panes;
}

- (NSArray*)sessions
{
    if (idMap_) {
        NSArray* sessionViews = [idMap_ allValues];
        NSMutableArray* result = [NSMutableArray arrayWithCapacity:[sessionViews count]];
        for (SessionView* sessionView in sessionViews) {
            [result addObject:[sessionView session]];
        }
        return result;
    } else {
        return [self _recursiveSessions:[NSMutableArray arrayWithCapacity:1] atNode:root_];
    }
}

- (NSArray*)sessionViews
{
    if (idMap_) {
        NSArray* sessionViews = [idMap_ allValues];
        NSMutableArray* result = [NSMutableArray arrayWithCapacity:[sessionViews count]];
        for (SessionView* sessionView in sessionViews) {
            [result addObject:sessionView];
        }
        return result;
    } else {
        return [self _recursiveSessionViews:[NSMutableArray arrayWithCapacity:1] atNode:root_];
    }
}

- (BOOL)allSessionsExited
{
    return [[self activeSession] exited];
}

- (void)setDvrInSession:(PTYSession*)newSession
{
    PtyLog(@"PTYTab setDvrInSession:%p", newSession);
    PTYSession* oldSession = [self activeSession];
    assert(oldSession != newSession);

    // Swap views between newSession and oldSession.
    SessionView* newView = [newSession view];
    SessionView* oldView = [oldSession view];
    NSSplitView* parentSplit = (NSSplitView*)[oldView superview];
    [oldView retain];
    [parentSplit replaceSubview:oldView with:newView];

    [newSession setName:[oldSession name]];
    [newSession setDefaultName:[oldSession defaultName]];

    // Put the new session in DVR mode and pass it the old session, which it
    // keeps a reference to.

    [newSession setDvr:[[oldSession SCREEN] dvr] liveSession:oldSession];

    activeSession_ = newSession;

    // TODO(georgen): the hidden window can resize itself and the FakeWindow
    // needs to pass that on to the SCREEN. Otherwise the DVR playback into the
    // time after cmd-d was pressed (but before the present) has the wrong
    // window size.
    [self setFakeParentWindow:[[FakeWindow alloc] initFromRealWindow:realParentWindow_
                                                             session:oldSession]];

    // This starts the new session's update timer
    [newSession updateDisplay];
}

- (void)showLiveSession:(PTYSession*)liveSession inPlaceOf:(PTYSession*)replaySession
{
    PtyLog(@"PTYTab showLiveSessio:%p", liveSession);
    [replaySession cancelTimers];
    [liveSession setAddressBookEntry:[replaySession addressBookEntry]];

    SessionView* oldView = [replaySession view];
    SessionView* newView = [liveSession view];
    NSSplitView* parentSplit = (NSSplitView*)[oldView superview];
    [parentSplit replaceSubview:oldView with:newView];
    [newView release];
    activeSession_ = liveSession;

    [fakeParentWindow_ rejoin:realParentWindow_];
}

- (void)_dumpView:(id)view withPrefix:(NSString*)prefix
{
    if ([view isKindOfClass:[SessionView class]]) {
        SessionView* sv = (SessionView*)view;
        NSSize size = [sv frame].size;
        PtyLog(@"%@%lfx%lf", prefix, size.width, size.height);
    } else {
        NSSplitView* sv = (NSSplitView*)view;
        for (id v in [sv subviews]) {
            [self _dumpView:v withPrefix:[NSString stringWithFormat:@" %@", prefix]];
        }
    }
}

- (void)dump
{
    for (id v in [root_ subviews]) {
        [self _dumpView:v withPrefix:@""];
    }
}

// When removing a view some invariants must be maintained:
// 1. A non-root splitview must have at least two children.
// 2. The root splitview may have exactly one child iff that child is a SessionView
// 3. A non-root splitview's orientation must be the opposite of its parent's.
//
// The algorithm is:
// Remove the view from its parent.
// Clean up the parent.
//
// Where "clean up splitView" consists of:
// If splitView (orientation -1^n) has one child
// If that child (orientation -1^(n+1) is a splitview
// If splitView is root:
// Remove only child
// swap splitView's orientation (to -1^(n+1), matching child's)
// move grandchildren into splitView
// else if splitView is not root:
// Move grandchildren into splitView's parent (orientation -1^(n-1), same as child)
// else if only child is a session:
// If splitView is root:
// Do nothing. This is allowed.
// else if splitView is not root:
// Replace splitView with child in its parent.
// else if splitView has no children:
// Remove splitView from its parent

- (void)_checkInvariants:(NSSplitView*)node
{
    if (node != root_) {
        if ([node isKindOfClass:[NSSplitView class]]) {
            // 1. A non-root splitview must have at least two children.
            assert([[node subviews] count] > 1);
            NSSplitView* parentSplit = (NSSplitView*)[node superview];
            // 3. A non-root splitview's orientation must be the opposite of its parent's.
            assert([node isVertical] != [parentSplit isVertical]);
        } else {
            if ([[node subviews] count] == 1) {
                NSView* onlyChild = [[node subviews] objectAtIndex:0];
                // The root splitview may have exactly one child iff that child is a SessionView.
                assert([onlyChild isKindOfClass:[SessionView class]]);
            }
        }
    }

    if ([node isKindOfClass:[NSSplitView class]]) {
        for (NSView* subView in [node subviews]) {
            if ([subView isKindOfClass:[NSSplitView class]]) {
                [self _checkInvariants:(NSSplitView*)subView];
            } else {
                //NSLog(@"CHECK INVARIANTS: retain count of %p is %d", subView, [subView retainCount]);
            }
        }
    } else {
        //NSLog(@"CHECK INVARIANTS: retain count of %p is %d", node, [node retainCount]);
    }
}

- (void)_cleanupAfterRemove:(NSSplitView*)splitView
{
    const int initialNumberOfSubviews = [[splitView subviews] count];
    if (initialNumberOfSubviews == 1) {
        NSView* onlyChild = [[splitView subviews] objectAtIndex:0];
        if ([onlyChild isKindOfClass:[NSSplitView class]]) {
            if (splitView == root_) {
                PtyLog(@"Case 1");
                // Remove only child.
                [onlyChild retain];
                [onlyChild removeFromSuperview];

                // Swap splitView's orientation to match child's
                [splitView setVertical:![splitView isVertical]];

                // Move grandchildren into splitView
                for (NSView* grandchild in [[[onlyChild subviews] copy] autorelease]) {
                    [grandchild retain];
                    [grandchild removeFromSuperview];
                    [splitView addSubview:grandchild];
                    [grandchild release];
                }
                [onlyChild release];
            } else {
                PtyLog(@"Case 2");
                // splitView is not root
                NSSplitView* splitViewParent = (NSSplitView*)[splitView superview];

                NSUInteger splitViewIndex = [[splitViewParent subviews] indexOfObjectIdenticalTo:splitView];
                assert(splitViewIndex != NSNotFound);
                NSView* referencePoint = splitViewIndex > 0 ? [[splitViewParent subviews] objectAtIndex:splitViewIndex - 1] : nil;

                // Remove splitView
                [splitView retain];
                [splitView removeFromSuperview];

                // Move grandchildren into grandparent.
                for (NSView* grandchild in [[[onlyChild subviews] copy] autorelease]) {
                    [grandchild retain];
                    [grandchild removeFromSuperview];
                    [splitViewParent addSubview:grandchild positioned:NSWindowAbove relativeTo:referencePoint];
                    [grandchild release];
                    ++splitViewIndex;
                    referencePoint = [[splitViewParent subviews] objectAtIndex:splitViewIndex - 1];
                }
            }
        } else {
            // onlyChild is a session
            if (splitView != root_) {
                PtyLog(@"Case 3");
                // Replace splitView with child in its parent.
                NSSplitView* splitViewParent = (NSSplitView*)[splitView superview];
                [splitViewParent replaceSubview:splitView with:onlyChild];
            }
        }
    } else if (initialNumberOfSubviews == 0) {
        if (splitView != root_) {
            PtyLog(@"Case 4");
            [self _recursiveRemoveView:splitView];
        }
    }
}
- (void)_recursiveRemoveView:(NSView*)theView
{
    NSSplitView* parentSplit = (NSSplitView*)[theView superview];
    if (parentSplit) {
        // When a session is in instant replay, both the live session (which has no superview)
        // and the fakey DVR session are called here. If parentSplit is null the it's the live
        // session and there's nothing to do here. Otherwise, it's the one that is visible and
        // we take this path.
        [self _checkInvariants:root_];
        [theView removeFromSuperview];
        [self _cleanupAfterRemove:parentSplit];
        [self _checkInvariants:root_];
    }
}

- (NSRect)_recursiveViewFrame:(NSView*)aView
{
    NSRect localFrame = [aView frame];
    if (aView != root_) {
        NSRect parentFrame = [self _recursiveViewFrame:[aView superview]];
        localFrame.origin.x += parentFrame.origin.x;
        localFrame.origin.y += parentFrame.origin.y;
    } else {
        localFrame.origin.x = 0;
        localFrame.origin.y = 0;
    }
    return localFrame;
}

- (PTYSession*)_recursiveSessionAtPoint:(NSPoint)point relativeTo:(NSView*)node
{
    NSRect nodeFrame = [node frame];
    if (point.x < nodeFrame.origin.x ||
        point.y < nodeFrame.origin.y ||
        point.x >= nodeFrame.origin.x + nodeFrame.size.width ||
        point.y >= nodeFrame.origin.y + nodeFrame.size.height) {
        return nil;
    }
    if ([node isKindOfClass:[SessionView class]]) {
        SessionView* sessionView = (SessionView*)node;
        return [sessionView session];
    } else {
        NSSplitView* splitView = (NSSplitView*)node;
        if (node != root_) {
            point.x -= nodeFrame.origin.x;
            point.y -= nodeFrame.origin.y;
        }
        for (NSView* child in [splitView subviews]) {
            PTYSession* theSession = [self _recursiveSessionAtPoint:point relativeTo:child];
            if (theSession) {
                return theSession;
            }
        }
    }
    return nil;
}

- (void)fitSubviewsToRoot
{
    // Make SessionViews full-size.
        [root_ adjustSubviews];

        // Make scrollbars the right size and put them at the tops of their session views.
        for (PTYSession *theSession in [self sessions]) {
                NSSize theSize = [theSession idealScrollViewSize];
                [[theSession SCROLLVIEW] setFrame:NSMakeRect(0,
                                                                                                         0,
                                                                                                         theSize.width,
                                                                                                         theSize.height)];
                [[theSession view] setAutoresizesSubviews:NO];
                [[theSession view] updateTitleFrame];
        }
}

- (void)removeSession:(PTYSession*)aSession
{
    if (idMap_) {
        [self unmaximize];
    }
    PtyLog(@"PTYTab removeSession:%p", aSession);
    // Grab the nearest neighbor (arbitrarily, the subview before if there is on or after if not)
    // to make its earliest descendent that is a session active.
    NSSplitView* parentSplit = (NSSplitView*)[[aSession view] superview];
    NSView* nearestNeighbor;
    if ([[parentSplit subviews] count] > 1) {
        // Do a depth-first search to find the first descendent of the neighbor that is a
        // SessionView and make it active.
        int theIndex = [[parentSplit subviews] indexOfObjectIdenticalTo:[aSession view]];
        int neighborIndex = theIndex > 0 ? theIndex - 1 : theIndex + 1;
        nearestNeighbor = [[parentSplit subviews] objectAtIndex:neighborIndex];
        while ([nearestNeighbor isKindOfClass:[NSSplitView class]]) {
            if ([[nearestNeighbor subviews] count] == 0) {
                // This happens during replaceViewHierarchyWithParseTree
                nearestNeighbor = nil;
                break;
            }
            nearestNeighbor = [[nearestNeighbor subviews] objectAtIndex:0];
        }
    } else {
        // The window is about to close.
        nearestNeighbor = nil;
    }

    // Remove the session.
    [self _recursiveRemoveView:[aSession view]];

    [viewOrder_ removeObject:[NSNumber numberWithInt:[[aSession view] viewId]]];
    if (currentViewIndex_ >= [viewOrder_ count]) {
        // Do not allow currentViewIndex_ to hold an out-of-bounds value
        currentViewIndex_ = [viewOrder_ count] - 1;
    }
    if (aSession == activeSession_) {
        [self setActiveSessionPreservingViewOrder:[(SessionView*)nearestNeighbor session]];
    }

    [self recheckBlur];
    [realParentWindow_ sessionWasRemoved];
    if ([self isTmuxTab]) {
        [self fitSubviewsToRoot];
    }
    [self numberOfSessionsDidChange];
}

- (BOOL)canSplitVertically:(BOOL)isVertical withSize:(NSSize)newSessionSize
{
    NSSplitView* parentSplit = (NSSplitView*)[[activeSession_ view] superview];
    if (isVertical == [parentSplit isVertical]) {
        // Add a child to parentSplit.
        // This is a slightly bogus heuristic: if any sibling of the active session has a violated min
        // size constraint then splits are no longer possible.
        for (NSView* aView in [parentSplit subviews]) {
            NSSize actualSize = [aView frame].size;
            NSSize minSize;
            if ([aView isKindOfClass:[NSSplitView class]]) {
                NSSplitView* splitView = (NSSplitView*)aView;
                minSize = [self _recursiveMinSize:splitView];
            } else {
                SessionView* sessionView = (SessionView*)aView;
                minSize = [self _minSessionSize:sessionView];
            }
            if (isVertical && actualSize.width < minSize.width) {
                return NO;
            }
            if (!isVertical && actualSize.height < minSize.height) {
                return NO;
            }
        }
        return YES;
    } else {
        // Active session will be replaced with a splitter.
        // Another bogus heuristic: if the active session's constraints have been violated then you
        // can't split.
        NSSize actualSize = [[activeSession_ view] frame].size;
        NSSize minSize = [self _minSessionSize:[activeSession_ view]];
        if (isVertical && actualSize.width < minSize.width) {
            return NO;
        }
        if (!isVertical && actualSize.height < minSize.height) {
            return NO;
        }
        return YES;
    }
}

- (void)dumpSubviewsOf:(NSSplitView*)split
{
    for (NSView* v in [split subviews]) {
        PtyLog(@"View %p has height %lf", v, [v frame].size.height);
    }
}

- (void)adjustSubviewsOf:(NSSplitView*)split
{
    PtyLog(@"--- adjust ---");
    [split adjustSubviews];
    PtyLog(@">>AFTER:");
    [self dumpSubviewsOf:split];
    PtyLog(@"<<<<<<<< end dump");
}

- (SessionView*)splitVertically:(BOOL)isVertical
                         before:(BOOL)before
                  targetSession:(PTYSession*)targetSession
{
    if (isMaximized_) {
        [self unmaximize];
    }
    PtyLog(@"PTYTab splitVertically");
    SessionView* targetSessionView = [targetSession view];
    NSSplitView* parentSplit = (NSSplitView*) [targetSessionView superview];
    SessionView* newView = [[[SessionView alloc] initWithFrame:[targetSessionView frame]] autorelease];

    // There has to be an active session, so the parent must have one child.
    assert([[parentSplit subviews] count] != 0);
    PtyLog(@"Before:");
    [self dump];
    if ([[parentSplit subviews] count] == 1) {
        PtyLog(@"PTYTab splitVertically: one child");
        // If the parent split has only one child then it must also be the root.
        assert(parentSplit == root_);

        // Set its orientation to vertical and add the new view.
        [parentSplit setVertical:isVertical];
        [parentSplit addSubview:newView
                     positioned:before ? NSWindowBelow : NSWindowAbove
                     relativeTo:targetSessionView];

        // Resize all subviews the same size to accommodate the new view.
        [self adjustSubviewsOf:parentSplit];
        [self _splitViewDidResizeSubviews:parentSplit];
    } else if ([parentSplit isVertical] != isVertical) {
        PtyLog(@"PTYTab splitVertically parent has opposite orientation");
        // The parent has the opposite orientation splits and has many children. We need to do this:
        // 1. Remove the active SessionView from its parent
        // 2. Replace it with an 'isVertical'-orientation NSSplitView
        // 3. Add two children to the 'isVertical'-orientation NSSplitView: the active session and the new view.
        [targetSessionView retain];
        NSSplitView* newSplit = [[PTYSplitView alloc] initWithFrame:[targetSessionView frame]];
        if (USE_THIN_SPLITTERS) {
            [newSplit setDividerStyle:NSSplitViewDividerStyleThin];
        }
        [newSplit setAutoresizesSubviews:YES];
        [newSplit setDelegate:self];
        [newSplit setVertical:isVertical];
        [[targetSessionView superview] replaceSubview:targetSessionView with:newSplit];
        [newSplit release];
        [newSplit addSubview:before ? newView : targetSessionView];
        [targetSessionView release];
        [newSplit addSubview:before ? targetSessionView : newView];

        // Resize all subviews the same size to accommodate the new view.
        [self adjustSubviewsOf:parentSplit];
        [newSplit adjustSubviews];
        [self _splitViewDidResizeSubviews:newSplit];
    } else {
        PtyLog(@"PTYTab splitVertically multiple children");
        // The parent has same-orientation splits and there is more than one child.
        [parentSplit addSubview:newView
                     positioned:before ? NSWindowBelow : NSWindowAbove
                     relativeTo:targetSessionView];

        // Resize all subviews the same size to accommodate the new view.
        [self adjustSubviewsOf:parentSplit];
        [self _splitViewDidResizeSubviews:parentSplit];
    }
    PtyLog(@"After:");
    [self dump];

    [self appendSessionViewToViewOrder:newView];

    return newView;
}

+ (NSSize)_sessionSizeWithCellSize:(NSSize)cellSize
                        dimensions:(NSSize)dimensions
                        showTitles:(BOOL)showTitles
                        inTerminal:(id<WindowControllerInterface>)term
{
    int rows = dimensions.height;
    int columns = dimensions.width;
    double charWidth = cellSize.width;
    double lineHeight = cellSize.height;
    NSSize size;
    PtyLog(@" session size based on %d rows", rows);
    size.width = columns * charWidth + MARGIN * 2;
    size.height = rows * lineHeight + VMARGIN * 2;

    BOOL hasScrollbar = ![term anyFullScreen] && ![[PreferencePanel sharedInstance] hideScrollbar];
    NSSize outerSize = [PTYScrollView frameSizeForContentSize:size
                                        hasHorizontalScroller:NO
                                          hasVerticalScroller:hasScrollbar
                                                   borderType:NSNoBorder];
    if (showTitles) {
        outerSize.height += [SessionView titleHeight];
    }
    PtyLog(@"session size with %d rows is %@", rows, [NSValue valueWithSize:outerSize]);
    return outerSize;
}

- (NSSize)_sessionSize:(SessionView*)sessionView
{
    PTYSession *session = [sessionView session];
    return [PTYTab _sessionSizeWithCellSize:NSMakeSize([[session TEXTVIEW] charWidth], [[session TEXTVIEW] lineHeight])
                                 dimensions:NSMakeSize([session columns], [session rows])
                                 showTitles:[sessionView showTitle]
                                 inTerminal:parentWindow_];
}

- (NSSize)_minSessionSize:(SessionView*)sessionView
{
    NSSize size;
    PTYSession* session = [sessionView session];
    size.width = MIN_SESSION_COLUMNS * [[session TEXTVIEW] charWidth] + MARGIN * 2;
    size.height = MIN_SESSION_ROWS * [[session TEXTVIEW] lineHeight] + VMARGIN * 2;

    BOOL hasScrollbar = ![parentWindow_ anyFullScreen] && ![[PreferencePanel sharedInstance] hideScrollbar];
    NSSize scrollViewSize = [PTYScrollView frameSizeForContentSize:size
                                             hasHorizontalScroller:NO
                                               hasVerticalScroller:hasScrollbar
                                                        borderType:NSNoBorder];
    return scrollViewSize;
}

// Return the size of a tree of splits based on the rows/cols in each session.
// If any session locked, sets *containsLockOut to YES. A locked session is one
// whose size is "canonical" when its size differs from that of its siblings.
- (NSSize)_recursiveSize:(NSSplitView*)node containsLock:(BOOL*)containsLockOut
{
    PtyLog(@"Computing recursive size for node %p", node);
    NSSize size;
    size.width = 0;
    size.height = 0;

    NSSize dividerSize = NSZeroSize;
    if ([node isVertical]) {
        dividerSize.width = [node dividerThickness];
    } else {
        dividerSize.height = [node dividerThickness];
    }
    *containsLockOut = NO;

    BOOL first = YES;
    BOOL haveFoundLock = NO;
    // Iterate over each subview and add up the width/height of each plus dividers.
    // If there is a discrepancy in height/width, prefer the subview that contains
    // a locked session; else, take the max.
    for (id subview in [node subviews]) {
        NSSize subviewSize;
        if (first) {
            first = NO;
        } else {
            // Add the size of the splitter between this pane and the previous one.
            size.width += dividerSize.width;
            size.height += dividerSize.height;
            PtyLog(@" add %lf for divider", dividerSize.height);
        }

        BOOL subviewContainsLock = NO;
        if ([subview isKindOfClass:[NSSplitView class]]) {
            // Get size of child tree at this subview.
            subviewSize = [self _recursiveSize:(NSSplitView*)subview containsLock:&subviewContainsLock];
            PtyLog(@" add %lf for child split", subviewSize.height);
        } else {
            // Get size of session at this subview.
            SessionView* sessionView = (SessionView*)subview;
            subviewSize = [self _sessionSize:sessionView];
            PtyLog(@" add %lf for session", subviewSize.height);
            if ([sessionView session] == lockedSession_) {
                subviewContainsLock = YES;
            }
        }
        if (subviewContainsLock) {
            *containsLockOut = YES;
        }
        if ([node isVertical]) {
            // Vertical splitters have their subviews arranged horizontally so widths add and
            // height goes to the tallest.
            if (size.height == 0) {
                // Take the cross-grain size of the first subview.
                size.height = subviewSize.height;
            } else if ((int)size.height != (int)subviewSize.height) {
                // There's a discripancy in cross-grain sizes among subviews.
                if (subviewContainsLock) {
                    // Prefer the locked subview.
                    size.height = subviewSize.height;
                } else if (!haveFoundLock) {
                    // This could happen if a session's font changes size.
                    size.height = MAX(size.height, subviewSize.height);
                }
            }
            size.width += subviewSize.width;
        } else {
            // Nonvertical splitters have subviews arranged vertically so heights add and width
            // goes to the widest.
            size.height += subviewSize.height;
            if (size.width == 0) {
                // Take the cross-grain size of the first subview.
                size.width = subviewSize.width;
            } else if ((int)size.width != (int)subviewSize.width) {
                // There's a discripancy in cross-grain sizes among subviews.
                if (subviewContainsLock) {
                    // Prefer the locked subview.
                    size.width = subviewSize.width;
                } else if (!haveFoundLock) {
                    // This could happen if a session's font changes size.
                    size.width = MAX(size.width, subviewSize.width);
                }
            }
        }
        if (subviewContainsLock) {
            haveFoundLock = YES;
        }
    }
    return size;
}

// Return the minimum size of a tree of splits so that no session is smaller than
// MIN_SESSION_COLUMNS columns by MIN_SESSION_ROWS rows.
- (NSSize)_recursiveMinSize:(NSSplitView*)node
{
    NSSize size;
    size.width = 0;
    size.height = 0;

    NSSize dividerSize = NSZeroSize;
    if ([node isVertical]) {
        dividerSize.width = [node dividerThickness];
    } else {
        dividerSize.height = [node dividerThickness];
    }

    BOOL first = YES;
    for (id subview in [node subviews]) {
        NSSize subviewSize;
        if (first) {
            first = NO;
        } else {
            // Add the size of the splitter between this pane and the previous one.
            size.width += dividerSize.width;
            size.height += dividerSize.height;
        }

        if ([subview isKindOfClass:[NSSplitView class]]) {
            // Get size of child tree at this subview.
            subviewSize = [self _recursiveMinSize:(NSSplitView*)subview];
        } else {
            // Get size of session at this subview.
            SessionView* sessionView = (SessionView*)subview;
            subviewSize = [self _minSessionSize:sessionView];
        }
        if ([node isVertical]) {
            // Vertical splitters have their subviews arranged horizontally so widths add and
            // height goes to the tallest.
            if (size.height == 0) {
                // Take the cross-grain size of the first subview.
                size.height = subviewSize.height;
            } else if ((int)size.height != (int)subviewSize.height) {
                size.height = MAX(size.height, subviewSize.height);
            }
            size.width += subviewSize.width;
        } else {
            // Nonvertical splitters have subviews arranged vertically so heights add and width
            // goes to the widest.
            size.height += subviewSize.height;
            if (size.width == 0) {
                // Take the cross-grain size of the first subview.
                size.width = subviewSize.width;
            } else if ((int)size.width != (int)subviewSize.width) {
                // There's a discripancy in cross-grain sizes among subviews.
                size.width = MAX(size.width, subviewSize.width);
            }
        }
    }
    return size;
}

// This returns the content size that would best fit the existing panes. It is the minimum size that
// fits them without having to resize downwards.
- (NSSize)size
{
    BOOL ignore;
    return [self _recursiveSize:root_ containsLock:&ignore];
}

- (void)setReportIdealSizeAsCurrent:(BOOL)v
{
    reportIdeal_ = v;
}

// This returns the current size
- (NSSize)currentSize
{
    if (reportIdeal_) {
        return [self size];
    } else {
        return [root_ frame].size;
    }
}

- (NSSize)minSize
{
    return [self _recursiveMinSize:root_];
}

- (void)setSize:(NSSize)newSize
{
    if ([self isTmuxTab]) {
        [tabView_ setFrameSize:newSize];
    } else {
        PtyLog(@"PTYTab setSize:%fx%f", (float)newSize.width, (float)newSize.height);
        [self dumpSubviewsOf:root_];
        [root_ setFrameSize:newSize];
        //[root_ adjustSubviews];
        [self adjustSubviewsOf:root_];
        [self _splitViewDidResizeSubviews:root_];
    }
}

- (void)_drawSession:(PTYSession*)session inImage:(NSImage*)viewImage atOrigin:(NSPoint)origin
{
    NSImage *textviewImage = [session imageOfSession:YES];

    origin.y = [viewImage size].height - [textviewImage size].height - origin.y;
    [viewImage lockFocus];
    [textviewImage compositeToPoint:origin operation:NSCompositeSourceOver];
    [viewImage unlockFocus];
}

- (void)_recursiveDrawSplit:(NSSplitView*)splitView inImage:(NSImage*)viewImage atOrigin:(NSPoint)splitOrigin
{
    NSPoint origin = splitOrigin;
    CGFloat myHeight = [viewImage size].height;
    BOOL first = YES;
    for (NSView* subview in [splitView subviews]) {
        if (first) {
            // No divider left/above first pane.
            first = NO;
        } else {
            // Draw the divider
            [viewImage lockFocus];
            [[splitView dividerColor] set];
            CGFloat dx = 0;
            CGFloat dy = 0;
            CGFloat hx = 0;
            CGFloat hy = 0;
            CGFloat thickness = [splitView dividerThickness];
            if ([splitView isVertical]) {
                dx = thickness;
                hy = [subview frame].size.height;
            } else {
                dy = thickness;
                hx = [subview frame].size.width;
            }
            // flip the y coordinate for drawing
            NSRectFill(NSMakeRect(origin.x, myHeight - origin.y - (dy + hy),
                                  dx + hx, dy + hy));
            [viewImage unlockFocus];

            // Advance the origin past the divider.
            origin.x += dx;
            origin.y += dy;
        }

        if ([subview isKindOfClass:[NSSplitView class]]) {
            [self _recursiveDrawSplit:(NSSplitView*)subview inImage:viewImage atOrigin:origin];
        } else {
            SessionView* sessionView = (SessionView*)subview;
            // flip the y coordinate for drawing
            CGFloat y = myHeight - origin.y - [subview frame].size.height;
            [self _drawSession:[sessionView session] inImage:viewImage atOrigin:NSMakePoint(origin.x,
                                                                                            y)];
        }
        if ([splitView isVertical]) {
            origin.x += [subview frame].size.width;
        } else {
            origin.y += [subview frame].size.height;
        }
    }
}

- (NSImage*)image:(BOOL)withSpaceForFrame
{
    PtyLog(@"PTYTab image");
    NSRect tabFrame = [[realParentWindow_ tabBarControl] frame];
    NSSize viewSize = [root_ frame].size;
    if (withSpaceForFrame) {
        viewSize.height += tabFrame.size.height;
    }

    NSImage* viewImage = [[[NSImage alloc] initWithSize:viewSize] autorelease];
    [viewImage lockFocus];
    [[NSColor windowBackgroundColor] set];
    NSRectFill(NSMakeRect(0, 0, viewSize.width, viewSize.height));
    [viewImage unlockFocus];

    float yOrigin = 0;
    if (withSpaceForFrame &&
        [[PreferencePanel sharedInstance] tabViewType] == PSMTab_BottomTab) {
        yOrigin += tabFrame.size.height;
    }

    [self _recursiveDrawSplit:root_ inImage:viewImage atOrigin:NSMakePoint(0, yOrigin)];

    // Draw over where the tab bar would usually be
    [viewImage lockFocus];
    [[NSColor windowBackgroundColor] set];
    if (withSpaceForFrame &&
        [[PreferencePanel sharedInstance] tabViewType] == PSMTab_TopTab) {
        tabFrame.origin.y += [viewImage size].height;
    }
    if (withSpaceForFrame) {
        NSRectFill(tabFrame);

        // Draw the background flipped, which is actually the right way up
        NSAffineTransform *transform = [NSAffineTransform transform];
        [transform scaleXBy:1.0 yBy:-1.0];
        [transform concat];
        tabFrame.origin.y = -tabFrame.origin.y - tabFrame.size.height;
        PSMTabBarControl *control = (PSMTabBarControl *)[[realParentWindow_ tabView] delegate];
        [(id <PSMTabStyle>)[control style] drawBackgroundInRect:tabFrame color:nil]; // TODO: use the right color
        [transform invert];
        [transform concat];
    }
    [viewImage unlockFocus];

    return viewImage;
}

- (NSSize)_recursiveRecompact:(NSSplitView *)splitView
{
    double offset = 0;
    double maxAgainstGrain = 0;
    double dividerThickness = [splitView dividerThickness];
    BOOL isVertical = [splitView isVertical];
    for (NSView *node in [splitView subviews]) {
        if ([node isKindOfClass:[NSSplitView class]]) {
            NSSize size = [self _recursiveRecompact:(NSSplitView *)node];
            if (isVertical) {
                offset += node.frame.size.width + dividerThickness;
                [node setFrame:NSMakeRect(0, offset, size.width, size.height)];
                maxAgainstGrain = MAX(maxAgainstGrain, size.height);
            } else {
                offset += node.frame.size.height + dividerThickness;
                [node setFrame:NSMakeRect(offset, 0, size.width, size.height)];
                maxAgainstGrain = MAX(maxAgainstGrain, size.width);
            }
        } else {
            SessionView *sv = (SessionView *)node;
            NSRect frame;
            frame.size = [sv compactFrame];
            if (isVertical) {
                frame.origin.x = offset;
                frame.origin.y = 0;
                offset += frame.size.width + dividerThickness;
                maxAgainstGrain = MAX(maxAgainstGrain, frame.size.height);
            } else {
                frame.origin.x = 0;
                frame.origin.y = offset;
                offset += frame.size.height + dividerThickness;
                maxAgainstGrain = MAX(maxAgainstGrain, frame.size.width);
            }
            [sv setFrame:frame];
        }
    }
    return (isVertical ?
            NSMakeSize(offset - dividerThickness, maxAgainstGrain) :
            NSMakeSize(maxAgainstGrain, offset - dividerThickness));
}

- (void)recompact
{
    NSSize size = [self _recursiveRecompact:root_];
    [root_ setFrame:NSMakeRect(0, 0, size.width, size.height)];
    [self fitSubviewsToRoot];
}

- (NSSize)sessionSizeForViewSize:(PTYSession *)aSession
{
    PtyLog(@"PTYTab fitSessionToCurrentViewSzie");
    PtyLog(@"fitSessionToCurrentViewSize begins");
    BOOL hasScrollbar = ![parentWindow_ anyFullScreen] && ![[PreferencePanel sharedInstance] hideScrollbar];
    [[aSession SCROLLVIEW] setHasVerticalScroller:hasScrollbar];
    NSSize size = [[aSession view] maximumPossibleScrollViewContentSize];
    int width = (size.width - MARGIN*2) / [[aSession TEXTVIEW] charWidth];
    int height = (size.height - VMARGIN*2) / [[aSession TEXTVIEW] lineHeight];
    PtyLog(@"fitSessionToCurrentViewSize %@ gives %d rows", [NSValue valueWithSize:size], height);
    if (width <= 0) {
        NSLog(@"WARNING: Session has %d width", width);
        width = 1;
    }
    if (height <= 0) {
        NSLog(@"WARNING: Session has %d height", height);
        height = 1;
    }

    PtyLog(@"PTYTab sessionSizeForViewSize: view is %fx%f, set screen to %dx%d", size.width, size.height, width, height);
    return NSMakeSize(width, height);
}

// Resize a session's rows and columns for the existing pixel size of its
// containing view.
- (BOOL)fitSessionToCurrentViewSize:(PTYSession*)aSession
{
    if ([aSession isTmuxClient]) {
        return NO;
    }
    NSSize temp = [self sessionSizeForViewSize:aSession];
    int width = temp.width;
    int height = temp.height;
    if ([aSession rows] == height &&
        [aSession columns] == width) {
        PtyLog(@"PTYTab fitSessionToCurrentViewSize: noop");
        return NO;
    }
    if (width == [aSession columns] && height == [aSession rows]) {
        PtyLog(@"fitSessionToWindow - terminating early because session size doesn't change");
        return NO;
    }

    [aSession setWidth:width height:height];
    PtyLog(@"fitSessionToCurrentViewSize - calling setWidth:%d height:%d", width, height);
    [[aSession SCROLLVIEW] setLineScroll:[[aSession TEXTVIEW] lineHeight]];
    [[aSession SCROLLVIEW] setPageScroll:2*[[aSession TEXTVIEW] lineHeight]];
    if ([aSession backgroundImagePath]) {
        [aSession setBackgroundImagePath:[aSession backgroundImagePath]];
    }
    PtyLog(@"PTYTab fitSessionToCurrentViewSize returns");
    return YES;
}

- (BOOL)hasMultipleSessions
{
    return [[root_ subviews] count] > 1;
}

// Return the left/top offset of some divider from its container's origin.
- (CGFloat)_positionOfDivider:(int)theIndex inSplitView:(NSSplitView*)splitView
{
    CGFloat p = 0;
    NSArray* subviews = [splitView subviews];
    for (int i = 0; i <= theIndex; ++i) {
        if ([splitView isVertical]) {
            p += [[subviews objectAtIndex:i] frame].size.width;
        } else {
            p += [[subviews objectAtIndex:i] frame].size.height;
        }
        if (i > 0) {
            p += [splitView dividerThickness];
        }
    }
    return p;
}

- (NSSize)_minSizeOfView:(NSView*)view
{
    if ([view isKindOfClass:[SessionView class]]) {
        SessionView* sessionView = (SessionView*)view;
        return [self _minSessionSize:sessionView];
    } else {
        return [self _recursiveMinSize:(NSSplitView*)view];
    }
}

// Blur the window if most sessions are blurred.
- (bool)blur
{
    int n = 0;
    int y = 0;
    NSArray* sessions = [self sessions];
    for (PTYSession* session in sessions) {
        if ([[[session addressBookEntry] objectForKey:KEY_BLUR] boolValue]) {
            ++y;
        } else {
            ++n;
        }
    }
    return y > n;
}

- (double)blurRadius
{
    double sum = 0;
    double count = 0;
    NSArray* sessions = [self sessions];
    for (PTYSession* session in sessions) {
        if ([[[session addressBookEntry] objectForKey:KEY_BLUR] boolValue]) {
            sum += [[session addressBookEntry] objectForKey:KEY_BLUR_RADIUS] ? [[[session addressBookEntry] objectForKey:KEY_BLUR_RADIUS] floatValue] : 2.0;
            ++count;
        }
    }
    if (count > 0) {
        return sum / count;
    } else {
        // This shouldn't actually happen, but better save than divide by zero.
        return 2.0;
    }
}

- (void)recheckBlur
{
    PtyLog(@"PTYTab recheckBlur");
    if ([realParentWindow_ currentTab] == self &&
        ![[realParentWindow_ window] isMiniaturized]) {
        if ([self blur]) {
            [parentWindow_ enableBlur:[self blurRadius]];
        } else {
            [parentWindow_ disableBlur];
        }
    }
}

+ (NSDictionary*)frameToDict:(NSRect)frame
{
    return [NSDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithDouble:frame.origin.x],
            TAB_X,
            [NSNumber numberWithDouble:frame.origin.y],
            TAB_Y,
            [NSNumber numberWithDouble:frame.size.width],
            TAB_WIDTH,
            [NSNumber numberWithDouble:frame.size.height],
            TAB_HEIGHT,
            nil];
}

+ (NSRect)dictToFrame:(NSDictionary*)dict
{
    return NSMakeRect([[dict objectForKey:TAB_X] doubleValue],
                      [[dict objectForKey:TAB_Y] doubleValue],
                      [[dict objectForKey:TAB_WIDTH] doubleValue],
                      [[dict objectForKey:TAB_HEIGHT] doubleValue]);
}

- (NSDictionary*)_recursiveArrangement:(NSView*)view idMap:(NSMutableDictionary*)idMap isMaximized:(BOOL)isMaximized
{
    NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:3];
    if (isMaximized) {
        [result setObject:[NSNumber numberWithBool:YES]
                   forKey:TAB_ARRANGEMENT_IS_MAXIMIZED];
    }
    isMaximized = NO;
    if ([view isKindOfClass:[NSSplitView class]]) {
        NSSplitView* splitView = (NSSplitView*)view;
        [result setObject:VIEW_TYPE_SPLITTER forKey:TAB_ARRANGEMENT_VIEW_TYPE];
        [result setObject:[PTYTab frameToDict:[view frame]] forKey:TAB_ARRANGEMENT_SPLIITER_FRAME];
        [result setObject:[NSNumber numberWithBool:[splitView isVertical]] forKey:SPLITTER_IS_VERTICAL];
        NSMutableArray* subviews = [NSMutableArray arrayWithCapacity:[[splitView subviews] count]];
        for (NSView* subview in [splitView subviews]) {
            [subviews addObject:[self _recursiveArrangement:subview idMap:idMap isMaximized:isMaximized]];
        }
        [result setObject:subviews forKey:SUBVIEWS];
    } else {
        SessionView* sessionView = (SessionView*)view;
        [result setObject:VIEW_TYPE_SESSIONVIEW
                   forKey:TAB_ARRANGEMENT_VIEW_TYPE];
        [result setObject:[PTYTab frameToDict:[view frame]]
                   forKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME];
        [result setObject:[[sessionView session] arrangement]
                   forKey:TAB_ARRANGEMENT_SESSION];
        [result setObject:[NSNumber numberWithBool:([sessionView session] == [self activeSession])]
                   forKey:TAB_ARRANGEMENT_IS_ACTIVE];
        if (idMap) {
            [result setObject:[NSNumber numberWithInt:[idMap count]]
                       forKey:TAB_ARRANGEMENT_ID];
            [sessionView saveFrameSize];
            [idMap setObject:sessionView forKey:[NSNumber numberWithInt:[idMap count]]];
        }
    }
    return result;
}

+ (void)_recursiveDrawArrangementPreview:(NSDictionary*)arrangement frame:(NSRect)frame
{
    NSLog(@"Frame=%@", [NSValue valueWithRect:frame]);
    if ([[arrangement objectForKey:TAB_ARRANGEMENT_VIEW_TYPE] isEqualToString:VIEW_TYPE_SPLITTER]) {
        BOOL isVerticalSplitter = [[arrangement objectForKey:SPLITTER_IS_VERTICAL] boolValue];
        float xExtent = 0;
        float yExtent = 0;
        float dx = 0;
        float dy = 0;
        float pw, ph;
        NSArray* subviews = [arrangement objectForKey:SUBVIEWS];
        if (isVerticalSplitter) {
            yExtent = frame.size.height;
            dx = frame.size.width / [subviews count];
            pw = dx;
            ph = yExtent;
        } else {
            xExtent = frame.size.width;
            dy = frame.size.height / [subviews count];
            pw = xExtent;
            ph = dy;
        }
        double x = frame.origin.x;
        double y = frame.origin.y;
        for (int i = 0; i < [subviews count]; i++) {
            NSDictionary* subArrangement = [subviews objectAtIndex:i];
            NSRect subFrame = NSMakeRect(x, y, pw, ph);
            [PTYTab _recursiveDrawArrangementPreview:subArrangement frame:subFrame];
            x += dx;
            y += dy;
        }
        [[NSColor grayColor] set];
        x = frame.origin.x;
        y = frame.origin.y;
        for (int i = 0; i < [subviews count]; i++) {
            NSBezierPath *line = [[[NSBezierPath alloc] init] autorelease];
            [line moveToPoint:NSMakePoint(x, y)];
            [line lineToPoint:NSMakePoint(x + xExtent, y + yExtent)];
            [line stroke];
            x += dx;
            y += dy;
// NSRectFill(NSMakeRect(x, y, x+10, y+10));
        }
    } else {
        [PTYSession drawArrangementPreview:[arrangement objectForKey:TAB_ARRANGEMENT_SESSION] frame:frame];
    }
}

+ (NSView*)_recusiveRestoreSplitters:(NSDictionary*)arrangement fromMap:(NSDictionary*)theMap
{
    if ([[arrangement objectForKey:TAB_ARRANGEMENT_VIEW_TYPE] isEqualToString:VIEW_TYPE_SPLITTER]) {
        NSRect frame = [PTYTab dictToFrame:[arrangement objectForKey:TAB_ARRANGEMENT_SPLIITER_FRAME]];
        NSSplitView *splitter = [[PTYSplitView alloc] initWithFrame:frame];
        if (USE_THIN_SPLITTERS) {
            [splitter setDividerStyle:NSSplitViewDividerStyleThin];
        }
        [splitter setVertical:[[arrangement objectForKey:SPLITTER_IS_VERTICAL] boolValue]];

        NSArray* subviews = [arrangement objectForKey:SUBVIEWS];
        for (NSDictionary* subArrangement in subviews) {
            NSView* subView = [PTYTab _recusiveRestoreSplitters:(NSDictionary*)subArrangement
                                                        fromMap:theMap];
            if (subView) {
                [splitter addSubview:subView];
            }
        }
        return splitter;
    } else {
        if (theMap) {
            NSNumber *wp = [arrangement objectForKey:TAB_ARRANGEMENT_TMUX_WINDOW_PANE];
            if (wp) {
                // Creating splitters for a tmux tab. The arrangement is marked
                // up with window pane IDs, whcih may or may not already exist.
                // When restoring a tmux tab, then all session dicts in the
                // arrangement have a window pane. The presence of a
                // TAB_ARRANGEMENT_TMUX_WINDOW_PANE implies that theMap is
                // window pane->SessionView.
                SessionView *sv = [theMap objectForKey:wp];
                NSRect frame = [PTYTab dictToFrame:[arrangement objectForKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME]];
                if (sv) {
                    // Recycle an existing session view.
                    [sv setFrame:frame];
                } else {
                    // This session is new, so set a nonnegative pending window
                    // pane and we'll create a session for it later.
                    sv = [[[SessionView alloc] initWithFrame:frame] autorelease];
                }
                return sv;
            } else {
                // Exiting a maximized-pane state, so we can get a session view from theMap, a map from arrangement id -> SessionView*
                // where arrangement IDs are stored in the arrangement dict.
                SessionView *sv = [theMap objectForKey:[arrangement objectForKey:TAB_ARRANGEMENT_ID]];
                [sv restoreFrameSize];
                return sv;
            }
        } else {
            NSRect frame = [PTYTab dictToFrame:[arrangement objectForKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME]];
            return [[[SessionView alloc] initWithFrame:frame] autorelease];
        }
    }
}

- (PTYSession*)_recursiveRestoreSessions:(NSDictionary*)arrangement
                                  atNode:(NSView*)view
                                   inTab:(PTYTab*)theTab
                           forObjectType:(iTermObjectType)objectType
{
    if ([[arrangement objectForKey:TAB_ARRANGEMENT_VIEW_TYPE] isEqualToString:VIEW_TYPE_SPLITTER]) {
        assert([view isKindOfClass:[NSSplitView class]]);
        NSSplitView* splitter = (NSSplitView*)view;
        NSArray* subArrangements = [arrangement objectForKey:SUBVIEWS];
        PTYSession* active = nil;
        iTermObjectType subObjectType = objectType;
        for (int i = 0; i < [subArrangements count]; ++i) {
            NSDictionary* subArrangement = [subArrangements objectAtIndex:i];
            PTYSession* session = [self _recursiveRestoreSessions:subArrangement
                                                           atNode:[[splitter subviews] objectAtIndex:i]
                                                            inTab:theTab
                                                    forObjectType:subObjectType];
            if (session) {
                active = session;
            }
            subObjectType = iTermPaneObject;
        }
        return active;
    } else {
        assert([view isKindOfClass:[SessionView class]]);
        SessionView* sessionView = (SessionView*)view;

        NSNumber *wp = [arrangement objectForKey:TAB_ARRANGEMENT_TMUX_WINDOW_PANE];
        PTYSession *session;
        if (wp && [sessionView session]) {
            // Re-use existing session because the session view was recycled
            // from the existing view hierarchy when the tmux layout changed but
            // this session was not added or removed.
            session = [sessionView session];
            [session setSizeFromArrangement:[arrangement objectForKey:TAB_ARRANGEMENT_SESSION]];
        } else {
            session = [PTYSession sessionFromArrangement:[arrangement objectForKey:TAB_ARRANGEMENT_SESSION]
                                                  inView:(SessionView*)view
                                                   inTab:theTab
                                           forObjectType:objectType];
            [sessionView setSession:session];
            [self appendSessionToViewOrder:session];
        }
        if ([[arrangement objectForKey:TAB_ARRANGEMENT_IS_ACTIVE] boolValue]) {
            return session;
        } else {
            return nil;
        }
    }
}

+ (void)drawArrangementPreview:(NSDictionary*)arrangement frame:(NSRect)frame
{
    [PTYTab _recursiveDrawArrangementPreview:[arrangement objectForKey:TAB_ARRANGEMENT_ROOT]
                                       frame:frame];
}

- (void)enableFlexibleView
{
    assert(!flexibleView_);
    // Interpose a vew between the tab and the root so the root can be smaller than the tab.
    flexibleView_ = [[SolidColorView alloc] initWithFrame:root_.frame
                                                                                           color:[self flexibleViewColor]];
    [flexibleView_ setFlipped:YES];
    tabView_ = flexibleView_;
    [root_ setAutoresizingMask:NSViewMaxXMargin | NSViewMaxYMargin];
    [tabView_ setAutoresizesSubviews:YES];
    [root_ retain];
    [root_ removeFromSuperview];
    [tabView_ addSubview:root_];
    [root_ release];
    [tabViewItem_ setView:tabView_];
}

- (void)notifyWindowChanged
{
  if (![self isTmuxTab]) {
    return;
  }
  if (!flexibleView_) {
    [self enableFlexibleView];
  }
  [self updateFlexibleViewColors];
  [flexibleView_ setFrameSize:[[realParentWindow_ tabView] frame].size];
  for (PTYSession *aSession in [self sessions]) {
    [[aSession view] setAutoresizesSubviews:NO];
    [[aSession view] updateTitleFrame];
  }
}

+ (PTYTab *)tabWithArrangement:(NSDictionary*)arrangement
                                        inTerminal:(PseudoTerminal*)term
                           hasFlexibleView:(BOOL)hasFlexible
{
    PTYTab* theTab;
    // Build a tree with splitters and SessionViews but no PTYSessions.
    NSSplitView* newRoot = (NSSplitView*)[PTYTab _recusiveRestoreSplitters:[arrangement objectForKey:TAB_ARRANGEMENT_ROOT]
                                                                   fromMap:nil];

    // Create a tab.
    theTab = [[PTYTab alloc] initWithRoot:newRoot];
    if (hasFlexible) {
        [theTab enableFlexibleView];
    }
    [theTab setParentWindow:term];
    [theTab->tabViewItem_ setLabel:@"Restoring..."];
    [newRoot release];

    [theTab setObjectCount:[term numberOfTabs] + 1];

    // Instantiate sessions in the skeleton view tree.
    iTermObjectType objectType;
    if ([term numberOfTabs] == 0) {
        objectType = iTermWindowObject;
    } else {
        objectType = iTermTabObject;
    }
    [theTab setActiveSession:[theTab _recursiveRestoreSessions:[arrangement objectForKey:TAB_ARRANGEMENT_ROOT]
                                                        atNode:theTab->root_
                                                         inTab:theTab
                                                 forObjectType:objectType]];
        return theTab;
}

// This can only be used in conjunction with
// +[tabWithArrangement:inTerminal:hasFlexibleView:].
 - (void)addToTerminal:(PseudoTerminal *)term withArrangement:(NSDictionary *)arrangement
{
    // Add the existing tab, which is now fully populated, to the term.
    [term appendTab:self];
    [self release];

    NSDictionary* root = [arrangement objectForKey:TAB_ARRANGEMENT_ROOT];
    if ([root objectForKey:TAB_ARRANGEMENT_IS_MAXIMIZED] &&
        [[root objectForKey:TAB_ARRANGEMENT_IS_MAXIMIZED] boolValue]) {
        [self maximize];
    }

    [self numberOfSessionsDidChange];
        [term setDimmingForSessions];
}

+ (PTYTab *)openTabWithArrangement:(NSDictionary*)arrangement
                        inTerminal:(PseudoTerminal*)term
                   hasFlexibleView:(BOOL)hasFlexible
{
        PTYTab *theTab = [PTYTab tabWithArrangement:arrangement
                                                                         inTerminal:term
                                                                hasFlexibleView:hasFlexible];
        [theTab addToTerminal:term
                  withArrangement:arrangement];
        return theTab;
}

- (NSDictionary*)arrangementWithMap:(NSMutableDictionary*)idMap
{
    NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:1];
    BOOL temp = isMaximized_;
    if (isMaximized_) {
        [self unmaximize];
    }
    [result setObject:[self _recursiveArrangement:root_ idMap:idMap isMaximized:temp] forKey:TAB_ARRANGEMENT_ROOT];
    if (temp) {
        [self maximize];
    }

    return result;
}

- (NSDictionary*)arrangement
{
    return [self arrangementWithMap:nil];
}

+ (NSSize)_recursiveSetSizesInTmuxParseTree:(NSMutableDictionary *)parseTree
                                 showTitles:(BOOL)showTitles
                                   bookmark:(Profile *)bookmark
                                 inTerminal:(PseudoTerminal *)term
{
    double splitterSize = 1; // hack: should use -[NSSplitView dividerThickness], but don't have an instance yet.
    NSSize totalSize = NSZeroSize;
    NSSize size;

    BOOL isVertical = NO;
    switch ([[parseTree objectForKey:kLayoutDictNodeType] intValue]) {
        case kLeafLayoutNode:
            size = [PTYTab _sessionSizeWithCellSize:[self cellSizeForBookmark:bookmark]
                                         dimensions:NSMakeSize([[parseTree objectForKey:kLayoutDictWidthKey] intValue],
                                                               [[parseTree objectForKey:kLayoutDictHeightKey] intValue])
                                         showTitles:showTitles
                                         inTerminal:term];
            [parseTree setObject:[NSNumber numberWithInt:size.width] forKey:kLayoutDictPixelWidthKey];
            [parseTree setObject:[NSNumber numberWithInt:size.height] forKey:kLayoutDictPixelHeightKey];
            return size;

        case kVSplitLayoutNode:
            isVertical = YES;
        case kHSplitLayoutNode: {
            BOOL isFirst = YES;
            for (NSMutableDictionary *node in [parseTree objectForKey:kLayoutDictChildrenKey]) {
                size = [self _recursiveSetSizesInTmuxParseTree:node
                                                    showTitles:showTitles
                                                      bookmark:bookmark
                                                    inTerminal:term];

                double splitter = isFirst ? 0 : splitterSize;
                SetWithGrainDim(isVertical, &totalSize,
                                WithGrainDim(isVertical, totalSize) + WithGrainDim(isVertical, size) + splitter);
                SetAgainstGrainDim(isVertical, &totalSize,
                                   MAX(AgainstGrainDim(isVertical, totalSize),
                                       AgainstGrainDim(isVertical, size)));
                isFirst = NO;
            }
            [parseTree setObject:[NSNumber numberWithInt:totalSize.width] forKey:kLayoutDictPixelWidthKey];
            [parseTree setObject:[NSNumber numberWithInt:totalSize.height] forKey:kLayoutDictPixelHeightKey];
            break;
        }
    }
    return totalSize;
}

+ (NSDictionary *)_recursiveArrangementForDecoratedTmuxParseTree:(NSDictionary *)parseTree
                                                        bookmark:(Profile *)bookmark
                                                          origin:(NSPoint)origin
                                                activeWindowPane:(int)activeWp
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    BOOL isVertical = YES;
    switch ([[parseTree objectForKey:kLayoutDictNodeType] intValue]) {
        case kLeafLayoutNode: {
            [dict setObject:VIEW_TYPE_SESSIONVIEW forKey:TAB_ARRANGEMENT_VIEW_TYPE];
            NSRect frame;
            frame.origin = origin;
            frame.size.width = [[parseTree objectForKey:kLayoutDictPixelWidthKey] intValue];
            frame.size.height = [[parseTree objectForKey:kLayoutDictPixelHeightKey] intValue];
            [dict setObject:[PTYTab frameToDict:frame] forKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME];
            [dict setObject:[PTYSession arrangementFromTmuxParsedLayout:parseTree bookmark:bookmark]
                     forKey:TAB_ARRANGEMENT_SESSION];
            int wp = [[parseTree objectForKey:kLayoutDictWindowPaneKey] intValue];
            [dict setObject:[NSNumber numberWithInt:wp]
                     forKey:TAB_ARRANGEMENT_TMUX_WINDOW_PANE];
            if (wp == activeWp) {
                [dict setObject:[NSNumber numberWithBool:YES] forKey:TAB_ARRANGEMENT_IS_ACTIVE];
            }
            break;
        }

        case kHSplitLayoutNode:
            isVertical = NO;
            // fall through
        case kVSplitLayoutNode: {
            [dict setObject:VIEW_TYPE_SPLITTER forKey:TAB_ARRANGEMENT_VIEW_TYPE];
            [dict setObject:[NSNumber numberWithBool:isVertical] forKey:SPLITTER_IS_VERTICAL];
            NSRect frame;
            frame.origin = origin;
            frame.size.width = [[parseTree objectForKey:kLayoutDictPixelWidthKey] intValue];
            frame.size.height = [[parseTree objectForKey:kLayoutDictPixelHeightKey] intValue];
            [dict setObject:[PTYTab frameToDict:frame] forKey:TAB_ARRANGEMENT_SPLIITER_FRAME];

            NSMutableArray *subviews = [NSMutableArray array];
            NSArray *children = [parseTree objectForKey:kLayoutDictChildrenKey];
            NSPoint childOrigin = NSZeroPoint;
            double dividerThickness = 1; // HACK! Don't have a splitter yet :(
            for (NSDictionary *child in children) {
                NSDictionary *childDict = [PTYTab _recursiveArrangementForDecoratedTmuxParseTree:child
                                                                                        bookmark:bookmark
                                                                                          origin:childOrigin
                                                                                activeWindowPane:activeWp];
                [subviews addObject:childDict];
                NSRect childFrame = [PTYTab dictToFrame:[childDict objectForKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME]];
                if (isVertical) {
                    childOrigin.x += dividerThickness + childFrame.size.width;
                } else {
                    childOrigin.y += dividerThickness + childFrame.size.height;
                }
            }
            [dict setObject:subviews forKey:SUBVIEWS];
            break;
        }
    }
    return dict;
}

+ (NSDictionary *)arrangementForDecoratedTmuxParseTree:(NSDictionary *)parseTree
                                              bookmark:(Profile *)bookmark
                                      activeWindowPane:(int)activeWp
{
    NSMutableDictionary *arrangement = [NSMutableDictionary dictionary];
    [arrangement setObject:[PTYTab _recursiveArrangementForDecoratedTmuxParseTree:parseTree
                                                                         bookmark:bookmark
                                                                           origin:NSZeroPoint
                                                                 activeWindowPane:activeWp]
                    forKey:TAB_ARRANGEMENT_ROOT];
    // -- BEGIN HACK --
    // HACK! Set the first session we find as the active one.
    NSMutableDictionary *temp = [arrangement objectForKey:TAB_ARRANGEMENT_ROOT];
    while ([[temp objectForKey:TAB_ARRANGEMENT_VIEW_TYPE] isEqualToString:VIEW_TYPE_SPLITTER]) {
        temp = [[temp objectForKey:SUBVIEWS] objectAtIndex:0];
    }
    [temp setObject:[NSNumber numberWithBool:YES] forKey:TAB_ARRANGEMENT_IS_ACTIVE];
    // -- END HACK --

    return arrangement;
}

- (BOOL)isTmuxTab
{
    return tmuxController_ != nil;
}

- (int)tmuxWindow
{
    return tmuxWindow_;
}

+ (Profile *)tmuxBookmark
{
    Profile *bookmark = [[ProfileModel sharedInstance] bookmarkWithName:@"tmux"];
    if (!bookmark) {
        Profile *defaultBookmark = [[ProfileModel sharedInstance] defaultBookmark];
        NSMutableDictionary *tmuxBookmark = [[defaultBookmark mutableCopy] autorelease];
        [tmuxBookmark setObject:@"tmux" forKey:KEY_NAME];
        [tmuxBookmark setObject:[ProfileModel freshGuid] forKey:KEY_GUID];
                [tmuxBookmark setObject:[NSNumber numberWithInt:1000]
                                                 forKey:KEY_SCROLLBACK_LINES];
        [[ProfileModel sharedInstance] addBookmark:tmuxBookmark];
        [[ProfileModel sharedInstance] postChangeNotification];
        bookmark = tmuxBookmark;
    }
    return bookmark;
}

+ (void)setTmuxFont:(NSFont *)font
             nafont:(NSFont *)nafont
           hSpacing:(double)hs
           vSpacing:(double)vs
{
    [[ProfileModel sharedInstance] setObject:[ITAddressBookMgr descFromFont:font]
                                       forKey:KEY_NORMAL_FONT
                                   inBookmark:[PTYTab tmuxBookmark]];
    [[ProfileModel sharedInstance] setObject:[ITAddressBookMgr descFromFont:nafont]
                                       forKey:KEY_NON_ASCII_FONT
                                   inBookmark:[PTYTab tmuxBookmark]];
    [[ProfileModel sharedInstance] setObject:[NSNumber numberWithDouble:hs]
                                       forKey:KEY_HORIZONTAL_SPACING
                                   inBookmark:[PTYTab tmuxBookmark]];
    [[ProfileModel sharedInstance] setObject:[NSNumber numberWithDouble:vs]
                                       forKey:KEY_VERTICAL_SPACING
                                   inBookmark:[PTYTab tmuxBookmark]];
    [[ProfileModel sharedInstance] postChangeNotification];
}

+ (void)setSizesInTmuxParseTree:(NSMutableDictionary *)parseTree
                     inTerminal:(PseudoTerminal *)term
{
    Profile *bookmark = [PTYTab tmuxBookmark];

    NSArray *theChildren = [parseTree objectForKey:kLayoutDictChildrenKey];
    BOOL haveMultipleSessions = ([theChildren count] > 1);
    BOOL showTitles = [PTYTab showTitlesPref] && haveMultipleSessions;
    // Begin by decorating the tree with pixel sizes.
    [PTYTab _recursiveSetSizesInTmuxParseTree:parseTree
                                   showTitles:showTitles
                                     bookmark:bookmark
                                   inTerminal:term];
}

+ (NSMutableDictionary *)parseTreeWithInjectedRootSplit:(NSMutableDictionary *)parseTree
{
    if ([[parseTree objectForKey:kLayoutDictNodeType] intValue] == kLeafLayoutNode) {
        // Inject a splitter at the root to follow our convention even if there is only one session.
        NSMutableDictionary *newRoot = [NSMutableDictionary dictionary];
        [newRoot setObject:[NSNumber numberWithInt:kVSplitLayoutNode] forKey:kLayoutDictNodeType];
        [newRoot setObject:[NSNumber numberWithInt:0] forKey:kLayoutDictXOffsetKey];
        [newRoot setObject:[NSNumber numberWithInt:0] forKey:kLayoutDictYOffsetKey];
        [newRoot setObject:[parseTree objectForKey:kLayoutDictWidthKey] forKey:kLayoutDictWidthKey];
        [newRoot setObject:[parseTree objectForKey:kLayoutDictHeightKey] forKey:kLayoutDictHeightKey];
        [newRoot setObject:[parseTree objectForKey:kLayoutDictPixelWidthKey] forKey:kLayoutDictPixelWidthKey];
        [newRoot setObject:[parseTree objectForKey:kLayoutDictPixelHeightKey] forKey:kLayoutDictPixelHeightKey];
        [newRoot setObject:[NSMutableArray arrayWithObject:parseTree] forKey:kLayoutDictChildrenKey];
        return newRoot;
    } else {
        return parseTree;
    }
}

- (void)reloadTmuxLayout
{
    [PTYTab setSizesInTmuxParseTree:parseTree_ inTerminal:realParentWindow_];
    [self resizeViewsInViewHierarchy:root_ forNewLayout:parseTree_];
    [[root_ window] makeFirstResponder:[[self activeSession] TEXTVIEW]];
}

+ (PTYTab *)openTabWithTmuxLayout:(NSMutableDictionary *)parseTree
                       inTerminal:(PseudoTerminal *)term
                       tmuxWindow:(int)tmuxWindow
                   tmuxController:(TmuxController *)tmuxController
{
    [PTYTab setSizesInTmuxParseTree:parseTree inTerminal:term];
    parseTree = [PTYTab parseTreeWithInjectedRootSplit:parseTree];

    // Grow the window to fit the tab before adding it
    NSSize rootSize = NSMakeSize([[parseTree objectForKey:kLayoutDictPixelWidthKey] intValue],
                                 [[parseTree objectForKey:kLayoutDictPixelHeightKey] intValue]);
    [term fitWindowToTabSize:rootSize];

    // Now we can make an arrangement and restore it.
    NSDictionary *arrangement = [PTYTab arrangementForDecoratedTmuxParseTree:parseTree
                                                                    bookmark:[PTYTab tmuxBookmark]
                                                            activeWindowPane:0];
    PTYTab *theTab = [self tabWithArrangement:arrangement inTerminal:term hasFlexibleView:YES];
    theTab->tmuxWindow_ = tmuxWindow;
    theTab->tmuxController_ = [tmuxController retain];
    theTab->parseTree_ = [parseTree retain];
        // The only way a tmux view should resize is because the server told it to.
        for (PTYSession *aSession in [theTab sessions]) {
                [[aSession view] setAutoresizesSubviews:NO];
        }
        [theTab addToTerminal:term
                  withArrangement:arrangement];

    return theTab;
}

- (void)_recursiveAddSplittersUnderNode:(NSSplitView *)splitter
                              forHeight:(BOOL)forHeight
                                toArray:(NSMutableArray *)splitterArray
                 andSaveSessionFramesIn:(NSMutableDictionary *)frameArray
                                 origin:(NSPoint)origin
{
    int dividerThickness = [splitter dividerThickness];
    for (NSView *v in [splitter subviews]) {
        NSRect frame = [v frame];
        NSPoint curOrigin = origin;
        curOrigin.x = origin.x + frame.origin.x;
        curOrigin.y = origin.y + frame.origin.y;
        if ([v isKindOfClass:[NSSplitView class]]) {
            [self _recursiveAddSplittersUnderNode:(NSSplitView *)v
                                        forHeight:forHeight
                                          toArray:splitterArray
                           andSaveSessionFramesIn:frameArray
                                           origin:curOrigin];
        } else {
            NSRect temp = frame;
            temp.origin = curOrigin;
            [frameArray setObject:[NSValue valueWithRect:temp] forKey:[NSValue valueWithPointer:v]];
        }
        if (forHeight) {
            [splitterArray addObject:[NSNumber numberWithInt:curOrigin.x + frame.size.width]];
        } else {
            [splitterArray addObject:[NSNumber numberWithInt:curOrigin.y + frame.size.height]];
        }
        if ([splitter isVertical]) {
            origin.x += frame.size.width + dividerThickness;
        } else {
            origin.y += frame.size.height + dividerThickness;
        }
    }
}

- (void)addSplitter:(NSSplitView *)splitter
        toIntervalMap:(IntervalMap *)intervalMap
          forHeight:(BOOL)forHeight
             origin:(NSPoint)origin
{
    BOOL first = YES;
    int minPos, size;
    NSSize cellSize = [PTYTab cellSizeForBookmark:[PTYTab tmuxBookmark]];
    if (forHeight != [splitter isVertical]) {
        if (forHeight) {
            minPos = splitter.frame.origin.x + origin.x;
            size = splitter.frame.size.width;
        } else {
            minPos = splitter.frame.origin.y + origin.y;
            size = splitter.frame.size.height;
        }
    }
    for (NSView *view in [splitter subviews]) {
        if (forHeight == [splitter isVertical]) {
            if ([splitter isVertical]) {
                // want to know height
                minPos = origin.x;
                size = view.frame.size.width;
            } else {
                // want to know width
                minPos = origin.y;
                size = view.frame.size.height;
            }
        } else {
            if ([splitter isVertical]) {
                // want to know width
                minPos = origin.y;
                size = view.frame.size.height;
            } else {
                // want to know height
                minPos = origin.x;
                size = view.frame.size.width;
            }
        }
        if ([view isKindOfClass:[NSSplitView class]]) {
            NSSplitView *sub = (NSSplitView *)view;
            [self addSplitter:sub
                  toIntervalMap:intervalMap
                    forHeight:forHeight
                       origin:origin];
        } else {
            SessionView *sv = (SessionView *)view;
            PTYSession *session = [sv session];
            NSRect svFrame = [[session SCROLLVIEW] frame];
            NSRect visibleFrame = [[session SCROLLVIEW] documentVisibleRect]; // excludes scrollbar, if any
            int chars = forHeight ? (svFrame.size.height - VMARGIN * 2) / cellSize.height :
                                    (visibleFrame.size.width - MARGIN * 2) / cellSize.width;
            [intervalMap incrementNumbersBy:chars
                                    inRange:[IntRange rangeWithMin:minPos size:size]];
        }
        if (!first && [splitter isVertical] != forHeight) {
            // Splitters have to be counted and there is a splitter before this view
            [intervalMap incrementNumbersBy:1
                                    inRange:[IntRange rangeWithMin:minPos size:size]];
        }
        first = NO;
        if ([splitter isVertical]) {
            origin.x += view.frame.size.width + [splitter dividerThickness];
        } else {
            origin.y += view.frame.size.height + [splitter dividerThickness];
        }
    }
}

- (int)tmuxSizeForHeight:(BOOL)forHeight
{
    // The minimum size of a splitter is determined thus:
    // Keep an interval map M: [min, max) -> count
    // Where intervals are in the space perpindicular to the size we're measuring.
    // Increment [min, max) by the number of splitters.
    // If a subview is a splitter, recurse
    // If a subview is a sessionview, add its number of rows/cols based on pixels
    // Pick the largest interval

    // So:
    // When forHeight is true, we want the tallest column.
    // intervalMap maps (min x pixel, max x pixel) -> number of rows (plus 1 for each splitter)
    // Then the largest value is the tallest column.
    IntervalMap *intervalMap = [[[IntervalMap alloc] init] autorelease];
    [self addSplitter:root_
          toIntervalMap:intervalMap
            forHeight:forHeight
               origin:NSZeroPoint];
    NSArray *values = [intervalMap allValues];
    NSArray *sortedValues = [values sortedArrayUsingSelector:@selector(compare:)];
    return [[sortedValues lastObject] intValue];
}

// Returns the size (in characters) of the minimum window size that can contain
// this tab. It picks the smallest height that can contain every column and
// every row (counting characters and dividers as 1).
- (NSSize)tmuxSize
{
    // The current size of the sessions in this tab in characters
    // ** BUG **
    // This rounds off fractional parts. We really need to know the maximum capacity, and fractional parts can add up to more than one whole char.
    // Here's a real world example. When scrollbars come into being, every pane interior shrinks by 15px width.
    // In this case, there are two panes side-by-side [|], 345 and 338px. The sizeDiff is 30px. It should add up to 99 chars:
    // (gdb) p (345.0 - 10.0)/7.0 + (338.0 - 10.0)/7.0 + 30.0/7.0
    // $28 = 99
    // But rounding errors shrink it to 97 chars:
    // (gdb) p (345 - 10)/7 + (338 - 10)/7 + 30/7
    // $29 = 97
    // For now, we work around this problem with respect to scrollbars by handling them specially.
    NSSize rootSizeChars = NSMakeSize([self tmuxSizeForHeight:NO], [self tmuxSizeForHeight:YES]);

    // The size in pixels we need to get it to (at most)
    NSSize targetSizePixels = [tabView_ frame].size;

    // The current size in pixels
    NSSize rootSizePixels = [root_ frame].size;

    // The pixel growth (+ for growth, - for shrinkage) needed to attain the target
    NSSize sizeDiff = NSMakeSize(targetSizePixels.width - rootSizePixels.width,
                                 targetSizePixels.height - rootSizePixels.height);

    // The size of a character
    NSSize charSize = [PTYTab cellSizeForBookmark:[PTYTab tmuxBookmark]];

    // The characters growth (+ growth, - shrinkage) needed to attain the target
    NSSize charsDiff = NSMakeSize(sizeDiff.width / charSize.width,
                                  sizeDiff.height / charSize.height);

    // The character size closest to the target.
    NSSize tmuxSize = NSMakeSize((int) (rootSizeChars.width + charsDiff.width),
                                 (int) (rootSizeChars.height + charsDiff.height));

    return tmuxSize;
}

- (BOOL)_recursiveParseTree:(NSMutableDictionary *)parseTree matchesViewHierarchy:(NSView *)view
{
    LayoutNodeType layoutNodeType = [[parseTree objectForKey:kLayoutDictNodeType] intValue];
    LayoutNodeType typeOfView;
    if ([view isKindOfClass:[NSSplitView class]]) {
        NSSplitView *split = (NSSplitView *) view;
        if ([split isVertical]) {
            typeOfView = kVSplitLayoutNode;
        } else {
            typeOfView = kHSplitLayoutNode;
        }
    } else {
        typeOfView = kLeafLayoutNode;
    }

    if (layoutNodeType != typeOfView) {
        return NO;
    }
    if (typeOfView == kLeafLayoutNode) {
        return YES;
    }

    NSArray *treeChildren = [parseTree objectForKey:kLayoutDictChildrenKey];
    NSArray *subviews = [view subviews];
    if ([treeChildren count] != [subviews count]) {
        return NO;
    }
    for (int i = 0; i < treeChildren.count; i++) {
        if (![self _recursiveParseTree:[treeChildren objectAtIndex:i]
                  matchesViewHierarchy:[subviews objectAtIndex:i]]) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)parseTree:(NSMutableDictionary *)parseTree matchesViewHierarchy:(NSView *)view
{
    return [self _recursiveParseTree:parseTree matchesViewHierarchy:view];
}

- (void)_recursiveResizeViewsInViewHierarchy:(NSView *)view
                              forArrangement:(NSDictionary *)arrangement
{
    assert(arrangement);
    NSDictionary *frameDict;
    if ([view isKindOfClass:[NSSplitView class]]) {
        frameDict = [arrangement objectForKey:TAB_ARRANGEMENT_SPLIITER_FRAME];
    } else {
        frameDict = [arrangement objectForKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME];
    }
    NSRect frame = [PTYTab dictToFrame:frameDict];
    [view setFrame:frame];
    [view setNeedsDisplay:YES];
    if ([view isKindOfClass:[NSSplitView class]]) {
        int i = 0;
        NSArray *subarrangements = [arrangement objectForKey:SUBVIEWS];
        for (NSView *child in [view subviews]) {
            [self _recursiveResizeViewsInViewHierarchy:child
                                        forArrangement:[subarrangements objectAtIndex:i]];
            i++;
        }
    } else {
        SessionView *sv = (SessionView *)view;
        PTYSession *theSession = [sv session];
        [theSession resizeFromArrangement:[arrangement objectForKey:TAB_ARRANGEMENT_SESSION]];
                assert([arrangement objectForKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME]);

                NSRect aFrame = [PTYTab dictToFrame:[arrangement objectForKey:TAB_ARRANGEMENT_SESSIONVIEW_FRAME]];
                [sv setFrame:aFrame];
                NSSize theSize = [theSession idealScrollViewSize];
                [[theSession SCROLLVIEW] setFrame:NSMakeRect(0,
                                                                                                         0,
                                                                                                         theSize.width,
                                                                                                         theSize.height)];
                [[theSession view] setAutoresizesSubviews:NO];
                [[theSession view] updateTitleFrame];
    }
}

- (void)resizeViewsInViewHierarchy:(NSView *)view forNewLayout:(NSMutableDictionary *)parseTree
{
    Profile *bookmark = [[ProfileModel sharedInstance] defaultBookmark];
    NSDictionary *arrangement = [PTYTab _recursiveArrangementForDecoratedTmuxParseTree:parseTree
                                                                              bookmark:bookmark
                                                                                origin:NSZeroPoint
                                                                      activeWindowPane:[activeSession_ tmuxPane]];
    ++tmuxOriginatedResizeInProgress_;
    [realParentWindow_ beginTmuxOriginatedResize];
    [self _recursiveResizeViewsInViewHierarchy:view forArrangement:arrangement];
    [realParentWindow_ tmuxTabLayoutDidChange:NO];
    [realParentWindow_ endTmuxOriginatedResize];
    --tmuxOriginatedResizeInProgress_;
    [root_ setNeedsDisplay:YES];
    [flexibleView_ setNeedsDisplay:YES];
}

- (void)setRoot:(NSSplitView *)newRoot
{
    [root_ autorelease];
    root_ = [newRoot retain];
    if (USE_THIN_SPLITTERS) {
        [root_ setDividerStyle:NSSplitViewDividerStyleThin];
    }
    [root_ setAutoresizesSubviews:YES];
    [root_ setDelegate:self];
    [PTYTab _recursiveSetDelegateIn:root_ to:self];
    [flexibleView_ setSubviews:[NSArray array]];
    [flexibleView_ addSubview:newRoot];
    if (!flexibleView_) {
        [root_ setAutoresizingMask:NSViewMaxXMargin | NSViewMaxYMargin];
        tabView_ = newRoot;
    }
    [tabViewItem_ setView:tabView_];
}

- (TmuxController *)tmuxController
{
    return tmuxController_;
}

- (void)replaceViewHierarchyWithParseTree:(NSMutableDictionary *)parseTree
{
    NSMutableDictionary *arrangement = [NSMutableDictionary dictionary];
    parseTree = [PTYTab parseTreeWithInjectedRootSplit:parseTree];
    [arrangement setObject:[PTYTab _recursiveArrangementForDecoratedTmuxParseTree:parseTree
                                                                         bookmark:[PTYTab tmuxBookmark]
                                                                           origin:NSZeroPoint
                                                                 activeWindowPane:[activeSession_ tmuxPane]]
                    forKey:TAB_ARRANGEMENT_ROOT];

    // Create a map of window pane -> SessionView *
    NSMutableDictionary *theMap = [NSMutableDictionary dictionary];
    for (PTYSession *aSession in [self sessions]) {
        [theMap setObject:[aSession view]
                   forKey:[NSNumber numberWithInt:[aSession tmuxPane]]];
    }
    NSArray *preexistingPanes = [[[theMap allKeys] copy] autorelease];
    NSSplitView* newRoot = (NSSplitView*)[PTYTab _recusiveRestoreSplitters:[arrangement objectForKey:TAB_ARRANGEMENT_ROOT]
                                                                   fromMap:theMap];
    // Instantiate sessions in the skeleton view tree.
    iTermObjectType objectType;
    if ([realParentWindow_ numberOfTabs] == 0) {
        objectType = iTermWindowObject;
    } else {
        objectType = iTermTabObject;
    }
    // TODO does this preserve the active session correctly? i don't think so
    PTYSession *activeSession = [self _recursiveRestoreSessions:[arrangement objectForKey:TAB_ARRANGEMENT_ROOT]
                                                    atNode:newRoot
                                                     inTab:self
                                             forObjectType:objectType];
    if (activeSession) {
        [self setActiveSession:activeSession];
    }

    // All sessions that remain in this tab have had their parentage changed so
    // -[sessions] returns only the ones that are to be terminated.
    NSArray *sessionsToTerminate = [self sessions];

    // Swap in the new root split view.
    [self setRoot:newRoot];

    // Terminate sessions that were removed from this tab.
    for (PTYSession *aSession in sessionsToTerminate) {
        [aSession terminate];
        [viewOrder_ removeObject:[NSNumber numberWithInt:[[aSession view] viewId]]];
    }

    if (!activeSession) {
        NSArray *sessions = [self sessions];
        if ([sessions count]) {
            [self setActiveSession:[sessions objectAtIndex:0]];
        }
    }

    for (PTYSession *aSession in [self sessions]) {
        NSNumber *n = [NSNumber numberWithInt:[aSession tmuxPane]];
        if (![preexistingPanes containsObject:n]) {
            // This is a new pane so register it.
            [tmuxController_ registerSession:aSession
                                    withPane:[aSession tmuxPane]
                                    inWindow:tmuxWindow_];
            [aSession setTmuxController:tmuxController_];
        }
    }
    [self fitSubviewsToRoot];
    [self numberOfSessionsDidChange];
    ++tmuxOriginatedResizeInProgress_;
    [realParentWindow_ beginTmuxOriginatedResize];
    [realParentWindow_ tmuxTabLayoutDidChange:YES];
    [realParentWindow_ endTmuxOriginatedResize];
    --tmuxOriginatedResizeInProgress_;
        [realParentWindow_ setDimmingForSessions];
}

- (void)setTmuxLayout:(NSMutableDictionary *)parseTree
       tmuxController:(TmuxController *)tmuxController
{
    [PTYTab setSizesInTmuxParseTree:parseTree
                         inTerminal:realParentWindow_];
    if ([self parseTree:parseTree matchesViewHierarchy:root_]) {
        [self resizeViewsInViewHierarchy:root_ forNewLayout:parseTree];
        [self fitSubviewsToRoot];
    } else {
        if ([[self realParentWindow] inInstantReplay]) {
            [[self realParentWindow] showHideInstantReplay];
        }
        [self replaceViewHierarchyWithParseTree:parseTree];
    }
    [self updateFlexibleViewColors];
    [[root_ window] makeFirstResponder:[[self activeSession] TEXTVIEW]];
    [parseTree_ release];
    parseTree_ = [parseTree retain];
}

- (BOOL)hasMaximizedPane
{
    return isMaximized_;
}

- (void)maximize
{
    assert(!savedArrangement_);
    assert(!idMap_);
    assert(!isMaximized_);

    SessionView* temp = [activeSession_ view];
    savedSize_ = [temp frame].size;

    idMap_ = [[NSMutableDictionary alloc] init];
    savedArrangement_ = [[self arrangementWithMap:idMap_] retain];
    isMaximized_ = YES;

    NSRect oldRootFrame = [root_ frame];
    [root_ removeFromSuperview];

    NSSplitView *newRoot = [[PTYSplitView alloc] init];
    [newRoot setFrame:oldRootFrame];
    [self setRoot:newRoot];

    [temp retain];
    [temp removeFromSuperview];
    [root_ addSubview:temp];
    [temp release];

    [[root_ window] makeFirstResponder:[activeSession_ TEXTVIEW]];
    [realParentWindow_ futureInvalidateRestorableState];
}

- (void)unmaximize
{
    assert(savedArrangement_);
    assert(idMap_);
    assert(isMaximized_);

    // Pull the formerly maximized sessionview out of the old root.
    assert([[root_ subviews] count] == 1);
    SessionView* formerlyMaximizedSessionView = [[root_ subviews] objectAtIndex:0];
    [formerlyMaximizedSessionView retain];
    [formerlyMaximizedSessionView removeFromSuperview];
    [formerlyMaximizedSessionView setFrameSize:savedSize_];

    // Build a tree with splitters and SessionViews/PTYSessions from idMap.
    NSSplitView* newRoot = (NSSplitView*)[PTYTab _recusiveRestoreSplitters:[savedArrangement_ objectForKey:TAB_ARRANGEMENT_ROOT]
                                                                   fromMap:idMap_];
    [PTYTab _recursiveSetDelegateIn:newRoot to:self];

    // Create a tab.
    [self setRoot:newRoot];

    [idMap_ release];
    idMap_ = nil;
    [savedArrangement_ release];
    savedArrangement_ = nil;
    isMaximized_ = NO;

    [[root_ window] makeFirstResponder:[activeSession_ TEXTVIEW]];
    [realParentWindow_ futureInvalidateRestorableState];
}

- (BOOL)promptOnClose
{
    for (PTYSession *aSession in [self sessions]) {
        if ([aSession promptOnClose]) {
            return YES;
        }
    }
    return NO;
}

#pragma mark NSSplitView delegate methods

- (void)splitView:(PTYSplitView *)splitView draggingWillBeginOfSplit:(int)splitterIndex
{
    if (![self isTmuxTab]) {
        // Don't care for non-tmux tabs.
        return;
    }
        // Dragging looks a lot better if we turn on resizing subviews temporarily.
        for (SessionView *sv in [self sessionViews]) {
                [sv setAutoresizesSubviews:YES];
        }
}

- (void)splitView:(PTYSplitView *)splitView draggingDidEndOfSplit:(int)splitterIndex pixels:(NSSize)pxMoved
{
    if (![self isTmuxTab]) {
        // Don't care for non-tmux tabs.
        return;
    }
        for (SessionView *sv in [self sessionViews]) {
                [sv setAutoresizesSubviews:NO];
        }
    // Find a session view adjacent to the moved splitter.
    NSArray *subviews = [splitView subviews];
    NSView *theView = [subviews objectAtIndex:splitterIndex]; // the view right of or below the dragged splitter.
    NSSplitView *parentSplitView = splitView;
    while ([theView isKindOfClass:[NSSplitView class]]) {
        NSSplitView *subSplitView = (NSSplitView *)theView;
        parentSplitView = subSplitView;
        theView = [[subSplitView subviews] objectAtIndex:0];
    }
    SessionView *sessionView = (SessionView *)theView;
    PTYSession *session = [sessionView session];

    // Determine the number of characters moved
    NSSize cellSize = [PTYTab cellSizeForBookmark:[PTYTab tmuxBookmark]];
    int amount;
    if (pxMoved.width) {
        amount = pxMoved.width / cellSize.width;
    } else {
        amount = pxMoved.height / cellSize.height;
    }

    // Ask the tmux server to perform the move and we'll update our layout when
    // it finishes.
    [tmuxController_ windowPane:[session tmuxPane]
                      resizedBy:amount
                   horizontally:[splitView isVertical]];
}

// Prevent any session from becoming smaller than its minimum size because of
// a divder's movement.
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
{
    if (tmuxOriginatedResizeInProgress_) {
        // Whoever's doing the resizing is responsible for making everything
        // perfect.
        return proposedMin;
    }
    PtyLog(@"PTYTab constrainMin:%f divider:%d", (float)proposedMin, dividerIndex);
    CGFloat dim;
    NSSize minSize = [self _minSizeOfView:[[splitView subviews] objectAtIndex:dividerIndex]];
    if ([splitView isVertical]) {
        dim = minSize.width;
    } else {
        dim = minSize.height;
    }
    return [self _positionOfDivider:dividerIndex-1 inSplitView:splitView] + dim;
}

// Prevent any session from becoming smaller than its minimum size because of
// a divder's movement.
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
{
    if (tmuxOriginatedResizeInProgress_) {
        // Whoever's doing the resizing is responsible for making everything
        // perfect.
        return proposedMax;
    }
    PtyLog(@"PTYTab constrainMax:%f divider:%d", (float)proposedMax, dividerIndex);
    CGFloat dim;
    NSSize minSize = [self _minSizeOfView:[[splitView subviews] objectAtIndex:dividerIndex+1]];
    if ([splitView isVertical]) {
        dim = minSize.width;
    } else {
        dim = minSize.height;
    }
    return [self _positionOfDivider:dividerIndex+1 inSplitView:splitView] - dim - [splitView dividerThickness];
}

// The "grain" runs perpindicular to the splitters. An example with isVertical==YES:
// +----------------+
// | | | |
// | | | |
// | | | |
// +----------------+
//
// <------grain----->

static CGFloat WithGrainDim(BOOL isVertical, NSSize size)
{
    return isVertical ? size.width : size.height;
}

static CGFloat AgainstGrainDim(BOOL isVertical, NSSize size)
{
    return WithGrainDim(!isVertical, size);
}

static void SetWithGrainDim(BOOL isVertical, NSSize* dest, CGFloat value)
{
    if (isVertical) {
        dest->width = value;
    } else {
        dest->height = value;
    }
}

static void SetAgainstGrainDim(BOOL isVertical, NSSize* dest, CGFloat value)
{
    SetWithGrainDim(!isVertical, dest, value);
}

- (void)_resizeSubviewsOfSplitViewWithLockedGrandchild:(NSSplitView *)splitView
{
    BOOL isVertical = [splitView isVertical];
    double unlockedSize = 0;
    double minUnlockedSize = 0;
    double lockedSize = WithGrainDim(isVertical, [self _sessionSize:[lockedSession_ view]]);

    // In comments, wgd = with-grain dimension
    // Add up the wgd of the unlocked subviews. Also add up their minimum wgds.
    for (NSView* subview in [splitView subviews]) {
        if ([[lockedSession_ view] superview] != subview) {
            unlockedSize += WithGrainDim(isVertical, [subview frame].size);
            if ([subview isKindOfClass:[NSSplitView class]]) {
                // Get size of child tree at this subview.
                minUnlockedSize += WithGrainDim(isVertical, [self _recursiveMinSize:(NSSplitView*)subview]);
            } else {
                // Get size of session at this subview.
                SessionView* sessionView = (SessionView*)subview;
                minUnlockedSize += WithGrainDim(isVertical, [self _minSessionSize:sessionView]);
            }
        }
    }

    // Check that we can respect the lock without allowing any subview to become smaller
    // than its minimum wgd.
    double overflow = minUnlockedSize + lockedSize - WithGrainDim(isVertical, [splitView frame].size);
    if (overflow > 0) {
        // We can't maintain the locked size without making some other subview smaller than
        // its allowed min. Ignore the lockedness of the session.
        NSLog(@"Warning: locked session doesn't leave enough space for other views. overflow=%lf", overflow);
        [splitView adjustSubviews];
        [self _splitViewDidResizeSubviews:splitView];
    } else {
        // Locked size can be respected. Adjust the size of every subview so that unlocked ones keep
        // their original relative proportions and the locked subview takes on its mandated size.
        double x = 0;
        double overage = 0; // If subviews ended up larger than their proportional size would give, this is the sum of the extra wgds.
        double newSize = WithGrainDim(isVertical, [splitView frame].size) - [splitView dividerThickness] * ([[splitView subviews] count] - 1);
        for (NSView* subview in [splitView subviews]) {
            NSRect newRect = NSZeroRect;
            if (isVertical) {
                newRect.origin.x = x;
            } else {
                newRect.origin.y = x;
            }

            SetAgainstGrainDim(isVertical,
                               &newRect.size,
                               AgainstGrainDim(isVertical, [splitView frame].size));
            if ([[lockedSession_ view] superview] != subview) {
                double fractionOfUnlockedSpace = WithGrainDim(isVertical,
                                                              [subview frame].size) / unlockedSize;
                SetWithGrainDim(isVertical,
                                &newRect.size,
                                (newSize - lockedSize - overage) * fractionOfUnlockedSpace);
            } else {
                SetWithGrainDim(isVertical,
                                &newRect.size,
                                lockedSize);
            }
            double minSize;
            if ([subview isKindOfClass:[NSSplitView class]]) {
                // Get size of child tree at this subview.
                minSize = WithGrainDim(isVertical, [self _recursiveMinSize:(NSSplitView*)subview]);
            } else {
                // Get size of session at this subview.
                SessionView* sessionView = (SessionView*)subview;
                minSize = WithGrainDim(isVertical, [self _minSessionSize:sessionView]);
            }
            if (WithGrainDim(isVertical, newRect.size) < minSize) {
                overage += minSize - WithGrainDim(isVertical, newRect.size);
                SetWithGrainDim(isVertical, &newRect.size, minSize);
            }
            [subview setFrame:newRect];
            x += WithGrainDim(isVertical, newRect.size);
            x += [splitView dividerThickness];
        }
    }
}

- (void)_resizeSubviewsOfSplitViewWithLockedChild:(NSSplitView *)splitView oldSize:(NSSize)oldSize
{
    if ([[splitView subviews] count] == 1) {
        PtyLog(@"PTYTab splitView:resizeSubviewsWithOldSize: case 2");
        // Case 2
        [splitView adjustSubviews];
    } else {
        PtyLog(@"PTYTab splitView:resizeSubviewsWithOldSize: case 3");
        // Case 3
        if ([splitView isVertical]) {
            // Vertical dividers so children are arranged horizontally.
            // Set width of locked session and then resize all others proportionately.
            CGFloat availableSize = [splitView frame].size.width;

            // This also does not include dividers.
            double originalSizeWithoutLockedSession = oldSize.width - [[lockedSession_ view] frame].size.width - ([[splitView subviews] count] - 1) * [splitView dividerThickness];
            NSArray* mySubviews = [splitView subviews];
            NSSize lockedSize = [self _sessionSize:[lockedSession_ view]];
            availableSize -= lockedSize.width;
            availableSize -= [splitView dividerThickness];

            // Resize each child's width so that the space left excluding the locked session is
            // divided up in the same proportions as it was before the resize.
            NSRect newFrame = NSZeroRect;
            newFrame.size.height = lockedSize.height;
            for (id subview in mySubviews) {
                if (subview != [lockedSession_ view]) {
                    // Resizing a non-locked child.
                    NSSize subviewSize = [subview frame].size;
                    double fractionOfOriginalSize = subviewSize.width / originalSizeWithoutLockedSession;
                    newFrame.size.width = availableSize * fractionOfOriginalSize;;
                } else {
                    newFrame.size.width = lockedSize.width;
                }
                [subview setFrame:newFrame];
                newFrame.origin.x += newFrame.size.width + [splitView dividerThickness];
            }
        } else {
            // Horizontal dividers so children are arranged vertically.
            // Set height of locked session and then resize all others proportionately.
            CGFloat availableSize = [splitView frame].size.height;

            // This also does not include dividers.
            double originalSizeWithoutLockedSession = oldSize.height - [[lockedSession_ view] frame].size.height - ([[splitView subviews] count] - 1) * [splitView dividerThickness];
            NSArray* mySubviews = [splitView subviews];
            NSSize lockedSize = [self _sessionSize:[lockedSession_ view]];
            availableSize -= lockedSize.height;
            availableSize -= [splitView dividerThickness];

            // Resize each child's height so that the space left excluding the locked session is
            // divided up in the same proportions as it was before the resize.
            NSRect newFrame = NSZeroRect;
            newFrame.size.width = lockedSize.width;
            for (id subview in mySubviews) {
                if (subview != [lockedSession_ view]) {
                    // Resizing a non-locked child.
                    NSSize subviewSize = [subview frame].size;
                    double fractionOfOriginalSize = subviewSize.height / originalSizeWithoutLockedSession;
                    newFrame.size.height = availableSize * fractionOfOriginalSize;
                } else {
                    newFrame.size.height = lockedSize.height;
                }
                [subview setFrame:newFrame];
                newFrame.origin.y += newFrame.size.height + [splitView dividerThickness];
            }
        }
    }
}

- (NSSet*)_ancestorsOfLockedSession
{
    NSMutableSet* result = [NSMutableSet setWithCapacity:1];
    id current = [[lockedSession_ view ]superview];
    while (current != nil) {
        [result addObject:current];
        if (current == root_) {
            break;
        }
        current = [current superview];
    }
    return result;
}

// min of unlocked session x = minSize(x)
// max of unlocked session x = inf
//
// min of locked session x = sessionSize of x
// max of locked session x = sessionSize of x
//
// min of splitter with locked session s[x] = wtg: sum(minSize(i) for i != x) + sessionSize(x)
// atg: sessionSize(x)
// max of splitter with locked session s[x] = wtg: sum(maxSize(i))
// atg: sessionSize(x)
//
// +--------+
// | | |
// | +----+
// | |xxxx|
// +---+----+
//
// ** this is a generalizable version of all the above: **
// min of splitter with locked grandchild s[x1][x2] = wtg: sum(minSize(i) for all i)
// atg: max(minSize(i) for all i)
// max of splitter with locked grandchild s[x1][x2] = wtg: sum(maxSize(i))
// atg: min(maxSize(i) for all i)


- (void)_recursiveLockedSize:(NSView*)theSubview ancestors:(NSSet*)ancestors minSize:(NSSize*)minSize maxSize:(NSSize*)maxSizeOut
{
    if ([theSubview isKindOfClass:[SessionView class]]) {
        // This must be the locked session. Its min and max size are exactly its ideal size.
        assert(theSubview == [lockedSession_ view]);
        NSSize size = [self _sessionSize:(SessionView*)theSubview];
        *minSize = *maxSizeOut = size;
    } else {
        // This is some ancestor of the locked session.
        NSSplitView* splitView = (NSSplitView*)theSubview;
        *minSize = NSZeroSize;
        BOOL isVertical = [splitView isVertical];
        SetAgainstGrainDim(isVertical, maxSizeOut, INFINITY);
        SetWithGrainDim(isVertical, maxSizeOut, 0);
        BOOL first = YES;
        for (NSView* aView in [splitView subviews]) {
            NSSize viewMin;
            NSSize viewMax;
            if (aView == [lockedSession_ view] || [ancestors containsObject:aView]) {
                [self _recursiveLockedSize:aView ancestors:ancestors minSize:&viewMin maxSize:&viewMax];
            } else {
                viewMin = [self _minSizeOfView:aView];
                viewMax.width = INFINITY;
                viewMax.height = INFINITY;
            }
            double thickness;
            if (first) {
                first = NO;
                thickness = 0;
            } else {
                thickness = [splitView dividerThickness];
            }
            // minSize.wtg := sum(viewMin)
            SetWithGrainDim(isVertical,
                            minSize,
                            WithGrainDim(isVertical, *minSize) + WithGrainDim(isVertical, viewMin) + thickness);
            // minSize.atg := MAX(viewMin)
            SetAgainstGrainDim(isVertical,
                               minSize,
                               MAX(AgainstGrainDim(isVertical, *minSize), AgainstGrainDim(isVertical, viewMin)));
            // maxSizeOut.wtg := sum(viewMax)
            SetWithGrainDim(isVertical,
                            maxSizeOut,
                            WithGrainDim(isVertical, *maxSizeOut) + WithGrainDim(isVertical, viewMax) + thickness);
            // maxSizeOut.atg := MIN(viewMax)
            SetAgainstGrainDim(isVertical,
                               maxSizeOut,
                               MIN(AgainstGrainDim(isVertical, *maxSizeOut), AgainstGrainDim(isVertical, viewMax)));
        }
    }
}

- (void)_redistributeQuantizationError:(const double)targetSize
                     currentSumOfSizes:(double)currentSumOfSizes
                                 sizes:(NSMutableArray *)sizes
                              minSizes:(NSArray*)minSizes
                              maxSizes:(NSArray*)maxSizes
{
    // In case quantization caused some rounding error, randomly adjust subviews by plus or minus
    // one pixel.
    int error = currentSumOfSizes - targetSize;
    int change;
    if (error > 0) {
        change = -1;
    } else {
        change = 1;
    }
    // First redistribute error while respecting min and max constraints until that is no longer
    // possible.
    while (error != 0) {
        BOOL anyChange = NO;
        for (int i = 0; i < [sizes count] && error != 0; ++i) {
            const double size = [[sizes objectAtIndex:i] doubleValue];
            const double theMin = [[minSizes objectAtIndex:i] doubleValue];
            const double theMax = [[maxSizes objectAtIndex:i] doubleValue];
            const double proposedSize = size + change;
            if (proposedSize >= theMin && proposedSize <= theMax) {
                [sizes replaceObjectAtIndex:i withObject:[NSNumber numberWithDouble:proposedSize]];
                error += change;
                anyChange = YES;
            }
        }
        if (!anyChange) {
            break;
        }
    }

    // As long as there is still some error left, use 1 for min and disregard max.
    while (error != 0) {
        BOOL anyChange = NO;
        for (int i = 0; i < [sizes count] && error != 0; ++i) {
            const double size = [[sizes objectAtIndex:i] doubleValue];
            if (size + change > 0) {
                [sizes replaceObjectAtIndex:i withObject:[NSNumber numberWithDouble:size + change]];
                error += change;
                anyChange = YES;
            }
        }
        if (!anyChange) {
            PtyLog(@"Failed to redistribute quantization error. Change=%d, sizes=%@.", change, sizes);
            NSLog(@"Failed to redistribute quantization error. Change=%d, sizes=%@.", change, sizes);
            return;
        }
    }
}

// Called after a splitter has been resized. This adjusts session sizes appropriately,
// with special attention paid to the "locked" session, which never resizes.
- (void)splitView:(NSSplitView *)splitView resizeSubviewsWithOldSize:(NSSize)oldSize
{
    // While we'd prefer not to do this if tmuxOriginatedResizeInProgress_>0,
    // it's necessary to avoid a warning. It should be harmless because after
    // setting a splitter's size we go back and set each child's size in
    // -[_recursiveSetSizesInTmuxParseTree:showTitles:bookmark:inTerminal:].
    if ([[splitView subviews] count] == 0) {
        // nothing to do!
        return;
    }
    if ([splitView frame].size.width == 0) {
        NSLog(@"Warning: splitView:resizeSubviewsWithOldSize: resized to 0 width");
        return;
    }
    PtyLog(@"splitView:resizeSubviewsWithOldSize for %p", splitView);
    BOOL isVertical = [splitView isVertical];
    NSSet* ancestors = [self _ancestorsOfLockedSession];
    NSSize minLockedSize = NSZeroSize;
    NSSize maxLockedSize = NSZeroSize;
    const double n = [[splitView subviews] count];

    // Find the min, max, and ideal proportionate size for each subview.
    NSMutableArray* sizes = [NSMutableArray arrayWithCapacity:[[splitView subviews] count]];
    NSMutableArray* minSizes = [NSMutableArray arrayWithCapacity:[[splitView subviews] count]];
    NSMutableArray* maxSizes = [NSMutableArray arrayWithCapacity:[[splitView subviews] count]];

    // This is the sum of the with-the-grain sizes excluding dividers that we need to attain.
    const double targetSize = WithGrainDim(isVertical, [splitView frame].size) - ([splitView dividerThickness] * (n - 1));
    PtyLog(@"splitView:resizeSubviewsWithOldSize - target size is %lf", targetSize);

    // Add up the existing subview sizes to come up with the previous total size excluding dividers.
    double oldTotalSize = 0;
    for (NSView* aSubview in [splitView subviews]) {
        oldTotalSize += WithGrainDim(isVertical, [aSubview frame].size);
    }
    double sizeChangeCoeff = 0;
    BOOL ignoreConstraints = NO;
    if (oldTotalSize == 0) {
        // Nothing to go by. Just set all subviews to the same size.
        PtyLog(@"splitView:resizeSubviewsWithOldSize: old size was 0");
        ignoreConstraints = YES;
    } else {
        sizeChangeCoeff = targetSize / oldTotalSize;
        PtyLog(@"splitView:resizeSubviewsWithOldSize. initial coeff=%lf", sizeChangeCoeff);
    }
    if (!ignoreConstraints) {
        // Set the min and max size for each subview. Assign an initial guess to sizes.
        double currentSumOfSizes = 0;
        double currentSumOfMinClamped = 0;
        double currentSumOfMaxClamped = 0;
        for (NSView* aSubview in [splitView subviews]) {
            double theMinSize;
            double theMaxSize;
            if (aSubview == [lockedSession_ view] || [ancestors containsObject:aSubview]) {
                [self _recursiveLockedSize:aSubview
                                 ancestors:ancestors
                                   minSize:&minLockedSize
                                   maxSize:&maxLockedSize];
                theMinSize = WithGrainDim(isVertical, minLockedSize);
                theMaxSize = WithGrainDim(isVertical, maxLockedSize);
                PtyLog(@"splitView:resizeSubviewsWithOldSize - this subview is LOCKED");
            } else {
                if ([aSubview isKindOfClass:[NSSplitView class]]) {
                    theMinSize = WithGrainDim(isVertical, [self _recursiveMinSize:(NSSplitView*)aSubview]);
                } else {
                    theMinSize = WithGrainDim(isVertical, [self _minSessionSize:(SessionView*)aSubview]);
                }
                theMaxSize = targetSize;
                PtyLog(@"splitView:resizeSubviewsWithOldSize - this subview is unlocked");
            }
            PtyLog(@"splitView:resizeSubviewsWithOldSize - range of %p is [%lf,%lf]", aSubview, theMinSize, theMaxSize);
            [minSizes addObject:[NSNumber numberWithDouble:theMinSize]];
            [maxSizes addObject:[NSNumber numberWithDouble:theMaxSize]];
            const double initialGuess = sizeChangeCoeff * WithGrainDim(isVertical, [aSubview frame].size);
            const double size = lround(MIN(MAX(initialGuess, theMinSize), theMaxSize));
            PtyLog(@"splitView:resizeSubviewsWithOldSize - initial guess of %p is %lf (based on size of %lf), clamped is %lf", aSubview, initialGuess, (double)WithGrainDim(isVertical, [aSubview frame].size), size);
            [sizes addObject:[NSNumber numberWithDouble:size]];
            currentSumOfSizes += size;
            if (size == theMinSize) {
                currentSumOfMinClamped += size;
            }
            if (size == theMaxSize) {
                currentSumOfMaxClamped += size;
            }
        }

        // Refine sizes while we're more than half a pixel away from the target size.
        const double kEpsilon = 0.5;
        while (fabs(currentSumOfSizes - targetSize) > kEpsilon) {
            PtyLog(@"splitView:resizeSubviewsWithOldSize - refining. currentSumOfSizes=%lf vs target %lf", currentSumOfSizes, targetSize);
            double currentSumOfUnclamped;
            double desiredNewSizeForUnclamped;
            if (currentSumOfSizes < targetSize) {
                currentSumOfUnclamped = currentSumOfSizes - currentSumOfMaxClamped;
                desiredNewSizeForUnclamped = targetSize - currentSumOfMaxClamped;
            } else {
                currentSumOfUnclamped = currentSumOfSizes - currentSumOfMinClamped;
                desiredNewSizeForUnclamped = targetSize - currentSumOfMinClamped;
            }
            if (currentSumOfUnclamped < kEpsilon) {
                // Not enough unclamped space to make any change.
                ignoreConstraints = YES;
                break;
            }
            // Set a coefficient that will be applied only to subviews that aren't clamped. If we're
            // able to resize all currently unclamped subviews by this coefficient then we should
            // hit exactly the target size.
            const double coeff = desiredNewSizeForUnclamped / currentSumOfUnclamped;
            PtyLog(@"splitView:resizeSubviewsWithOldSize - coeff %lf to bring current %lf unclamped size to %lf", coeff, currentSumOfUnclamped, desiredNewSizeForUnclamped);

            // Try to resize every subview by the coefficient. Clamped subviews won't be able to
            // change.
            currentSumOfSizes = 0;
            currentSumOfMinClamped = 0;
            currentSumOfMaxClamped = 0;
            BOOL anyChanges = NO;
            for (int i = 0; i < [sizes count]; ++i) {
                const double preferredSize = [[sizes objectAtIndex:i] doubleValue] * coeff;
                const double theMinSize = [[minSizes objectAtIndex:i] doubleValue];
                const double theMaxSize = [[maxSizes objectAtIndex:i] doubleValue];
                const double size = lround(MIN(MAX(preferredSize, theMinSize), theMaxSize));
                if (!anyChanges && size != [[sizes objectAtIndex:i] doubleValue]) {
                    anyChanges = YES;
                }
                PtyLog(@"splitView:resizeSubviewsWithOldSize - change %lf to %lf (would be %lf unclamped)", [[sizes objectAtIndex:i] doubleValue], size, preferredSize);
                [sizes replaceObjectAtIndex:i withObject:[NSNumber numberWithDouble:size]];

                currentSumOfSizes += size;
                if (size == theMinSize) {
                    currentSumOfMinClamped += size;
                }
                if (size == theMaxSize) {
                    currentSumOfMaxClamped += size;
                }
            }
            if (!anyChanges) {
                PtyLog(@"splitView:resizeSubviewsWithOldSize - nothing changed in this round");
                if (fabs(currentSumOfSizes - targetSize) > [[splitView subviews] count]) {
                    // I'm not sure this will ever happen, but just in case quantization prevents us
                    // from converging give up and ignore constraints.
                    NSLog(@"No changes! Ignoring constraints!");
                    PtyLog(@"splitView:resizeSubviewsWithOldSize - No changes! Ignoring constraints!");
                    ignoreConstraints = YES;
                } else {
                    PtyLog(@"splitView:resizeSubviewsWithOldSize - redistribute quantization error");
                    [self _redistributeQuantizationError:targetSize
                                       currentSumOfSizes:currentSumOfSizes
                                                   sizes:sizes
                                                minSizes:minSizes
                                                maxSizes:maxSizes];
                }
                break;
            }
        }
    }

    if (ignoreConstraints) {
        PtyLog(@"splitView:resizeSubviewsWithOldSize - ignoring constraints");
        // Not all the constraints could be satisfied. Set every subview to its ideal size and hope
        // for the best.
        double currentSumOfSizes = 0;
        if (sizeChangeCoeff == 0) {
            // Original size was 0 so make all subviews equal.
            for (NSView* aSubview in [splitView subviews]) {
                const double size = lround(targetSize / n);
                currentSumOfSizes += size;
                [sizes addObject:[NSNumber numberWithDouble:size]];
            }
        } else {
            // Resize everything proportionately.
            for (int i = 0; i < [sizes count]; ++i) {
                NSView* aSubview = [[splitView subviews] objectAtIndex:i];
                const double size = lround(sizeChangeCoeff * WithGrainDim(isVertical, [aSubview frame].size));
                currentSumOfSizes += size;
                [sizes replaceObjectAtIndex:i withObject:[NSNumber numberWithDouble:size]];
            }
        }

        [self _redistributeQuantizationError:targetSize
                           currentSumOfSizes:currentSumOfSizes
                                       sizes:sizes
                                    minSizes:minSizes
                                    maxSizes:maxSizes];
    }

    // If all subviews are leaf nodes, redistribute extra pixels among the subviews
    // so that as few as possible of them has extra space "with the grain".
    BOOL allSubviewsAreLeafNodes = YES;
    for (id aSubview in [splitView subviews]) {
        if (![aSubview isKindOfClass:[SessionView class]]) {
            allSubviewsAreLeafNodes = NO;
            break;
        }
    }
    if (allSubviewsAreLeafNodes) {
        // index -> overage
        NSMutableDictionary *over = [NSMutableDictionary dictionary];
        // index -> underage
        NSMutableDictionary *under = [NSMutableDictionary dictionary];
        for (int i = 0; i < sizes.count; i++) {
            NSSize size;
            SetWithGrainDim(isVertical, &size, [[sizes objectAtIndex:i] doubleValue]);
            SessionView *sessionView = (SessionView *) [[splitView subviews] objectAtIndex:i];
            PTYSession *aSession = [sessionView session];
            int ou = [aSession overUnder:WithGrainDim(isVertical, size) inVerticalDimension:!isVertical];
            if (ou > 0) {
                [over setObject:[NSNumber numberWithInt:ou] forKey:[NSNumber numberWithInt:i]];
            } else if (ou < 0) {
                [under setObject:[NSNumber numberWithInt:-ou] forKey:[NSNumber numberWithInt:i]];
            }
        }

        // Get indices of subviews with extra/lacking pixels
        NSMutableArray *overKeys = [NSMutableArray arrayWithArray:[[over allKeys] sortedArrayUsingSelector:@selector(compare:)]];
        NSMutableArray *underKeys = [NSMutableArray arrayWithArray:[[under allKeys] sortedArrayUsingSelector:@selector(compare:)]];
        while (overKeys.count && underKeys.count) {
            // Pick the last over and under values and cancel the out as much as possible.
            int mostOverIndex = [[overKeys lastObject] intValue];
            int mostOverValue = [[over objectForKey:[overKeys lastObject]] intValue];
            int mostUnderIndex = [[underKeys lastObject] intValue];
            int mostUnderValue = [[under objectForKey:[underKeys lastObject]] intValue];

            int currentValue = MIN(mostOverValue, mostUnderValue);
            mostOverValue -= currentValue;
            mostUnderValue -= currentValue;
            double overSize = [[sizes objectAtIndex:mostOverIndex] doubleValue];
            double underSize = [[sizes objectAtIndex:mostUnderIndex] doubleValue];
            [sizes replaceObjectAtIndex:mostOverIndex withObject:[NSNumber numberWithDouble:overSize - currentValue]];
            [sizes replaceObjectAtIndex:mostUnderIndex withObject:[NSNumber numberWithDouble:underSize + currentValue]];
            if (!mostOverValue) {
                [overKeys removeObject:[NSNumber numberWithInt:mostOverIndex]];
            }
            if (!mostUnderValue) {
                [underKeys removeObject:[NSNumber numberWithInt:mostUnderIndex]];
            }
            [over setObject:[NSNumber numberWithInt:mostOverValue] forKey:[NSNumber numberWithInt:mostOverIndex]];
            [under setObject:[NSNumber numberWithInt:mostUnderValue] forKey:[NSNumber numberWithInt:mostUnderIndex]];
        }
    }

    NSRect frame = NSZeroRect;
    SetAgainstGrainDim(isVertical, &frame.size, AgainstGrainDim(isVertical, [splitView frame].size));
    for (int i = 0; i < [sizes count]; ++i) {
        SetWithGrainDim(isVertical, &frame.size, [[sizes objectAtIndex:i] doubleValue]);
        [[[splitView subviews] objectAtIndex:i] setFrame:frame];
        if (isVertical) {
            frame.origin.x += frame.size.width + [splitView dividerThickness];
        } else {
            frame.origin.y += frame.size.height + [splitView dividerThickness];
        }
    }
}

// Inform sessions about their new sizes. This is called after views have finished
// being resized.
- (void)splitViewDidResizeSubviews:(NSNotification *)aNotification
{
    if (tmuxOriginatedResizeInProgress_) {
        // Whoever's doing the resizing is responsible for making everything
        // perfect.
        return;
    }
    if ([root_ frame].size.width == 0) {
        NSLog(@"Warning: splitViewDidResizeSubviews: resized to 0 width");
        return;
    }
    PtyLog(@"splitViewDidResizeSubviews notification received. new height is %lf", [root_ frame].size.height);
    NSSplitView* splitView = [aNotification object];
    [self _splitViewDidResizeSubviews:splitView];
}

- (void)_splitViewDidResizeSubviews:(NSSplitView*)splitView
{
    PtyLog(@"_splitViewDidResizeSubviews running");
    for (NSView* subview in [splitView subviews]) {
        if ([subview isKindOfClass:[SessionView class]]) {
            PTYSession* session = [(SessionView*)subview session];
            if (session) {
                PtyLog(@"splitViewDidResizeSubviews - view is %fx%f, ignore=%d", [subview frame].size.width, [subview frame].size.height, (int)[session ignoreResizeNotifications]);
                if (![session ignoreResizeNotifications]) {
                    PtyLog(@"splitViewDidResizeSubviews - adjust session %p", session);
                    [self fitSessionToCurrentViewSize:session];
                }
            }
        } else {
            [self _splitViewDidResizeSubviews:(NSSplitView*)subview];
        }
    }
}

- (CGFloat)_recursiveStepSize:(NSView*)theView wantWidth:(BOOL)wantWidth
{
    if ([theView isKindOfClass:[SessionView class]]) {
        SessionView* sessionView = (SessionView*)theView;
        if (wantWidth) {
            return [[[sessionView session] TEXTVIEW] charWidth];
        } else {
            return [[[sessionView session] TEXTVIEW] lineHeight];
        }
    } else {
        CGFloat maxStep = 0;
        for (NSView* subview in [theView subviews]) {
            CGFloat step = [self _recursiveStepSize:subview wantWidth:wantWidth];
            maxStep = MAX(maxStep, step);
        }
        return maxStep;
    }
}

// Make splitters jump by char widths/line heights. If there is a difference,
// pick the largest on either side of the divider.
- (CGFloat)splitView:(NSSplitView *)splitView constrainSplitPosition:(CGFloat)proposedPosition ofSubviewAt:(NSInteger)dividerIndex
{
    if (tmuxOriginatedResizeInProgress_) {
        return proposedPosition;
    }
    PtyLog(@"PTYTab splitView:constraintSplitPosition%f divider:%d case ", (float)proposedPosition, dividerIndex);
    NSArray* subviews = [splitView subviews];
    NSView* childBefore = [subviews objectAtIndex:dividerIndex];
    NSView* childAfter = [subviews objectAtIndex:dividerIndex + 1];
    CGFloat beforeStep = [self _recursiveStepSize:childBefore wantWidth:[splitView isVertical]];
    CGFloat afterStep = [self _recursiveStepSize:childAfter wantWidth:[splitView isVertical]];
    CGFloat step = MAX(beforeStep, afterStep);

    NSRect beforeRect = [childBefore frame];
    CGFloat originalPosition;
    if ([splitView isVertical]) {
        originalPosition = beforeRect.origin.x + beforeRect.size.width;
    } else {
        originalPosition = beforeRect.origin.y + beforeRect.size.height;
    }
    CGFloat diff = fabs(proposedPosition - originalPosition);
    int chars = diff / step;
    CGFloat allowedDiff = chars * step;
    if (proposedPosition < originalPosition) {
        allowedDiff *= -1;
    }
    return originalPosition + allowedDiff;
}

@end

@implementation PTYTab (Private)

- (void)_setLabelAttributesForDeadSession
{
    [parentWindow_ setLabelColor:deadStateColor
                 forTabViewItem:tabViewItem_];
    if ([self isProcessing]) {
        [self setIsProcessing:NO];
    }
}

- (BOOL)_windowResizedRecently
{
    NSDate *lastResize = [realParentWindow_ lastResizeTime];
    double elapsed = [[NSDate date] timeIntervalSinceDate:lastResize];
    return elapsed < (2 * kBackgroundSessionIntervalSec);
}

- (void)_setLabelAttributesForIdleBackgroundTabAtTime:(struct timeval)now
{
    if ([self isProcessing]) {
        [self setIsProcessing:NO];
    }

    for (PTYSession* session in [self sessions]) {
        if ([session newOutput]) {
            // Idle after new output
            if (![session growlIdle] &&
                [[session SCREEN] growl] &&
                [[NSDate date] timeIntervalSinceDate:[SessionView lastResizeDate]] > POST_WINDOW_RESIZE_SILENCE_SEC &&
                now.tv_sec > [session lastOutput].tv_sec + 1) {
                [[iTermGrowlDelegate sharedInstance] growlNotify:NSLocalizedStringFromTableInBundle(@"Idle",
                                                                                                    @"iTerm",
                                                                                                    [NSBundle bundleForClass:[self class]],
                                                                                                    @"Growl Alerts")
                                                 withDescription:[NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"Session %@ in tab #%d became idle.",
                                                                                                                               @"iTerm",
                                                                                                                               [NSBundle bundleForClass:[self class]],
                                                                                                                               @"Growl Alerts"),
                                                                  [[self activeSession] name],
                                                                  [self realObjectCount]]
                                                 andNotification:@"Idle"
                                                      andSession:session];
                [session setGrowlIdle:YES];
                [session setGrowlNewOutput:NO];
            }
            [parentWindow_ setLabelColor:idleStateColor
                          forTabViewItem:tabViewItem_];
        } else {
            // normal state
            [parentWindow_ setLabelColor:normalStateColor
                          forTabViewItem:tabViewItem_];
        }
    }
}

- (void)_setLabelAttributesForActiveBackgroundTab
{
    if ([self isProcessing] == NO &&
        ![[PreferencePanel sharedInstance] useCompactLabel]) {
        [self setIsProcessing:YES];
    }

    if (![[self activeSession] growlNewOutput] &&
        [[self realParentWindow] broadcastMode] == BROADCAST_OFF &&
        [[[self activeSession] SCREEN] growl] &&
        [[NSDate date] timeIntervalSinceDate:[SessionView lastResizeDate]] > POST_WINDOW_RESIZE_SILENCE_SEC) {
        [[iTermGrowlDelegate sharedInstance] growlNotify:NSLocalizedStringFromTableInBundle(