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

#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include "llaccordionctrltab.h"
#include "llagent.h"
#include "llagentcamera.h"
#include "llagentwearables.h"
#include "llappearancemgr.h"
#include "llattachmentsmgr.h"
#include "llcommandhandler.h"
#include "lleventtimer.h"
#include "llfloatersidepanelcontainer.h"
#include "llgesturemgr.h"
#include "llinventorybridge.h"
#include "llinventoryfunctions.h"
#include "llinventoryobserver.h"
#include "llnotificationsutil.h"
#include "lloutfitobserver.h"
#include "lloutfitslist.h"
#include "llselectmgr.h"
#include "llsidepanelappearance.h"
#include "llviewerobjectlist.h"
#include "llvoavatar.h"
#include "llvoavatarself.h"
#include "llviewerregion.h"
#include "llwearablelist.h"
#include "llsdutil.h"
#include "llsdserialize.h"
#include "llhttpretrypolicy.h"
#include "llaisapi.h"
#include "llhttpsdhandler.h"
#include "llcorehttputil.h"
#include "llappviewer.h"
#include "llcoros.h"
#include "lleventcoro.h"

#include "llavatarpropertiesprocessor.h"

#if LL_MSVC
// disable boost::lexical_cast warning
#pragma warning (disable:4702)
#endif

namespace 
{
    const S32   BAKE_RETRY_MAX_COUNT = 5;
    const F32   BAKE_RETRY_TIMEOUT = 2.0F;
}

// *TODO$: LLInventoryCallback should be deprecated to conform to the new boost::bind/coroutine model.
// temp code in transition
void doAppearanceCb(LLPointer<LLInventoryCallback> cb, LLUUID id)
{
    if (cb.notNull())
        cb->fire(id);
}

std::string self_av_string()
{
	// On logout gAgentAvatarp can already be invalid
	return isAgentAvatarValid() ? gAgentAvatarp->avString() : "";
}

// RAII thingy to guarantee that a variable gets reset when the Setter
// goes out of scope.  More general utility would be handy - TODO:
// check boost.
class BoolSetter
{
public:
	BoolSetter(bool& var):
		mVar(var)
	{
		mVar = true;
	}
	~BoolSetter()
	{
		mVar = false; 
	}
private:
	bool& mVar;
};

char ORDER_NUMBER_SEPARATOR('@');

class LLOutfitUnLockTimer: public LLEventTimer
{
public:
	LLOutfitUnLockTimer(F32 period) : LLEventTimer(period)
	{
		// restart timer on BOF changed event
		LLOutfitObserver::instance().addBOFChangedCallback(boost::bind(
				&LLOutfitUnLockTimer::reset, this));
		stop();
	}

	/*virtual*/
	BOOL tick()
	{
		if(mEventTimer.hasExpired())
		{
			LLAppearanceMgr::instance().setOutfitLocked(false);
		}
		return FALSE;
	}
	void stop() { mEventTimer.stop(); }
	void start() { mEventTimer.start(); }
	void reset() { mEventTimer.reset(); }
	BOOL getStarted() { return mEventTimer.getStarted(); }

	LLTimer&  getEventTimer() { return mEventTimer;}
};

// support for secondlife:///app/appearance SLapps
class LLAppearanceHandler : public LLCommandHandler
{
public:
	// requests will be throttled from a non-trusted browser
	LLAppearanceHandler() : LLCommandHandler("appearance", UNTRUSTED_THROTTLE) {}

	bool handle(const LLSD& params, const LLSD& query_map, LLMediaCtrl* web)
	{
		// support secondlife:///app/appearance/show, but for now we just
		// make all secondlife:///app/appearance SLapps behave this way
		if (!LLUI::getInstance()->mSettingGroups["config"]->getBOOL("EnableAppearance"))
		{
			LLNotificationsUtil::add("NoAppearance", LLSD(), LLSD(), std::string("SwitchToStandardSkinAndQuit"));
			return true;
		}

		LLFloaterSidePanelContainer::showPanel("appearance", LLSD());
		return true;
	}
};

LLAppearanceHandler gAppearanceHandler;


LLUUID findDescendentCategoryIDByName(const LLUUID& parent_id, const std::string& name)
{
	LLInventoryModel::cat_array_t cat_array;
	LLInventoryModel::item_array_t item_array;
	LLNameCategoryCollector has_name(name);
	gInventory.collectDescendentsIf(parent_id,
									cat_array,
									item_array,
									LLInventoryModel::EXCLUDE_TRASH,
									has_name);
	if (0 == cat_array.size())
		return LLUUID();
	else
	{
		LLViewerInventoryCategory *cat = cat_array.at(0);
		if (cat)
			return cat->getUUID();
		else
		{
			LL_WARNS() << "null cat" << LL_ENDL;
			return LLUUID();
		}
	}
}

// We want this to be much lower (e.g. 15.0 is usually fine), bumping
// up for now until we can diagnose some cases of very slow response
// to requests.
const F32 DEFAULT_RETRY_AFTER_INTERVAL = 300.0;

// Given the current back-end problems, retrying is causing too many
// duplicate items. Bump this back to 2 once they are resolved (or can
// leave at 0 if the operations become actually reliable).
const S32 DEFAULT_MAX_RETRIES = 0;

class LLCallAfterInventoryBatchMgr: public LLEventTimer 
{
public:
	LLCallAfterInventoryBatchMgr(const LLUUID& dst_cat_id,
								 const std::string& phase_name,
								 nullary_func_t on_completion_func,
								 nullary_func_t on_failure_func = no_op,
								 F32 retry_after = DEFAULT_RETRY_AFTER_INTERVAL,
								 S32 max_retries = DEFAULT_MAX_RETRIES
		):
		mDstCatID(dst_cat_id),
		mTrackingPhase(phase_name),
		mOnCompletionFunc(on_completion_func),
		mOnFailureFunc(on_failure_func),
		mRetryAfter(retry_after),
		mMaxRetries(max_retries),
		mPendingRequests(0),
		mFailCount(0),
		mCompletionOrFailureCalled(false),
		mRetryCount(0),
		LLEventTimer(5.0)
	{
		if (!mTrackingPhase.empty())
		{
			selfStartPhase(mTrackingPhase);
		}
	}

	void addItems(LLInventoryModel::item_array_t& src_items)
	{
		for (LLInventoryModel::item_array_t::const_iterator it = src_items.begin();
			 it != src_items.end();
			 ++it)
		{
			LLViewerInventoryItem* item = *it;
			llassert(item);
			addItem(item->getUUID());
		}
	}

	// Request or re-request operation for specified item.
	void addItem(const LLUUID& item_id)
	{
		LL_DEBUGS("Avatar") << "item_id " << item_id << LL_ENDL;
		if (!requestOperation(item_id))
		{
			LL_DEBUGS("Avatar") << "item_id " << item_id << " requestOperation false, skipping" << LL_ENDL;
			return;
		}

		mPendingRequests++;
		// On a re-request, this will reset the timer.
		mWaitTimes[item_id] = LLTimer();
		if (mRetryCounts.find(item_id) == mRetryCounts.end())
		{
			mRetryCounts[item_id] = 0;
		}
		else
		{
			mRetryCounts[item_id]++;
		}
	}

	virtual bool requestOperation(const LLUUID& item_id) = 0;

	void onOp(const LLUUID& src_id, const LLUUID& dst_id, LLTimer timestamp)
	{
		if (ll_frand() < gSavedSettings.getF32("InventoryDebugSimulateLateOpRate"))
		{
			LL_WARNS() << "Simulating late operation by punting handling to later" << LL_ENDL;
			doAfterInterval(boost::bind(&LLCallAfterInventoryBatchMgr::onOp,this,src_id,dst_id,timestamp),
							mRetryAfter);
			return;
		}
		mPendingRequests--;
		F32 elapsed = timestamp.getElapsedTimeF32();
		LL_DEBUGS("Avatar") << "op done, src_id " << src_id << " dst_id " << dst_id << " after " << elapsed << " seconds" << LL_ENDL;
		if (mWaitTimes.find(src_id) == mWaitTimes.end())
		{
			// No longer waiting for this item - either serviced
			// already or gave up after too many retries.
			LL_WARNS() << "duplicate or late operation, src_id " << src_id << "dst_id " << dst_id
					<< " elapsed " << elapsed << " after end " << (S32) mCompletionOrFailureCalled << LL_ENDL;
		}
		mTimeStats.push(elapsed);
		mWaitTimes.erase(src_id);
		if (mWaitTimes.empty() && !mCompletionOrFailureCalled)
		{
			onCompletionOrFailure();
		}
	}

	void onCompletionOrFailure()
	{
		assert (!mCompletionOrFailureCalled);
		mCompletionOrFailureCalled = true;
		
		// Will never call onCompletion() if any item has been flagged as
		// a failure - otherwise could wind up with corrupted
		// outfit, involuntary nudity, etc.
		reportStats();
		if (!mTrackingPhase.empty())
		{
			selfStopPhase(mTrackingPhase);
		}
		if (!mFailCount)
		{
			onCompletion();
		}
		else
		{
			onFailure();
		}
	}

	void onFailure()
	{
		LL_INFOS() << "failed" << LL_ENDL;
		mOnFailureFunc();
	}

	void onCompletion()
	{
		LL_INFOS() << "done" << LL_ENDL;
		mOnCompletionFunc();
	}
	
	// virtual
	// Will be deleted after returning true - only safe to do this if all callbacks have fired.
	BOOL tick()
	{
		// mPendingRequests will be zero if all requests have been
		// responded to.  mWaitTimes.empty() will be true if we have
		// received at least one reply for each UUID.  If requests
		// have been dropped and retried, these will not necessarily
		// be the same.  Only safe to return true if all requests have
		// been serviced, since it will result in this object being
		// deleted.
		bool all_done = (mPendingRequests==0);

		if (!mWaitTimes.empty())
		{
			LL_WARNS() << "still waiting on " << mWaitTimes.size() << " items" << LL_ENDL;
			for (std::map<LLUUID,LLTimer>::iterator it = mWaitTimes.begin();
				 it != mWaitTimes.end();)
			{
				// Use a copy of iterator because it may be erased/invalidated.
				std::map<LLUUID,LLTimer>::iterator curr_it = it;
				++it;
				
				F32 time_waited = curr_it->second.getElapsedTimeF32();
				S32 retries = mRetryCounts[curr_it->first];
				if (time_waited > mRetryAfter)
				{
					if (retries < mMaxRetries)
					{
						LL_DEBUGS("Avatar") << "Waited " << time_waited <<
							" for " << curr_it->first << ", retrying" << LL_ENDL;
						mRetryCount++;
						addItem(curr_it->first);
					}
					else
					{
						LL_WARNS() << "Giving up on " << curr_it->first << " after too many retries" << LL_ENDL;
						mWaitTimes.erase(curr_it);
						mFailCount++;
					}
				}
				if (mWaitTimes.empty())
				{
					onCompletionOrFailure();
				}

			}
		}
		return all_done;
	}

	void reportStats()
	{
		LL_DEBUGS("Avatar") << "Phase: " << mTrackingPhase << LL_ENDL;
		LL_DEBUGS("Avatar") << "mFailCount: " << mFailCount << LL_ENDL;
		LL_DEBUGS("Avatar") << "mRetryCount: " << mRetryCount << LL_ENDL;
		LL_DEBUGS("Avatar") << "Times: n " << mTimeStats.getCount() << " min " << mTimeStats.getMinValue() << " max " << mTimeStats.getMaxValue() << LL_ENDL;
		LL_DEBUGS("Avatar") << "Mean " << mTimeStats.getMean() << " stddev " << mTimeStats.getStdDev() << LL_ENDL;
	}
	
	virtual ~LLCallAfterInventoryBatchMgr()
	{
		LL_DEBUGS("Avatar") << "deleting" << LL_ENDL;
	}

protected:
	std::string mTrackingPhase;
	std::map<LLUUID,LLTimer> mWaitTimes;
	std::map<LLUUID,S32> mRetryCounts;
	LLUUID mDstCatID;
	nullary_func_t mOnCompletionFunc;
	nullary_func_t mOnFailureFunc;
	F32 mRetryAfter;
	S32 mMaxRetries;
	S32 mPendingRequests;
	S32 mFailCount;
	S32 mRetryCount;
	bool mCompletionOrFailureCalled;
	LLViewerStats::StatsAccumulator mTimeStats;
};

class LLCallAfterInventoryCopyMgr: public LLCallAfterInventoryBatchMgr
{
public:
	LLCallAfterInventoryCopyMgr(LLInventoryModel::item_array_t& src_items,
								const LLUUID& dst_cat_id,
								const std::string& phase_name,
								nullary_func_t on_completion_func,
								nullary_func_t on_failure_func = no_op,
								 F32 retry_after = DEFAULT_RETRY_AFTER_INTERVAL,
								 S32 max_retries = DEFAULT_MAX_RETRIES
		):
		LLCallAfterInventoryBatchMgr(dst_cat_id, phase_name, on_completion_func, on_failure_func, retry_after, max_retries)
	{
		addItems(src_items);
		sInstanceCount++;
	}

	~LLCallAfterInventoryCopyMgr()
	{
		sInstanceCount--;
	}
	
	virtual bool requestOperation(const LLUUID& item_id)
	{
		LLViewerInventoryItem *item = gInventory.getItem(item_id);
		llassert(item);
		LL_DEBUGS("Avatar") << "copying item " << item_id << LL_ENDL;
		if (ll_frand() < gSavedSettings.getF32("InventoryDebugSimulateOpFailureRate"))
		{
			LL_DEBUGS("Avatar") << "simulating failure by not sending request for item " << item_id << LL_ENDL;
			return true;
		}
		copy_inventory_item(
			gAgent.getID(),
			item->getPermissions().getOwner(),
			item->getUUID(),
			mDstCatID,
			std::string(),
			new LLBoostFuncInventoryCallback(boost::bind(&LLCallAfterInventoryBatchMgr::onOp,this,item_id,_1,LLTimer()))
			);
		return true;
	}

	static S32 getInstanceCount() { return sInstanceCount; }
	
private:
	static S32 sInstanceCount;
};

S32 LLCallAfterInventoryCopyMgr::sInstanceCount = 0;

class LLWearCategoryAfterCopy: public LLInventoryCallback
{
public:
	LLWearCategoryAfterCopy(bool append):
		mAppend(append)
	{}

	// virtual
	void fire(const LLUUID& id)
	{
		// Wear the inventory category.
		LLInventoryCategory* cat = gInventory.getCategory(id);
		LLAppearanceMgr::instance().wearInventoryCategoryOnAvatar(cat, mAppend);
	}

private:
	bool mAppend;
};

class LLTrackPhaseWrapper : public LLInventoryCallback
{
public:
	LLTrackPhaseWrapper(const std::string& phase_name, LLPointer<LLInventoryCallback> cb = NULL):
		mTrackingPhase(phase_name),
		mCB(cb)
	{
		selfStartPhase(mTrackingPhase);
	}

	// virtual
	void fire(const LLUUID& id)
	{
		if (mCB)
		{
			mCB->fire(id);
		}
	}

	// virtual
	~LLTrackPhaseWrapper()
	{
		selfStopPhase(mTrackingPhase);
	}

protected:
	std::string mTrackingPhase;
	LLPointer<LLInventoryCallback> mCB;
};

LLUpdateAppearanceOnDestroy::LLUpdateAppearanceOnDestroy(bool enforce_item_restrictions,
														 bool enforce_ordering,
														 nullary_func_t post_update_func 
	):
	mFireCount(0),
	mEnforceItemRestrictions(enforce_item_restrictions),
	mEnforceOrdering(enforce_ordering),
	mPostUpdateFunc(post_update_func)
{
	selfStartPhase("update_appearance_on_destroy");
}

void LLUpdateAppearanceOnDestroy::fire(const LLUUID& inv_item)
{
	LLViewerInventoryItem* item = (LLViewerInventoryItem*)gInventory.getItem(inv_item);
	const std::string item_name = item ? item->getName() : "ITEM NOT FOUND";
#ifndef LL_RELEASE_FOR_DOWNLOAD
	LL_DEBUGS("Avatar") << self_av_string() << "callback fired [ name:" << item_name << " UUID:" << inv_item << " count:" << mFireCount << " ] " << LL_ENDL;
#endif
	mFireCount++;
}

LLUpdateAppearanceOnDestroy::~LLUpdateAppearanceOnDestroy()
{
	if (!LLApp::isExiting())
	{
		// speculative fix for MAINT-1150
		LL_INFOS("Avatar") << self_av_string() << "done update appearance on destroy" << LL_ENDL;

		selfStopPhase("update_appearance_on_destroy");

		LLAppearanceMgr::instance().updateAppearanceFromCOF(mEnforceItemRestrictions,
															mEnforceOrdering,
															mPostUpdateFunc);
	}
}

LLUpdateAppearanceAndEditWearableOnDestroy::LLUpdateAppearanceAndEditWearableOnDestroy(const LLUUID& item_id):
	mItemID(item_id)
{
}

LLRequestServerAppearanceUpdateOnDestroy::~LLRequestServerAppearanceUpdateOnDestroy()
{
	LL_DEBUGS("Avatar") << "ATT requesting server appearance update" << LL_ENDL;
    if (!LLApp::isExiting())
    {
        LLAppearanceMgr::instance().requestServerAppearanceUpdate();
    }
}

void edit_wearable_and_customize_avatar(LLUUID item_id)
{
	// Start editing the item if previously requested.
	gAgentWearables.editWearableIfRequested(item_id);
	
	// TODO: camera mode may not be changed if a debug setting is tweaked
	if( gAgentCamera.cameraCustomizeAvatar() )
	{
		// If we're in appearance editing mode, the current tab may need to be refreshed
		LLSidepanelAppearance *panel = dynamic_cast<LLSidepanelAppearance*>(
			LLFloaterSidePanelContainer::getPanel("appearance"));
		if (panel)
		{
			panel->showDefaultSubpart();
		}
	}
}

LLUpdateAppearanceAndEditWearableOnDestroy::~LLUpdateAppearanceAndEditWearableOnDestroy()
{
	if (!LLApp::isExiting())
	{
		LLAppearanceMgr::instance().updateAppearanceFromCOF(
			true,true,
			boost::bind(edit_wearable_and_customize_avatar, mItemID));
	}
}


struct LLFoundData
{
	LLFoundData() :
		mAssetType(LLAssetType::AT_NONE),
		mWearableType(LLWearableType::WT_INVALID),
		mWearable(NULL) {}

	LLFoundData(const LLUUID& item_id,
				const LLUUID& asset_id,
				const std::string& name,
				const LLAssetType::EType& asset_type,
				const LLWearableType::EType& wearable_type,
				const bool is_replacement = false
		) :
		mItemID(item_id),
		mAssetID(asset_id),
		mName(name),
		mAssetType(asset_type),
		mWearableType(wearable_type),
		mIsReplacement(is_replacement),
		mWearable( NULL ) {}
	
	LLUUID mItemID;
	LLUUID mAssetID;
	std::string mName;
	LLAssetType::EType mAssetType;
	LLWearableType::EType mWearableType;
	LLViewerWearable* mWearable;
	bool mIsReplacement;
};

	
class LLWearableHoldingPattern
{
	LOG_CLASS(LLWearableHoldingPattern);

public:
	LLWearableHoldingPattern();
	~LLWearableHoldingPattern();

	bool pollFetchCompletion();
	void onFetchCompletion();
	bool isFetchCompleted();
	bool isTimedOut();

	void checkMissingWearables();
	bool pollMissingWearables();
	bool isMissingCompleted();
	void recoverMissingWearable(LLWearableType::EType type);
	void clearCOFLinksForMissingWearables();
	
	void onWearableAssetFetch(LLViewerWearable *wearable);
	void onAllComplete();

	typedef std::list<LLFoundData> found_list_t;
	found_list_t& getFoundList();
	void eraseTypeToLink(LLWearableType::EType type);
	void eraseTypeToRecover(LLWearableType::EType type);
	void setObjItems(const LLInventoryModel::item_array_t& items);
	void setGestItems(const LLInventoryModel::item_array_t& items);
	bool isMostRecent();
	void handleLateArrivals();
	void resetTime(F32 timeout);
	static S32 countActive() { return sActiveHoldingPatterns.size(); }
	S32 index() { return mIndex; }
	
private:
	found_list_t mFoundList;
	LLInventoryModel::item_array_t mObjItems;
	LLInventoryModel::item_array_t mGestItems;
	typedef std::set<S32> type_set_t;
	type_set_t mTypesToRecover;
	type_set_t mTypesToLink;
	S32 mResolved;
	LLTimer mWaitTime;
	bool mFired;
	typedef std::set<LLWearableHoldingPattern*> type_set_hp;
	static type_set_hp sActiveHoldingPatterns;
	static S32 sNextIndex;
	S32 mIndex;
	bool mIsMostRecent;
	std::set<LLViewerWearable*> mLateArrivals;
	bool mIsAllComplete;
};

LLWearableHoldingPattern::type_set_hp LLWearableHoldingPattern::sActiveHoldingPatterns;
S32 LLWearableHoldingPattern::sNextIndex = 0;

LLWearableHoldingPattern::LLWearableHoldingPattern():
	mResolved(0),
	mFired(false),
	mIsMostRecent(true),
	mIsAllComplete(false)
{
	if (countActive()>0)
	{
		LL_INFOS() << "Creating LLWearableHoldingPattern when "
				   << countActive()
				   << " other attempts are active."
				   << " Flagging others as invalid."
				   << LL_ENDL;
		for (type_set_hp::iterator it = sActiveHoldingPatterns.begin();
			 it != sActiveHoldingPatterns.end();
			 ++it)
		{
			(*it)->mIsMostRecent = false;
		}
			 
	}
	mIndex = sNextIndex++;
	sActiveHoldingPatterns.insert(this);
	LL_DEBUGS("Avatar") << "HP " << index() << " created" << LL_ENDL;
	selfStartPhase("holding_pattern");
}

LLWearableHoldingPattern::~LLWearableHoldingPattern()
{
	sActiveHoldingPatterns.erase(this);
	if (isMostRecent())
	{
		selfStopPhase("holding_pattern");
	}
	LL_DEBUGS("Avatar") << "HP " << index() << " deleted" << LL_ENDL;
}

bool LLWearableHoldingPattern::isMostRecent()
{
	return mIsMostRecent;
}

LLWearableHoldingPattern::found_list_t& LLWearableHoldingPattern::getFoundList()
{
	return mFoundList;
}

void LLWearableHoldingPattern::eraseTypeToLink(LLWearableType::EType type)
{
	mTypesToLink.erase(type);
}

void LLWearableHoldingPattern::eraseTypeToRecover(LLWearableType::EType type)
{
	mTypesToRecover.erase(type);
}

void LLWearableHoldingPattern::setObjItems(const LLInventoryModel::item_array_t& items)
{
	mObjItems = items;
}

void LLWearableHoldingPattern::setGestItems(const LLInventoryModel::item_array_t& items)
{
	mGestItems = items;
}

bool LLWearableHoldingPattern::isFetchCompleted()
{
	return (mResolved >= (S32)getFoundList().size()); // have everything we were waiting for?
}

bool LLWearableHoldingPattern::isTimedOut()
{
	return mWaitTime.hasExpired();
}

void LLWearableHoldingPattern::checkMissingWearables()
{
	if (!isMostRecent())
	{
		// runway why don't we actually skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}

	std::vector<S32> found_by_type(LLWearableType::WT_COUNT,0);
	std::vector<S32> requested_by_type(LLWearableType::WT_COUNT,0);
	for (found_list_t::iterator it = getFoundList().begin(); it != getFoundList().end(); ++it)
	{
		LLFoundData &data = *it;
		if (data.mWearableType < LLWearableType::WT_COUNT)
			requested_by_type[data.mWearableType]++;
		if (data.mWearable)
			found_by_type[data.mWearableType]++;
	}

	for (S32 type = 0; type < LLWearableType::WT_COUNT; ++type)
	{
		if (requested_by_type[type] > found_by_type[type])
		{
			LL_WARNS() << self_av_string() << "got fewer wearables than requested, type " << type << ": requested " << requested_by_type[type] << ", found " << found_by_type[type] << LL_ENDL;
		}
		if (found_by_type[type] > 0)
			continue;
		if (
			// If at least one wearable of certain types (pants/shirt/skirt)
			// was requested but none was found, create a default asset as a replacement.
			// In all other cases, don't do anything.
			// For critical types (shape/hair/skin/eyes), this will keep the avatar as a cloud 
			// due to logic in LLVOAvatarSelf::getIsCloud().
			// For non-critical types (tatoo, socks, etc.) the wearable will just be missing.
			(requested_by_type[type] > 0) &&  
			((type == LLWearableType::WT_PANTS) || (type == LLWearableType::WT_SHIRT) || (type == LLWearableType::WT_SKIRT)))
		{
			mTypesToRecover.insert(type);
			mTypesToLink.insert(type);
			recoverMissingWearable((LLWearableType::EType)type);
			LL_WARNS() << self_av_string() << "need to replace " << type << LL_ENDL; 
		}
	}

	resetTime(60.0F);

	if (isMostRecent())
	{
		selfStartPhase("get_missing_wearables_2");
	}
	if (!pollMissingWearables())
	{
		doOnIdleRepeating(boost::bind(&LLWearableHoldingPattern::pollMissingWearables,this));
	}
}

void LLWearableHoldingPattern::onAllComplete()
{
	if (isAgentAvatarValid())
	{
		gAgentAvatarp->outputRezTiming("Agent wearables fetch complete");
	}

	if (!isMostRecent())
	{
		// runway need to skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}

	// Activate all gestures in this folder
	if (mGestItems.size() > 0)
	{
		LL_DEBUGS("Avatar") << self_av_string() << "Activating " << mGestItems.size() << " gestures" << LL_ENDL;
		
		LLGestureMgr::instance().activateGestures(mGestItems);
		
		// Update the inventory item labels to reflect the fact
		// they are active.
		LLViewerInventoryCategory* catp =
			gInventory.getCategory(LLAppearanceMgr::instance().getCOF());
		
		if (catp)
		{
			gInventory.updateCategory(catp);
			gInventory.notifyObservers();
		}
	}

	if (isAgentAvatarValid())
	{
		LL_DEBUGS("Avatar") << self_av_string() << "Updating " << mObjItems.size() << " attachments" << LL_ENDL;
		LLAgentWearables::llvo_vec_t objects_to_remove;
		LLAgentWearables::llvo_vec_t objects_to_retain;
		LLInventoryModel::item_array_t items_to_add;

		LLAgentWearables::findAttachmentsAddRemoveInfo(mObjItems,
													   objects_to_remove,
													   objects_to_retain,
													   items_to_add);

		LL_DEBUGS("Avatar") << self_av_string() << "Removing " << objects_to_remove.size()
							<< " attachments" << LL_ENDL;

		// Here we remove the attachment pos overrides for *all*
		// attachments, even those that are not being removed. This is
		// needed to get joint positions all slammed down to their
		// pre-attachment states.
		gAgentAvatarp->clearAttachmentOverrides();

		if (objects_to_remove.size() || items_to_add.size())
		{
			LL_DEBUGS("Avatar") << "ATT will remove " << objects_to_remove.size()
								<< " and add " << items_to_add.size() << " items" << LL_ENDL;
		}

		// Take off the attachments that will no longer be in the outfit.
		LLAgentWearables::userRemoveMultipleAttachments(objects_to_remove);
		
		// Update wearables.
		LL_INFOS("Avatar") << self_av_string() << "HP " << index() << " updating agent wearables with "
						   << mResolved << " wearable items " << LL_ENDL;
		LLAppearanceMgr::instance().updateAgentWearables(this);
		
		// Restore attachment pos overrides for the attachments that
		// are remaining in the outfit.
		for (LLAgentWearables::llvo_vec_t::iterator it = objects_to_retain.begin();
			 it != objects_to_retain.end();
			 ++it)
		{
			LLViewerObject *objectp = *it;
            if (!objectp->isAnimatedObject())
            {
                gAgentAvatarp->addAttachmentOverridesForObject(objectp);
            }
		}
		
		// Add new attachments to match those requested.
		LL_DEBUGS("Avatar") << self_av_string() << "Adding " << items_to_add.size() << " attachments" << LL_ENDL;
		LLAgentWearables::userAttachMultipleAttachments(items_to_add);
	}

	if (isFetchCompleted() && isMissingCompleted())
	{
		// Only safe to delete if all wearable callbacks and all missing wearables completed.
		delete this;
	}
	else
	{
		mIsAllComplete = true;
		handleLateArrivals();
	}
}

void LLWearableHoldingPattern::onFetchCompletion()
{
	if (isMostRecent())
	{
		selfStopPhase("get_wearables_2");
	}
		
	if (!isMostRecent())
	{
		// runway skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}

	checkMissingWearables();
}

// Runs as an idle callback until all wearables are fetched (or we time out).
bool LLWearableHoldingPattern::pollFetchCompletion()
{
	if (!isMostRecent())
	{
		// runway skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}

	bool completed = isFetchCompleted();
	bool timed_out = isTimedOut();
	bool done = completed || timed_out;

	if (done)
	{
		LL_INFOS("Avatar") << self_av_string() << "HP " << index() << " polling, done status: " << completed << " timed out " << timed_out
				<< " elapsed " << mWaitTime.getElapsedTimeF32() << LL_ENDL;

		mFired = true;
		
		if (timed_out)
		{
			LL_WARNS() << self_av_string() << "Exceeded max wait time for wearables, updating appearance based on what has arrived" << LL_ENDL;
		}

		onFetchCompletion();
	}
	return done;
}

void recovered_item_link_cb(const LLUUID& item_id, LLWearableType::EType type, LLViewerWearable *wearable, LLWearableHoldingPattern* holder)
{
	if (!holder->isMostRecent())
	{
		LL_WARNS() << "HP " << holder->index() << " skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
		// runway skip here?
	}

	LL_INFOS() << "HP " << holder->index() << " recovered item link for type " << type << LL_ENDL;
	holder->eraseTypeToLink(type);
	// Add wearable to FoundData for actual wearing
	LLViewerInventoryItem *item = gInventory.getItem(item_id);
	LLViewerInventoryItem *linked_item = item ? item->getLinkedItem() : NULL;

	if (linked_item)
	{
		gInventory.addChangedMask(LLInventoryObserver::LABEL, linked_item->getUUID());
			
		if (item)
		{
			LLFoundData found(linked_item->getUUID(),
							  linked_item->getAssetUUID(),
							  linked_item->getName(),
							  linked_item->getType(),
							  linked_item->isWearableType() ? linked_item->getWearableType() : LLWearableType::WT_INVALID,
							  true // is replacement
				);
			found.mWearable = wearable;
			holder->getFoundList().push_front(found);
		}
		else
		{
			LL_WARNS() << self_av_string() << "inventory link not found for recovered wearable" << LL_ENDL;
		}
	}
	else
	{
		LL_WARNS() << self_av_string() << "HP " << holder->index() << " inventory link not found for recovered wearable" << LL_ENDL;
	}
}

void recovered_item_cb(const LLUUID& item_id, LLWearableType::EType type, LLViewerWearable *wearable, LLWearableHoldingPattern* holder)
{
	if (!holder->isMostRecent())
	{
		// runway skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}

	LL_DEBUGS("Avatar") << self_av_string() << "Recovered item for type " << type << LL_ENDL;
	LLConstPointer<LLInventoryObject> itemp = gInventory.getItem(item_id);
	wearable->setItemID(item_id);
	holder->eraseTypeToRecover(type);
	llassert(itemp);
	if (itemp)
	{
		LLPointer<LLInventoryCallback> cb = new LLBoostFuncInventoryCallback(boost::bind(recovered_item_link_cb,_1,type,wearable,holder));

		link_inventory_object(LLAppearanceMgr::instance().getCOF(), itemp, cb);
	}
}

void LLWearableHoldingPattern::recoverMissingWearable(LLWearableType::EType type)
{
	if (!isMostRecent())
	{
		// runway skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}
	
		// Try to recover by replacing missing wearable with a new one.
	LLNotificationsUtil::add("ReplacedMissingWearable");
	LL_DEBUGS() << "Wearable " << LLWearableType::getTypeLabel(type)
				<< " could not be downloaded.  Replaced inventory item with default wearable." << LL_ENDL;
	LLViewerWearable* wearable = LLWearableList::instance().createNewWearable(type, gAgentAvatarp);

	// Add a new one in the lost and found folder.
	const LLUUID lost_and_found_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_LOST_AND_FOUND);
	LLPointer<LLInventoryCallback> cb = new LLBoostFuncInventoryCallback(boost::bind(recovered_item_cb,_1,type,wearable,this));

	create_inventory_item(gAgent.getID(),
						  gAgent.getSessionID(),
						  lost_and_found_id,
						  wearable->getTransactionID(),
						  wearable->getName(),
						  wearable->getDescription(),
						  wearable->getAssetType(),
						  LLInventoryType::IT_WEARABLE,
						  wearable->getType(),
						  wearable->getPermissions().getMaskNextOwner(),
						  cb);
}

bool LLWearableHoldingPattern::isMissingCompleted()
{
	return mTypesToLink.size()==0 && mTypesToRecover.size()==0;
}

void LLWearableHoldingPattern::clearCOFLinksForMissingWearables()
{
	for (found_list_t::iterator it = getFoundList().begin(); it != getFoundList().end(); ++it)
	{
		LLFoundData &data = *it;
		if ((data.mWearableType < LLWearableType::WT_COUNT) && (!data.mWearable))
		{
			// Wearable link that was never resolved; remove links to it from COF
			LL_INFOS("Avatar") << self_av_string() << "HP " << index() << " removing link for unresolved item " << data.mItemID.asString() << LL_ENDL;
			LLAppearanceMgr::instance().removeCOFItemLinks(data.mItemID);
		}
	}
}

bool LLWearableHoldingPattern::pollMissingWearables()
{
	if (!isMostRecent())
	{
		// runway skip here?
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}
	
	bool timed_out = isTimedOut();
	bool missing_completed = isMissingCompleted();
	bool done = timed_out || missing_completed;

	if (!done)
	{
		LL_INFOS("Avatar") << self_av_string() << "HP " << index() << " polling missing wearables, waiting for items " << mTypesToRecover.size()
				<< " links " << mTypesToLink.size()
				<< " wearables, timed out " << timed_out
				<< " elapsed " << mWaitTime.getElapsedTimeF32()
				<< " done " << done << LL_ENDL;
	}

	if (done)
	{
		if (isMostRecent())
		{
			selfStopPhase("get_missing_wearables_2");
		}

		gAgentAvatarp->debugWearablesLoaded();

		// BAP - if we don't call clearCOFLinksForMissingWearables()
		// here, we won't have to add the link back in later if the
		// wearable arrives late.  This is to avoid corruption of
		// wearable ordering info.  Also has the effect of making
		// unworn item links visible in the COF under some
		// circumstances.

		//clearCOFLinksForMissingWearables();
		onAllComplete();
	}
	return done;
}

// Handle wearables that arrived after the timeout period expired.
void LLWearableHoldingPattern::handleLateArrivals()
{
	// Only safe to run if we have previously finished the missing
	// wearables and other processing - otherwise we could be in some
	// intermediate state - but have not been superceded by a later
	// outfit change request.
	if (mLateArrivals.size() == 0)
	{
		// Nothing to process.
		return;
	}
	if (!isMostRecent())
	{
		LL_WARNS() << self_av_string() << "Late arrivals not handled - outfit change no longer valid" << LL_ENDL;
	}
	if (!mIsAllComplete)
	{
		LL_WARNS() << self_av_string() << "Late arrivals not handled - in middle of missing wearables processing" << LL_ENDL;
	}

	LL_INFOS("Avatar") << self_av_string() << "HP " << index() << " need to handle " << mLateArrivals.size() << " late arriving wearables" << LL_ENDL;

	// Update mFoundList using late-arriving wearables.
	std::set<LLWearableType::EType> replaced_types;
	for (LLWearableHoldingPattern::found_list_t::iterator iter = getFoundList().begin();
		 iter != getFoundList().end(); ++iter)
	{
		LLFoundData& data = *iter;
		for (std::set<LLViewerWearable*>::iterator wear_it = mLateArrivals.begin();
			 wear_it != mLateArrivals.end();
			 ++wear_it)
		{
			LLViewerWearable *wearable = *wear_it;

			if(wearable->getAssetID() == data.mAssetID)
			{
				data.mWearable = wearable;

				replaced_types.insert(data.mWearableType);

				// BAP - if we didn't call
				// clearCOFLinksForMissingWearables() earlier, we
				// don't need to restore the link here.  Fixes
				// wearable ordering problems.

				// LLAppearanceMgr::instance().addCOFItemLink(data.mItemID,false);

				// BAP failing this means inventory or asset server
				// are corrupted in a way we don't handle.
				llassert((data.mWearableType < LLWearableType::WT_COUNT) && (wearable->getType() == data.mWearableType));
				break;
			}
		}
	}

	// Remove COF links for any default wearables previously used to replace the late arrivals.
	// All this pussyfooting around with a while loop and explicit
	// iterator incrementing is to allow removing items from the list
	// without clobbering the iterator we're using to navigate.
	LLWearableHoldingPattern::found_list_t::iterator iter = getFoundList().begin();
	while (iter != getFoundList().end())
	{
		LLFoundData& data = *iter;

		// If an item of this type has recently shown up, removed the corresponding replacement wearable from COF.
		if (data.mWearable && data.mIsReplacement &&
			replaced_types.find(data.mWearableType) != replaced_types.end())
		{
			LLAppearanceMgr::instance().removeCOFItemLinks(data.mItemID);
			std::list<LLFoundData>::iterator clobber_ator = iter;
			++iter;
			getFoundList().erase(clobber_ator);
		}
		else
		{
			++iter;
		}
	}

	// Clear contents of late arrivals.
	mLateArrivals.clear();

	// Update appearance based on mFoundList
	LLAppearanceMgr::instance().updateAgentWearables(this);
}

void LLWearableHoldingPattern::resetTime(F32 timeout)
{
	mWaitTime.reset();
	mWaitTime.setTimerExpirySec(timeout);
}

void LLWearableHoldingPattern::onWearableAssetFetch(LLViewerWearable *wearable)
{
	if (!isMostRecent())
	{
		LL_WARNS() << self_av_string() << "skipping because LLWearableHolding pattern is invalid (superceded by later outfit request)" << LL_ENDL;
	}
	
	mResolved += 1;  // just counting callbacks, not successes.
	LL_DEBUGS("Avatar") << self_av_string() << "HP " << index() << " resolved " << mResolved << "/" << getFoundList().size() << LL_ENDL;
	if (!wearable)
	{
		LL_WARNS() << self_av_string() << "no wearable found" << LL_ENDL;
	}

	if (mFired)
	{
		LL_WARNS() << self_av_string() << "called after holder fired" << LL_ENDL;
		if (wearable)
		{
			mLateArrivals.insert(wearable);
			if (mIsAllComplete)
			{
				handleLateArrivals();
			}
		}
		return;
	}

	if (!wearable)
	{
		return;
	}

	U32 use_count = 0;
	for (LLWearableHoldingPattern::found_list_t::iterator iter = getFoundList().begin();
		iter != getFoundList().end(); ++iter)
	{
		LLFoundData& data = *iter;
		if (wearable->getAssetID() == data.mAssetID)
		{
			// Failing this means inventory or asset server are corrupted in a way we don't handle.
			if ((data.mWearableType >= LLWearableType::WT_COUNT) || (wearable->getType() != data.mWearableType))
			{
				LL_WARNS() << self_av_string() << "recovered wearable but type invalid. inventory wearable type: " << data.mWearableType << " asset wearable type: " << wearable->getType() << LL_ENDL;
				break;
			}

			if (use_count == 0)
			{
				data.mWearable = wearable;
				use_count++;
			}
			else
			{
				LLViewerInventoryItem* wearable_item = gInventory.getItem(data.mItemID);
				if (wearable_item && wearable_item->isFinished() && wearable_item->getPermissions().allowModifyBy(gAgentID))
				{
					// We can't edit and do some other interactions with same asset twice, copy it
					// Note: can't update incomplete items. Usually attached from previous viewer build, but
					// consider adding fetch and completion callback
					LLViewerWearable* new_wearable = LLWearableList::instance().createCopy(wearable, wearable->getName());
					data.mWearable = new_wearable;
					data.mAssetID = new_wearable->getAssetID();

					// Update existing inventory item
					wearable_item->setAssetUUID(new_wearable->getAssetID());
					wearable_item->setTransactionID(new_wearable->getTransactionID());
					gInventory.updateItem(wearable_item, LLInventoryObserver::INTERNAL);
					wearable_item->updateServer(FALSE);

					use_count++;
				}
				else
				{
					// Note: technically a bug, LLViewerWearable can identify only one item id at a time,
					// yet we are tying it to multiple items here.
					// LLViewerWearable need to support more then one item.
					LL_WARNS() << "Same LLViewerWearable is used by multiple items! " << wearable->getAssetID() << LL_ENDL;
					data.mWearable = wearable;
				}
			}
		}
	}

	if (use_count > 1)
	{
		LL_WARNS() << "Copying wearable, multiple asset id uses! " << wearable->getAssetID() << LL_ENDL;
		gInventory.notifyObservers();
	}
}

static void onWearableAssetFetch(LLViewerWearable* wearable, void* data)
{
	LLWearableHoldingPattern* holder = (LLWearableHoldingPattern*)data;
	holder->onWearableAssetFetch(wearable);
}


static void removeDuplicateItems(LLInventoryModel::item_array_t& items)
{
	LLInventoryModel::item_array_t new_items;
	std::set<LLUUID> items_seen;
	std::deque<LLViewerInventoryItem*> tmp_list;
	// Traverse from the front and keep the first of each item
	// encountered, so we actually keep the *last* of each duplicate
	// item.  This is needed to give the right priority when adding
	// duplicate items to an existing outfit.
	for (S32 i=items.size()-1; i>=0; i--)
	{
		LLViewerInventoryItem *item = items.at(i);
		LLUUID item_id = item->getLinkedUUID();
		if (items_seen.find(item_id)!=items_seen.end())
			continue;
		items_seen.insert(item_id);
		tmp_list.push_front(item);
	}
	for (std::deque<LLViewerInventoryItem*>::iterator it = tmp_list.begin();
		 it != tmp_list.end();
		 ++it)
	{
		new_items.push_back(*it);
	}
	items = new_items;
}

//=========================================================================

const std::string LLAppearanceMgr::sExpectedTextureName = "OutfitPreview";

const LLUUID LLAppearanceMgr::getCOF() const
{
	return gInventory.findCategoryUUIDForType(LLFolderType::FT_CURRENT_OUTFIT);
}

S32 LLAppearanceMgr::getCOFVersion() const
{
	LLViewerInventoryCategory *cof = gInventory.getCategory(getCOF());
	if (cof)
	{
		return cof->getVersion();
	}
	else
	{
		return LLViewerInventoryCategory::VERSION_UNKNOWN;
	}
}

const LLViewerInventoryItem* LLAppearanceMgr::getBaseOutfitLink()
{
	const LLUUID& current_outfit_cat = getCOF();
	LLInventoryModel::cat_array_t cat_array;
	LLInventoryModel::item_array_t item_array;
	// Can't search on FT_OUTFIT since links to categories return FT_CATEGORY for type since they don't
	// return preferred type.
	LLIsType is_category( LLAssetType::AT_CATEGORY ); 
	gInventory.collectDescendentsIf(current_outfit_cat,
									cat_array,
									item_array,
									false,
									is_category);
	for (LLInventoryModel::item_array_t::const_iterator iter = item_array.begin();
		 iter != item_array.end();
		 iter++)
	{
		const LLViewerInventoryItem *item = (*iter);
		const LLViewerInventoryCategory *cat = item->getLinkedCategory();
		if (cat && cat->getPreferredType() == LLFolderType::FT_OUTFIT)
		{
			const LLUUID parent_id = cat->getParentUUID();
			LLViewerInventoryCategory*  parent_cat =  gInventory.getCategory(parent_id);
			// if base outfit moved to trash it means that we don't have base outfit
			if (parent_cat != NULL && parent_cat->getPreferredType() == LLFolderType::FT_TRASH)
			{
				return NULL;
			}
			return item;
		}
	}
	return NULL;
}

bool LLAppearanceMgr::getBaseOutfitName(std::string& name)
{
	const LLViewerInventoryItem* outfit_link = getBaseOutfitLink();
	if(outfit_link)
	{
		const LLViewerInventoryCategory *cat = outfit_link->getLinkedCategory();
		if (cat)
		{
			name = cat->getName();
			return true;
		}
	}
	return false;
}

const LLUUID LLAppearanceMgr::getBaseOutfitUUID()
{
	const LLViewerInventoryItem* outfit_link = getBaseOutfitLink();
	if (!outfit_link || !outfit_link->getIsLinkType()) return LLUUID::null;

	const LLViewerInventoryCategory* outfit_cat = outfit_link->getLinkedCategory();
	if (!outfit_cat) return LLUUID::null;

	if (outfit_cat->getPreferredType() != LLFolderType::FT_OUTFIT)
	{
		LL_WARNS() << "Expected outfit type:" << LLFolderType::FT_OUTFIT << " but got type:" << outfit_cat->getType() << " for folder name:" << outfit_cat->getName() << LL_ENDL;
		return LLUUID::null;
	}

	return outfit_cat->getUUID();
}

void wear_on_avatar_cb(const LLUUID& inv_item, bool do_replace = false)
{
	if (inv_item.isNull())
		return;
	
	LLViewerInventoryItem *item = gInventory.getItem(inv_item);
	if (item)
	{
		LLAppearanceMgr::instance().wearItemOnAvatar(inv_item, true, do_replace);
	}
}

void LLAppearanceMgr::wearItemsOnAvatar(const uuid_vec_t& item_ids_to_wear,
                                        bool do_update,
                                        bool replace,
                                        LLPointer<LLInventoryCallback> cb)
{
    bool first = true;

    LLInventoryObject::const_object_list_t items_to_link;

    for (uuid_vec_t::const_iterator it = item_ids_to_wear.begin();
         it != item_ids_to_wear.end();
         ++it)
    {
        replace = first && replace;
        first = false;

        const LLUUID& item_id_to_wear = *it;

        if (item_id_to_wear.isNull())
        {
            LL_DEBUGS("Avatar") << "null id " << item_id_to_wear << LL_ENDL;
            continue;
        }

        LLViewerInventoryItem* item_to_wear = gInventory.getItem(item_id_to_wear);
        if (!item_to_wear)
        {
            LL_DEBUGS("Avatar") << "inventory item not found for id " << item_id_to_wear << LL_ENDL;
            continue;
        }

        if (gInventory.isObjectDescendentOf(item_to_wear->getUUID(), gInventory.getLibraryRootFolderID()))
        {
            LL_DEBUGS("Avatar") << "inventory item in library, will copy and wear "
                                << item_to_wear->getName() << " id " << item_id_to_wear << LL_ENDL;
            LLPointer<LLInventoryCallback> cb = new LLBoostFuncInventoryCallback(boost::bind(wear_on_avatar_cb,_1,replace));
            copy_inventory_item(gAgent.getID(), item_to_wear->getPermissions().getOwner(),
                                item_to_wear->getUUID(), LLUUID::null, std::string(), cb);
            continue;
        } 
        else if (!gInventory.isObjectDescendentOf(item_to_wear->getUUID(), gInventory.getRootFolderID()))
        {
			// not in library and not in agent's inventory
            LL_DEBUGS("Avatar") << "inventory item not in user inventory or library, skipping "
                                << item_to_wear->getName() << " id " << item_id_to_wear << LL_ENDL;
            continue; 
        }
        else if (gInventory.isObjectDescendentOf(item_to_wear->getUUID(), gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH)))
        {
            LLNotificationsUtil::add("CannotWearTrash");
            LL_DEBUGS("Avatar") << "inventory item is in trash, skipping "
                                << item_to_wear->getName() << " id " << item_id_to_wear << LL_ENDL;
            continue;
        }
        else if (isLinkedInCOF(item_to_wear->getUUID())) // EXT-84911
        {
            LL_DEBUGS("Avatar") << "inventory item is already in COF, skipping "
                                << item_to_wear->getName() << " id " << item_id_to_wear << LL_ENDL;
            continue;
        }

        switch (item_to_wear->getType())
        {
            case LLAssetType::AT_CLOTHING:
            {
                if (gAgentWearables.areWearablesLoaded())
                {
                    if (!cb && do_update)
                    {
                        cb = new LLUpdateAppearanceAndEditWearableOnDestroy(item_id_to_wear);
                    }
                    LLWearableType::EType type = item_to_wear->getWearableType();
                    S32 wearable_count = gAgentWearables.getWearableCount(type);
                    if ((replace && wearable_count != 0) || !gAgentWearables.canAddWearable(type))
                    {
                        LLUUID item_id = gAgentWearables.getWearableItemID(item_to_wear->getWearableType(),
                                                                           wearable_count-1);
                        removeCOFItemLinks(item_id, cb);
                    }
                    
                    items_to_link.push_back(item_to_wear);
                } 
            }
            break;

            case LLAssetType::AT_BODYPART:
            {
                // TODO: investigate wearables may not be loaded at this point EXT-8231
                
                // Remove the existing wearables of the same type.
                // Remove existing body parts anyway because we must not be able to wear e.g. two skins.
                removeCOFLinksOfType(item_to_wear->getWearableType());
                if (!cb && do_update)
                {
                    cb = new LLUpdateAppearanceAndEditWearableOnDestroy(item_id_to_wear);
                }
                items_to_link.push_back(item_to_wear);
            }
            break;
                
            case LLAssetType::AT_OBJECT:
            {
                rez_attachment(item_to_wear, NULL, replace);
            }
            break;

            default: continue;
        }
    }

    // Batch up COF link creation - more efficient if using AIS.
    if (items_to_link.size())
    {
        link_inventory_array(getCOF(), items_to_link, cb); 
    }
}

void LLAppearanceMgr::wearItemOnAvatar(const LLUUID& item_id_to_wear,
									   bool do_update,
									   bool replace,
									   LLPointer<LLInventoryCallback> cb)
{
    uuid_vec_t ids;
    ids.push_back(item_id_to_wear);
    wearItemsOnAvatar(ids, do_update, replace, cb);
}

// Update appearance from outfit folder.
void LLAppearanceMgr::changeOutfit(bool proceed, const LLUUID& category, bool append)
{
	if (!proceed)
		return;
	LLAppearanceMgr::instance().updateCOF(category,append);
}

void LLAppearanceMgr::replaceCurrentOutfit(const LLUUID& new_outfit)
{
	LLViewerInventoryCategory* cat = gInventory.getCategory(new_outfit);
	wearInventoryCategory(cat, false, false);
}

// Remove existing photo link from outfit folder.
void LLAppearanceMgr::removeOutfitPhoto(const LLUUID& outfit_id)
{
    LLInventoryModel::cat_array_t sub_cat_array;
    LLInventoryModel::item_array_t outfit_item_array;
    gInventory.collectDescendents(
        outfit_id,
        sub_cat_array,
        outfit_item_array,
        LLInventoryModel::EXCLUDE_TRASH);
    BOOST_FOREACH(LLViewerInventoryItem* outfit_item, outfit_item_array)
    {
        LLViewerInventoryItem* linked_item = outfit_item->getLinkedItem();
        if (linked_item != NULL)
        {
            if (linked_item->getActualType() == LLAssetType::AT_TEXTURE)
            {
                gInventory.removeItem(outfit_item->getUUID());
            }
        }
        else if (outfit_item->getActualType() == LLAssetType::AT_TEXTURE)
        {
            gInventory.removeItem(outfit_item->getUUID());
        }
    }
}

// Open outfit renaming dialog.
void LLAppearanceMgr::renameOutfit(const LLUUID& outfit_id)
{
	LLViewerInventoryCategory* cat = gInventory.getCategory(outfit_id);
	if (!cat)
	{
		return;
	}

	LLSD args;
	args["NAME"] = cat->getName();

	LLSD payload;
	payload["cat_id"] = outfit_id;

	LLNotificationsUtil::add("RenameOutfit", args, payload, boost::bind(onOutfitRename, _1, _2));
}

// User typed new outfit name.
// static
void LLAppearanceMgr::onOutfitRename(const LLSD& notification, const LLSD& response)
{
	S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
	if (option != 0) return; // canceled

	std::string outfit_name = response["new_name"].asString();
	LLStringUtil::trim(outfit_name);
	if (!outfit_name.empty())
	{
		LLUUID cat_id = notification["payload"]["cat_id"].asUUID();
		rename_category(&gInventory, cat_id, outfit_name);
	}
}

void LLAppearanceMgr::setOutfitLocked(bool locked)
{
	if (mOutfitLocked == locked)
	{
		return;
	}

	mOutfitLocked = locked;
	if (locked)
	{
		mUnlockOutfitTimer->reset();
		mUnlockOutfitTimer->start();
	}
	else
	{
		mUnlockOutfitTimer->stop();
	}

	LLOutfitObserver::instance().notifyOutfitLockChanged();
}

void LLAppearanceMgr::addCategoryToCurrentOutfit(const LLUUID& cat_id)
{
	LLViewerInventoryCategory* cat = gInventory.getCategory(cat_id);
	wearInventoryCategory(cat, false, true);
}

void LLAppearanceMgr::takeOffOutfit(const LLUUID& cat_id)
{
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	LLFindWearablesEx collector(/*is_worn=*/ true, /*include_body_parts=*/ false);

	gInventory.collectDescendentsIf(cat_id, cats, items, FALSE, collector);

	LLInventoryModel::item_array_t::const_iterator it = items.begin();
	const LLInventoryModel::item_array_t::const_iterator it_end = items.end();
	uuid_vec_t uuids_to_remove;
	for( ; it_end != it; ++it)
	{
		LLViewerInventoryItem* item = *it;
		uuids_to_remove.push_back(item->getUUID());
	}
	removeItemsFromAvatar(uuids_to_remove);

	// deactivate all gestures in the outfit folder
	LLInventoryModel::item_array_t gest_items;
	getDescendentsOfAssetType(cat_id, gest_items, LLAssetType::AT_GESTURE);
	for(S32 i = 0; i  < gest_items.size(); ++i)
	{
		LLViewerInventoryItem *gest_item = gest_items[i];
		if ( LLGestureMgr::instance().isGestureActive( gest_item->getLinkedUUID()) )
		{
			LLGestureMgr::instance().deactivateGesture( gest_item->getLinkedUUID() );
		}
	}
}

// Create a copy of src_id + contents as a subfolder of dst_id.
void LLAppearanceMgr::shallowCopyCategory(const LLUUID& src_id, const LLUUID& dst_id,
											  LLPointer<LLInventoryCallback> cb)
{
	LLInventoryCategory *src_cat = gInventory.getCategory(src_id);
	if (!src_cat)
	{
		LL_WARNS() << "folder not found for src " << src_id.asString() << LL_ENDL;
		return;
	}
	LL_INFOS() << "starting, src_id " << src_id << " name " << src_cat->getName() << " dst_id " << dst_id << LL_ENDL;
	LLUUID parent_id = dst_id;
	if(parent_id.isNull())
	{
		parent_id = gInventory.getRootFolderID();
	}
	LLUUID subfolder_id = gInventory.createNewCategory( parent_id,
														LLFolderType::FT_NONE,
														src_cat->getName());
	shallowCopyCategoryContents(src_id, subfolder_id, cb);

	gInventory.notifyObservers();
}

void LLAppearanceMgr::slamCategoryLinks(const LLUUID& src_id, const LLUUID& dst_id,
										bool include_folder_links, LLPointer<LLInventoryCallback> cb)
{
	LLInventoryModel::cat_array_t* cats;
	LLInventoryModel::item_array_t* items;
	LLSD contents = LLSD::emptyArray();
	gInventory.getDirectDescendentsOf(src_id, cats, items);
	if (!cats || !items)
	{
		// NULL means the call failed -- cats/items map doesn't exist (note: this does NOT mean
		// that the cat just doesn't have any items or subfolders).
		LLViewerInventoryCategory* category = gInventory.getCategory(src_id);
		if (category)
		{
			LL_WARNS() << "Category '" << category->getName() << "' descendents corrupted, linking content failed." << LL_ENDL;
		}
		else
		{
			LL_WARNS() << "Category could not be retrieved, linking content failed." << LL_ENDL;
		}
		llassert(cats != NULL && items != NULL);

		return;
	}

	LL_INFOS() << "copying " << items->size() << " items" << LL_ENDL;
	for (LLInventoryModel::item_array_t::const_iterator iter = items->begin();
		 iter != items->end();
		 ++iter)
	{
		const LLViewerInventoryItem* item = (*iter);
		switch (item->getActualType())
		{
			case LLAssetType::AT_LINK:
			{
				LL_DEBUGS("Avatar") << "linking inventory item " << item->getName() << LL_ENDL;
				//getActualDescription() is used for a new description 
				//to propagate ordering information saved in descriptions of links
				LLSD item_contents;
				item_contents["name"] = item->getName();
				item_contents["desc"] = item->getActualDescription();
				item_contents["linked_id"] = item->getLinkedUUID();
				item_contents["type"] = LLAssetType::AT_LINK; 
				contents.append(item_contents);
				break;
			}
			case LLAssetType::AT_LINK_FOLDER:
			{
				LLViewerInventoryCategory *catp = item->getLinkedCategory();
				if (catp && include_folder_links)
				{
					LL_DEBUGS("Avatar") << "linking inventory folder " << item->getName() << LL_ENDL;
					LLSD base_contents;
					base_contents["name"] = catp->getName();
					base_contents["desc"] = ""; // categories don't have descriptions.
					base_contents["linked_id"] = catp->getLinkedUUID();
					base_contents["type"] = LLAssetType::AT_LINK_FOLDER; 
					contents.append(base_contents);
				}
				break;
			}
			default:
			{
				// Linux refuses to compile unless all possible enums are handled. Really, Linux?
				break;
			}
		}
	}
	slam_inventory_folder(dst_id, contents, cb);
}
// Copy contents of src_id to dst_id.
void LLAppearanceMgr::shallowCopyCategoryContents(const LLUUID& src_id, const LLUUID& dst_id,
													  LLPointer<LLInventoryCallback> cb)
{
	LLInventoryModel::cat_array_t* cats;
	LLInventoryModel::item_array_t* items;
	gInventory.getDirectDescendentsOf(src_id, cats, items);
	LL_INFOS() << "copying " << items->size() << " items" << LL_ENDL;
	LLInventoryObject::const_object_list_t link_array;
	for (LLInventoryModel::item_array_t::const_iterator iter = items->begin();
		 iter != items->end();
		 ++iter)
	{
		const LLViewerInventoryItem* item = (*iter);
		switch (item->getActualType())
		{
			case LLAssetType::AT_LINK:
			{
				LL_DEBUGS("Avatar") << "linking inventory item " << item->getName() << LL_ENDL;
				link_array.push_back(LLConstPointer<LLInventoryObject>(item));
				break;
			}
			case LLAssetType::AT_LINK_FOLDER:
			{
				LLViewerInventoryCategory *catp = item->getLinkedCategory();
				// Skip copying outfit links.
				if (catp && catp->getPreferredType() != LLFolderType::FT_OUTFIT)
				{
					LL_DEBUGS("Avatar") << "linking inventory folder " << item->getName() << LL_ENDL;
					link_array.push_back(LLConstPointer<LLInventoryObject>(item));
				}
				break;
			}
			case LLAssetType::AT_CLOTHING:
			case LLAssetType::AT_OBJECT:
			case LLAssetType::AT_BODYPART:
			case LLAssetType::AT_GESTURE:
			{
				LL_DEBUGS("Avatar") << "copying inventory item " << item->getName() << LL_ENDL;
				copy_inventory_item(gAgent.getID(),
									item->getPermissions().getOwner(),
									item->getUUID(),
									dst_id,
									item->getName(),
									cb);
				break;
			}
			default:
				// Ignore non-outfit asset types
				break;
		}
	}
	if (!link_array.empty())
	{
		link_inventory_array(dst_id, link_array, cb);
	}
}

BOOL LLAppearanceMgr::getCanMakeFolderIntoOutfit(const LLUUID& folder_id)
{
	// These are the wearable items that are required for considering this
	// folder as containing a complete outfit.
	U32 required_wearables = 0;
	required_wearables |= 1LL << LLWearableType::WT_SHAPE;
	required_wearables |= 1LL << LLWearableType::WT_SKIN;
	required_wearables |= 1LL << LLWearableType::WT_HAIR;
	required_wearables |= 1LL << LLWearableType::WT_EYES;

	// These are the wearables that the folder actually contains.
	U32 folder_wearables = 0;
	LLInventoryModel::cat_array_t* cats;
	LLInventoryModel::item_array_t* items;
	gInventory.getDirectDescendentsOf(folder_id, cats, items);
	for (LLInventoryModel::item_array_t::const_iterator iter = items->begin();
		 iter != items->end();
		 ++iter)
	{
		const LLViewerInventoryItem* item = (*iter);
		if (item->isWearableType())
		{
			const LLWearableType::EType wearable_type = item->getWearableType();
			folder_wearables |= 1LL << wearable_type;
		}
	}

	// If the folder contains the required wearables, return TRUE.
	return ((required_wearables & folder_wearables) == required_wearables);
}

bool LLAppearanceMgr::getCanRemoveOutfit(const LLUUID& outfit_cat_id)
{
	// Disallow removing the base outfit.
	if (outfit_cat_id == getBaseOutfitUUID())
	{
		return false;
	}

	// Check if the outfit folder itself is removable.
	if (!get_is_category_removable(&gInventory, outfit_cat_id))
	{
		return false;
	}

	// Check for the folder's non-removable descendants.
	LLFindNonRemovableObjects filter_non_removable;
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	gInventory.collectDescendentsIf(outfit_cat_id, cats, items, false, filter_non_removable);
	if (!cats.empty() || !items.empty())
	{
		return false;
	}

	return true;
}

// static
bool LLAppearanceMgr::getCanRemoveFromCOF(const LLUUID& outfit_cat_id)
{
	if (gAgentWearables.isCOFChangeInProgress())
	{
		return false;
	}
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	LLFindWearablesEx is_worn(/*is_worn=*/ true, /*include_body_parts=*/ false);
	gInventory.collectDescendentsIf(outfit_cat_id,
		cats,
		items,
		LLInventoryModel::EXCLUDE_TRASH,
		is_worn);
	return items.size() > 0;
}

// static
bool LLAppearanceMgr::getCanAddToCOF(const LLUUID& outfit_cat_id)
{
	if (gAgentWearables.isCOFChangeInProgress())
	{
		return false;
	}

	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	LLFindWearablesEx not_worn(/*is_worn=*/ false, /*include_body_parts=*/ false);
	gInventory.collectDescendentsIf(outfit_cat_id,
		cats,
		items,
		LLInventoryModel::EXCLUDE_TRASH,
		not_worn);

	return items.size() > 0;
}

bool LLAppearanceMgr::getCanReplaceCOF(const LLUUID& outfit_cat_id)
{
	// Don't allow wearing anything while we're changing appearance.
	if (gAgentWearables.isCOFChangeInProgress())
	{
		return false;
	}

	// Check whether it's the base outfit.
	if (outfit_cat_id.isNull())
	{
		return false;
	}

	// Check whether the outfit contains any wearables
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	LLFindWearables is_wearable;
	gInventory.collectDescendentsIf(outfit_cat_id,
		cats,
		items,
		LLInventoryModel::EXCLUDE_TRASH,
		is_wearable);

	return items.size() > 0;
}

// Moved from LLWearableList::ContextMenu for wider utility.
bool LLAppearanceMgr::canAddWearables(const uuid_vec_t& item_ids)
{
	// TODO: investigate wearables may not be loaded at this point EXT-8231

	U32 n_objects = 0;
	U32 n_clothes = 0;

	// Count given clothes (by wearable type) and objects.
	for (uuid_vec_t::const_iterator it = item_ids.begin(); it != item_ids.end(); ++it)
	{
		LLViewerInventoryItem* item = gInventory.getItem(*it);
		if (!item)
		{
			return false;
		}

		if (item->getType() == LLAssetType::AT_OBJECT)
		{
			++n_objects;
		}
		else if (item->getType() == LLAssetType::AT_CLOTHING)
		{
			++n_clothes;
		}
		else if (item->getType() == LLAssetType::AT_BODYPART || item->getType() == LLAssetType::AT_GESTURE)
		{
			return isAgentAvatarValid();
		}
		else
		{
			LL_WARNS() << "Unexpected wearable type" << LL_ENDL;
			return false;
		}
	}

	// Check whether we can add all the objects.
	if (!isAgentAvatarValid() || !gAgentAvatarp->canAttachMoreObjects(n_objects))
	{
		return false;
	}

	// Check whether we can add all the clothes.
    U32 sum_clothes = n_clothes + gAgentWearables.getClothingLayerCount();
    return sum_clothes <= LLAgentWearables::MAX_CLOTHING_LAYERS;
}

void LLAppearanceMgr::purgeBaseOutfitLink(const LLUUID& category, LLPointer<LLInventoryCallback> cb)
{
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	gInventory.collectDescendents(category, cats, items,
								  LLInventoryModel::EXCLUDE_TRASH);
	for (S32 i = 0; i < items.size(); ++i)
	{
		LLViewerInventoryItem *item = items.at(i);
		if (item->getActualType() != LLAssetType::AT_LINK_FOLDER)
			continue;
		LLViewerInventoryCategory* catp = item->getLinkedCategory();
		if(catp && catp->getPreferredType() == LLFolderType::FT_OUTFIT)
		{
			remove_inventory_item(item->getUUID(), cb);
		}
	}
}

// Keep the last N wearables of each type.  For viewer 2.0, N is 1 for
// both body parts and clothing items.
void LLAppearanceMgr::filterWearableItems(
	LLInventoryModel::item_array_t& items, S32 max_per_type, S32 max_total)
{
    // Restrict by max total items first.
    if ((max_total > 0) && (items.size() > max_total))
    {
        LLInventoryModel::item_array_t items_to_keep;
        for (S32 i=0; i<max_total; i++)
        {
            items_to_keep.push_back(items[i]);
        }
        items = items_to_keep;
    }

    if (max_per_type > 0)
    {
        // Divvy items into arrays by wearable type.
        std::vector<LLInventoryModel::item_array_t> items_by_type(LLWearableType::WT_COUNT);
        divvyWearablesByType(items, items_by_type);

        // rebuild items list, retaining the last max_per_type of each array
        items.clear();
        for (S32 i=0; i<LLWearableType::WT_COUNT; i++)
        {
            S32 size = items_by_type[i].size();
            if (size <= 0)
                continue;
            S32 start_index = llmax(0,size-max_per_type);
            for (S32 j = start_index; j<size; j++)
            {
                items.push_back(items_by_type[i][j]);
            }
        }
    }
}

void LLAppearanceMgr::updateCOF(const LLUUID& category, bool append)
{
	LLViewerInventoryCategory *pcat = gInventory.getCategory(category);
	if (!pcat)
	{
		LL_WARNS() << "no category found for id " << category << LL_ENDL;
		return;
	}
	LL_INFOS("Avatar") << self_av_string() << "starting, cat '" << (pcat ? pcat->getName() : "[UNKNOWN]") << "'" << LL_ENDL;

	const LLUUID cof = getCOF();

	// Deactivate currently active gestures in the COF, if replacing outfit
	if (!append)
	{
		LLInventoryModel::item_array_t gest_items;
		getDescendentsOfAssetType(cof, gest_items, LLAssetType::AT_GESTURE);
		for(S32 i = 0; i  < gest_items.size(); ++i)
		{
			LLViewerInventoryItem *gest_item = gest_items.at(i);
			if ( LLGestureMgr::instance().isGestureActive( gest_item->getLinkedUUID()) )
			{
				LLGestureMgr::instance().deactivateGesture( gest_item->getLinkedUUID() );
			}
		}
	}
	
	// Collect and filter descendents to determine new COF contents.

	// - Body parts: always include COF contents as a fallback in case any
	// required parts are missing.
	// Preserve body parts from COF if appending.
	LLInventoryModel::item_array_t body_items;
	getDescendentsOfAssetType(cof, body_items, LLAssetType::AT_BODYPART);
	getDescendentsOfAssetType(category, body_items, LLAssetType::AT_BODYPART);
	if (append)
		reverse(body_items.begin(), body_items.end());
	// Reduce body items to max of one per type.
	removeDuplicateItems(body_items);
	filterWearableItems(body_items, 1, 0);

	// - Wearables: include COF contents only if appending.
	LLInventoryModel::item_array_t wear_items;
	if (append)
		getDescendentsOfAssetType(cof, wear_items, LLAssetType::AT_CLOTHING);
	getDescendentsOfAssetType(category, wear_items, LLAssetType::AT_CLOTHING);
	// Reduce wearables to max of one per type.
	removeDuplicateItems(wear_items);
	filterWearableItems(wear_items, 0, LLAgentWearables::MAX_CLOTHING_LAYERS);

	// - Attachments: include COF contents only if appending.
	LLInventoryModel::item_array_t obj_items;
	if (append)
		getDescendentsOfAssetType(cof, obj_items, LLAssetType::AT_OBJECT);
	getDescendentsOfAssetType(category, obj_items, LLAssetType::AT_OBJECT);
	removeDuplicateItems(obj_items);

	// - Gestures: include COF contents only if appending.
	LLInventoryModel::item_array_t gest_items;
	if (append)
		getDescendentsOfAssetType(cof, gest_items, LLAssetType::AT_GESTURE);
	getDescendentsOfAssetType(category, gest_items, LLAssetType::AT_GESTURE);
	removeDuplicateItems(gest_items);
	
	// Create links to new COF contents.
	LLInventoryModel::item_array_t all_items;
	std::copy(body_items.begin(), body_items.end(), std::back_inserter(all_items));
	std::copy(wear_items.begin(), wear_items.end(), std::back_inserter(all_items));
	std::copy(obj_items.begin(), obj_items.end(), std::back_inserter(all_items));
	std::copy(gest_items.begin(), gest_items.end(), std::back_inserter(all_items));

	// Find any wearables that need description set to enforce ordering.
	desc_map_t desc_map;
	getWearableOrderingDescUpdates(wear_items, desc_map);

	// Will link all the above items.
	// link_waiter enforce flags are false because we've already fixed everything up in updateCOF().
	LLPointer<LLInventoryCallback> link_waiter = new LLUpdateAppearanceOnDestroy(false,false);
	LLSD contents = LLSD::emptyArray();

	for (LLInventoryModel::item_array_t::const_iterator it = all_items.begin();
		 it != all_items.end(); ++it)
	{
		LLSD item_contents;
		LLInventoryItem *item = *it;

		std::string desc;
		desc_map_t::const_iterator desc_iter = desc_map.find(item->getUUID());
		if (desc_iter != desc_map.end())
		{
			desc = desc_iter->second;
			LL_DEBUGS("Avatar") << item->getName() << " overriding desc to: " << desc
								<< " (was: " << item->getActualDescription() << ")" << LL_ENDL;
		}
		else
		{
			desc = item->getActualDescription();
		}

		item_contents["name"] = item->getName();
		item_contents["desc"] = desc;
		item_contents["linked_id"] = item->getLinkedUUID();
		item_contents["type"] = LLAssetType::AT_LINK; 
		contents.append(item_contents);
	}
	const LLUUID& base_id = append ? getBaseOutfitUUID() : category;
	LLViewerInventoryCategory *base_cat = gInventory.getCategory(base_id);
	if (base_cat && (base_cat->getPreferredType() == LLFolderType::FT_OUTFIT))
	{
		LLSD base_contents;
		base_contents["name"] = base_cat->getName();
		base_contents["desc"] = "";
		base_contents["linked_id"] = base_cat->getLinkedUUID();
		base_contents["type"] = LLAssetType::AT_LINK_FOLDER; 
		contents.append(base_contents);
	}
	if (gSavedSettings.getBOOL("DebugAvatarAppearanceMessage"))
	{
		dump_sequential_xml(gAgentAvatarp->getFullname() + "_slam_request", contents);
	}
	slam_inventory_folder(getCOF(), contents, link_waiter);

	LL_DEBUGS("Avatar") << self_av_string() << "waiting for LLUpdateAppearanceOnDestroy" << LL_ENDL;
}

void LLAppearanceMgr::updatePanelOutfitName(const std::string& name)
{
	LLSidepanelAppearance* panel_appearance =
		dynamic_cast<LLSidepanelAppearance *>(LLFloaterSidePanelContainer::getPanel("appearance"));
	if (panel_appearance)
	{
		panel_appearance->refreshCurrentOutfitName(name);
	}
}

void LLAppearanceMgr::createBaseOutfitLink(const LLUUID& category, LLPointer<LLInventoryCallback> link_waiter)
{
	const LLUUID cof = getCOF();
	LLViewerInventoryCategory* catp = gInventory.getCategory(category);
	std::string new_outfit_name = "";

	purgeBaseOutfitLink(cof, link_waiter);

	if (catp && catp->getPreferredType() == LLFolderType::FT_OUTFIT)
	{
		link_inventory_object(cof, catp, link_waiter);
		new_outfit_name = catp->getName();
	}
	
	updatePanelOutfitName(new_outfit_name);
}

void LLAppearanceMgr::updateAgentWearables(LLWearableHoldingPattern* holder)
{
	LL_DEBUGS("Avatar") << "updateAgentWearables()" << LL_ENDL;
	LLInventoryItem::item_array_t items;
	std::vector< LLViewerWearable* > wearables;
	wearables.reserve(32);

	// For each wearable type, find the wearables of that type.
	for( S32 i = 0; i < LLWearableType::WT_COUNT; i++ )
	{
		for (LLWearableHoldingPattern::found_list_t::iterator iter = holder->getFoundList().begin();
			 iter != holder->getFoundList().end(); ++iter)
		{
			LLFoundData& data = *iter;
			LLViewerWearable* wearable = data.mWearable;
			if( wearable && ((S32)wearable->getType() == i) )
			{
				LLViewerInventoryItem* item = (LLViewerInventoryItem*)gInventory.getItem(data.mItemID);
				if( item && (item->getAssetUUID() == wearable->getAssetID()) )
				{
					items.push_back(item);
					wearables.push_back(wearable);
				}
			}
		}
	}

	if(wearables.size() > 0)
	{
		gAgentWearables.setWearableOutfit(items, wearables);
	}
}

S32 LLAppearanceMgr::countActiveHoldingPatterns()
{
	return LLWearableHoldingPattern::countActive();
}

static void remove_non_link_items(LLInventoryModel::item_array_t &items)
{
	LLInventoryModel::item_array_t pruned_items;
	for (LLInventoryModel::item_array_t::const_iterator iter = items.begin();
		 iter != items.end();
		 ++iter)
	{
 		const LLViewerInventoryItem *item = (*iter);
		if (item && item->getIsLinkType())
		{
			pruned_items.push_back((*iter));
		}
	}
	items = pruned_items;
}

//a predicate for sorting inventory items by actual descriptions
bool sort_by_actual_description(const LLInventoryItem* item1, const LLInventoryItem* item2)
{
	if (!item1 || !item2) 
	{
		LL_WARNS() << "either item1 or item2 is NULL" << LL_ENDL;
		return true;
	}

	return item1->getActualDescription() < item2->getActualDescription();
}

void item_array_diff(LLInventoryModel::item_array_t& full_list,
					 LLInventoryModel::item_array_t& keep_list,
					 LLInventoryModel::item_array_t& kill_list)
	
{
	for (LLInventoryModel::item_array_t::iterator it = full_list.begin();
		 it != full_list.end();
		 ++it)
	{
		LLViewerInventoryItem *item = *it;
		if (std::find(keep_list.begin(), keep_list.end(), item) == keep_list.end())
		{
			kill_list.push_back(item);
		}
	}
}

S32 LLAppearanceMgr::findExcessOrDuplicateItems(const LLUUID& cat_id,
												 LLAssetType::EType type,
												 S32 max_items_per_type,
												 S32 max_items_total,
												 LLInventoryObject::object_list_t& items_to_kill)
{
	S32 to_kill_count = 0;

	LLInventoryModel::item_array_t items;
	getDescendentsOfAssetType(cat_id, items, type);
	LLInventoryModel::item_array_t curr_items = items;
	removeDuplicateItems(items);
	if (max_items_per_type > 0 || max_items_total > 0)
	{
		filterWearableItems(items, max_items_per_type, max_items_total);
	}
	LLInventoryModel::item_array_t kill_items;
	item_array_diff(curr_items,items,kill_items);
	for (LLInventoryModel::item_array_t::iterator it = kill_items.begin();
		 it != kill_items.end();
		 ++it)
	{
		items_to_kill.push_back(LLPointer<LLInventoryObject>(*it));
		to_kill_count++;
	}
	return to_kill_count;
}
	

void LLAppearanceMgr::findAllExcessOrDuplicateItems(const LLUUID& cat_id,
													LLInventoryObject::object_list_t& items_to_kill)
{
	findExcessOrDuplicateItems(cat_id,LLAssetType::AT_BODYPART,
							   1, 0, items_to_kill);
	findExcessOrDuplicateItems(cat_id,LLAssetType::AT_CLOTHING,
							   0, LLAgentWearables::MAX_CLOTHING_LAYERS, items_to_kill);
	findExcessOrDuplicateItems(cat_id,LLAssetType::AT_OBJECT,
							   0, 0, items_to_kill);
}

void LLAppearanceMgr::enforceCOFItemRestrictions(LLPointer<LLInventoryCallback> cb)
{
	LLInventoryObject::object_list_t items_to_kill;
	findAllExcessOrDuplicateItems(getCOF(), items_to_kill);
	if (items_to_kill.size()>0)
	{
		// Remove duplicate or excess wearables. Should normally be enforced at the UI level, but
		// this should catch anything that gets through.
		remove_inventory_items(items_to_kill, cb);
	}
}

void LLAppearanceMgr::updateAppearanceFromCOF(bool enforce_item_restrictions,
											  bool enforce_ordering,
											  nullary_func_t post_update_func)
{
	if (mIsInUpdateAppearanceFromCOF)
	{
		LL_WARNS() << "Called updateAppearanceFromCOF inside updateAppearanceFromCOF, skipping" << LL_ENDL;
		return;
	}

	LL_DEBUGS("Avatar") << self_av_string() << "starting" << LL_ENDL;

	if (enforce_item_restrictions)
	{
		// The point here is just to call
		// updateAppearanceFromCOF() again after excess items
		// have been removed. That time we will set
		// enforce_item_restrictions to false so we don't get
		// caught in a perpetual loop.
		LLPointer<LLInventoryCallback> cb(
			new LLUpdateAppearanceOnDestroy(false, enforce_ordering, post_update_func));
		enforceCOFItemRestrictions(cb);
		return;
	}

	if (enforce_ordering)
	{
		//checking integrity of the COF in terms of ordering of wearables, 
		//checking and updating links' descriptions of wearables in the COF (before analyzed for "dirty" state)

		// As with enforce_item_restrictions handling above, we want
		// to wait for the update callbacks, then (finally!) call
		// updateAppearanceFromCOF() with no additional COF munging needed.
		LLPointer<LLInventoryCallback> cb(
			new LLUpdateAppearanceOnDestroy(false, false, post_update_func));
		updateClothingOrderingInfo(LLUUID::null, cb);
		return;
	}

	if (!validateClothingOrderingInfo())
	{
		LL_WARNS() << "Clothing ordering error" << LL_ENDL;
	}

	BoolSetter setIsInUpdateAppearanceFromCOF(mIsInUpdateAppearanceFromCOF);
	selfStartPhase("update_appearance_from_cof");

	// update dirty flag to see if the state of the COF matches
	// the saved outfit stored as a folder link
	updateIsDirty();

	// Send server request for appearance update
	if (gAgent.getRegion() && gAgent.getRegion()->getCentralBakeVersion())
	{
		requestServerAppearanceUpdate();
	}

	LLUUID current_outfit_id = getCOF();

	// Find all the wearables that are in the COF's subtree.
	LL_DEBUGS() << "LLAppearanceMgr::updateFromCOF()" << LL_ENDL;
	LLInventoryModel::item_array_t wear_items;
	LLInventoryModel::item_array_t obj_items;
	LLInventoryModel::item_array_t gest_items;
	getUserDescendents(current_outfit_id, wear_items, obj_items, gest_items);
	// Get rid of non-links in case somehow the COF was corrupted.
	remove_non_link_items(wear_items);
	remove_non_link_items(obj_items);
	remove_non_link_items(gest_items);

	dumpItemArray(wear_items,"asset_dump: wear_item");
	dumpItemArray(obj_items,"asset_dump: obj_item");

	LLViewerInventoryCategory *cof = gInventory.getCategory(current_outfit_id);
	if (!gInventory.isCategoryComplete(current_outfit_id))
	{
		LL_WARNS() << "COF info is not complete. Version " << cof->getVersion()
				<< " descendent_count " << cof->getDescendentCount()
				<< " viewer desc count " << cof->getViewerDescendentCount() << LL_ENDL;
	}
	if(!wear_items.size())
	{
		LLNotificationsUtil::add("CouldNotPutOnOutfit");
		return;
	}

	//preparing the list of wearables in the correct order for LLAgentWearables
	sortItemsByActualDescription(wear_items);


	LL_DEBUGS("Avatar") << "HP block starts" << LL_ENDL;
	LLTimer hp_block_timer;
	LLWearableHoldingPattern* holder = new LLWearableHoldingPattern;

	holder->setObjItems(obj_items);
	holder->setGestItems(gest_items);
		
	// Note: can't do normal iteration, because if all the
	// wearables can be resolved immediately, then the
	// callback will be called (and this object deleted)
	// before the final getNextData().

	for(S32 i = 0; i  < wear_items.size(); ++i)
	{
		LLViewerInventoryItem *item = wear_items.at(i);
		LLViewerInventoryItem *linked_item = item ? item->getLinkedItem() : NULL;

		// Fault injection: use debug setting to test asset 
		// fetch failures (should be replaced by new defaults in
		// lost&found).
		U32 skip_type = gSavedSettings.getU32("ForceAssetFail");

		if (item && item->getIsLinkType() && linked_item)
		{
			LLFoundData found(linked_item->getUUID(),
							  linked_item->getAssetUUID(),
							  linked_item->getName(),
							  linked_item->getType(),
							  linked_item->isWearableType() ? linked_item->getWearableType() : LLWearableType::WT_INVALID
				);

			if (skip_type != LLWearableType::WT_INVALID && skip_type == found.mWearableType)
			{
				found.mAssetID.generate(); // Replace with new UUID, guaranteed not to exist in DB
			}
			//pushing back, not front, to preserve order of wearables for LLAgentWearables
			holder->getFoundList().push_back(found);
		}
		else
		{
			if (!item)
			{
				LL_WARNS() << "Attempt to wear a null item " << LL_ENDL;
			}
			else if (!linked_item)
			{
				LL_WARNS() << "Attempt to wear a broken link [ name:" << item->getName() << " ] " << LL_ENDL;
			}
		}
	}

	selfStartPhase("get_wearables_2");

	for (LLWearableHoldingPattern::found_list_t::iterator it = holder->getFoundList().begin();
		 it != holder->getFoundList().end(); ++it)
	{
		LLFoundData& found = *it;

		LL_DEBUGS() << self_av_string() << "waiting for onWearableAssetFetch callback, asset " << found.mAssetID.asString() << LL_ENDL;

		// Fetch the wearables about to be worn.
		LLWearableList::instance().getAsset(found.mAssetID,
											found.mName,
											gAgentAvatarp,
											found.mAssetType,
											onWearableAssetFetch,
											(void*)holder);

	}

	holder->resetTime(gSavedSettings.getF32("MaxWearableWaitTime"));
	if (!holder->pollFetchCompletion())
	{
		doOnIdleRepeating(boost::bind(&LLWearableHoldingPattern::pollFetchCompletion,holder));
	}
	post_update_func();

	LL_DEBUGS("Avatar") << "HP block ends, elapsed " << hp_block_timer.getElapsedTimeF32() << LL_ENDL;
}

void LLAppearanceMgr::getDescendentsOfAssetType(const LLUUID& category,
													LLInventoryModel::item_array_t& items,
													LLAssetType::EType type)
{
	LLInventoryModel::cat_array_t cats;
	LLIsType is_of_type(type);
	gInventory.collectDescendentsIf(category,
									cats,
									items,
									LLInventoryModel::EXCLUDE_TRASH,
									is_of_type);
}

void LLAppearanceMgr::getUserDescendents(const LLUUID& category, 
											 LLInventoryModel::item_array_t& wear_items,
											 LLInventoryModel::item_array_t& obj_items,
											 LLInventoryModel::item_array_t& gest_items)
{
	LLInventoryModel::cat_array_t wear_cats;
	LLFindWearables is_wearable;
	gInventory.collectDescendentsIf(category,
									wear_cats,
									wear_items,
									LLInventoryModel::EXCLUDE_TRASH,
									is_wearable);

	LLInventoryModel::cat_array_t obj_cats;
	LLIsType is_object( LLAssetType::AT_OBJECT );
	gInventory.collectDescendentsIf(category,
									obj_cats,
									obj_items,
									LLInventoryModel::EXCLUDE_TRASH,
									is_object);

	// Find all gestures in this folder
	LLInventoryModel::cat_array_t gest_cats;
	LLIsType is_gesture( LLAssetType::AT_GESTURE );
	gInventory.collectDescendentsIf(category,
									gest_cats,
									gest_items,
									LLInventoryModel::EXCLUDE_TRASH,
									is_gesture);
}

void LLAppearanceMgr::wearInventoryCategory(LLInventoryCategory* category, bool copy, bool append)
{
	if(!category) return;

	selfClearPhases();
	selfStartPhase("wear_inventory_category");

	gAgentWearables.notifyLoadingStarted();

	LL_INFOS("Avatar") << self_av_string() << "wearInventoryCategory( " << category->getName()
			 << " )" << LL_ENDL;

	// If we are copying from library, attempt to use AIS to copy the category.
    if (copy && AISAPI::isAvailable())
	{
		LLUUID parent_id;
		parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_CLOTHING);
		if (parent_id.isNull())
		{
			parent_id = gInventory.getRootFolderID();
		}

		LLPointer<LLInventoryCallback> copy_cb = new LLWearCategoryAfterCopy(append);
		LLPointer<LLInventoryCallback> track_cb = new LLTrackPhaseWrapper(
													std::string("wear_inventory_category_callback"), copy_cb);

        AISAPI::completion_t cr = boost::bind(&doAppearanceCb, track_cb, _1);
        AISAPI::CopyLibraryCategory(category->getUUID(), parent_id, false, cr);
	}
    else
	{
		selfStartPhase("wear_inventory_category_fetch");
		callAfterCategoryFetch(category->getUUID(),boost::bind(&LLAppearanceMgr::wearCategoryFinal,
															   &LLAppearanceMgr::instance(),
															   category->getUUID(), copy, append));
	}
}

S32 LLAppearanceMgr::getActiveCopyOperations() const
{
	return LLCallAfterInventoryCopyMgr::getInstanceCount(); 
}

void LLAppearanceMgr::wearCategoryFinal(LLUUID& cat_id, bool copy_items, bool append)
{
	LL_INFOS("Avatar") << self_av_string() << "starting" << LL_ENDL;

	selfStopPhase("wear_inventory_category_fetch");
	
	// We now have an outfit ready to be copied to agent inventory. Do
	// it, and wear that outfit normally.
	LLInventoryCategory* cat = gInventory.getCategory(cat_id);
	if(copy_items)
	{
		LLInventoryModel::cat_array_t* cats;
		LLInventoryModel::item_array_t* items;
		gInventory.getDirectDescendentsOf(cat_id, cats, items);
		std::string name;
		if(!cat)
		{
			// should never happen.
			name = "New Outfit";
		}
		else
		{
			name = cat->getName();
		}
		LLViewerInventoryItem* item = NULL;
		LLInventoryModel::item_array_t::const_iterator it = items->begin();
		LLInventoryModel::item_array_t::const_iterator end = items->end();
		LLUUID pid;
		for(; it < end; ++it)
		{
			item = *it;
			if(item)
			{
				if(LLInventoryType::IT_GESTURE == item->getInventoryType())
				{
					pid = gInventory.findCategoryUUIDForType(LLFolderType::FT_GESTURE);
				}
				else
				{
					pid = gInventory.findCategoryUUIDForType(LLFolderType::FT_CLOTHING);
				}
				break;
			}
		}
		if(pid.isNull())
		{
			pid = gInventory.getRootFolderID();
		}
		
		LLUUID new_cat_id = gInventory.createNewCategory(
			pid,
			LLFolderType::FT_NONE,
			name);

		// Create a CopyMgr that will copy items, manage its own destruction
		new LLCallAfterInventoryCopyMgr(
			*items, new_cat_id, std::string("wear_inventory_category_callback"),
			boost::bind(&LLAppearanceMgr::wearInventoryCategoryOnAvatar,
						LLAppearanceMgr::getInstance(),
						gInventory.getCategory(new_cat_id),
						append));

		// BAP fixes a lag in display of created dir.
		gInventory.notifyObservers();
	}
	else
	{
		// Wear the inventory category.
		LLAppearanceMgr::instance().wearInventoryCategoryOnAvatar(cat, append);
	}
}

// *NOTE: hack to get from avatar inventory to avatar
void LLAppearanceMgr::wearInventoryCategoryOnAvatar( LLInventoryCategory* category, bool append )
{
	// Avoid unintentionally overwriting old wearables.  We have to do
	// this up front to avoid having to deal with the case of multiple
	// wearables being dirty.
	if (!category) return;

	if ( !LLInventoryCallbackManager::is_instantiated() )
	{
		// shutting down, ignore.
		return;
	}

	LL_INFOS("Avatar") << self_av_string() << "wearInventoryCategoryOnAvatar '" << category->getName()
			 << "'" << LL_ENDL;
			 	
	if (gAgentCamera.cameraCustomizeAvatar())
	{
		// switching to outfit editor should automagically save any currently edited wearable
		LLFloaterSidePanelContainer::showPanel("appearance", LLSD().with("type", "edit_outfit"));
	}

	LLAppearanceMgr::changeOutfit(TRUE, category->getUUID(), append);
}

// FIXME do we really want to search entire inventory for matching name?
void LLAppearanceMgr::wearOutfitByName(const std::string& name)
{
	LL_INFOS("Avatar") << self_av_string() << "Wearing category " << name << LL_ENDL;

	LLInventoryModel::cat_array_t cat_array;
	LLInventoryModel::item_array_t item_array;
	LLNameCategoryCollector has_name(name);
	gInventory.collectDescendentsIf(gInventory.getRootFolderID(),
									cat_array,
									item_array,
									LLInventoryModel::EXCLUDE_TRASH,
									has_name);
	bool copy_items = false;
	LLInventoryCategory* cat = NULL;
	if (cat_array.size() > 0)
	{
		// Just wear the first one that matches
		cat = cat_array.at(0);
	}
	else
	{
		gInventory.collectDescendentsIf(LLUUID::null,
										cat_array,
										item_array,
										LLInventoryModel::EXCLUDE_TRASH,
										has_name);
		if(cat_array.size() > 0)
		{
			cat = cat_array.at(0);
			copy_items = true;
		}
	}

	if(cat)
	{
		LLAppearanceMgr::wearInventoryCategory(cat, copy_items, false);
	}
	else
	{
		LL_WARNS() << "Couldn't find outfit " <<name<< " in wearOutfitByName()"
				<< LL_ENDL;
	}
}

bool areMatchingWearables(const LLViewerInventoryItem *a, const LLViewerInventoryItem *b)
{
	return (a->isWearableType() && b->isWearableType() &&
			(a->getWearableType() == b->getWearableType()));
}

class LLDeferredCOFLinkObserver: public LLInventoryObserver
{
public:
	LLDeferredCOFLinkObserver(const LLUUID& item_id, LLPointer<LLInventoryCallback> cb, const std::string& description):
		mItemID(item_id),
		mCallback(cb),
		mDescription(description)
	{
	}

	~LLDeferredCOFLinkObserver()
	{
	}
	
	/* virtual */ void changed(U32 mask)
	{
		const LLInventoryItem *item = gInventory.getItem(mItemID);
		if (item)
		{
			gInventory.removeObserver(this);
			LLAppearanceMgr::instance().addCOFItemLink(item, mCallback, mDescription);
			delete this;
		}
	}

private:
	const LLUUID mItemID;
	std::string mDescription;
	LLPointer<LLInventoryCallback> mCallback;
};


// BAP - note that this runs asynchronously if the item is not already loaded from inventory.
// Dangerous if caller assumes link will exist after calling the function.
void LLAppearanceMgr::addCOFItemLink(const LLUUID &item_id,
									 LLPointer<LLInventoryCallback> cb,
									 const std::string description)
{
	const LLInventoryItem *item = gInventory.getItem(item_id);
	if (!item)
	{
		LLDeferredCOFLinkObserver *observer = new LLDeferredCOFLinkObserver(item_id, cb, description);
		gInventory.addObserver(observer);
	}
	else
	{
		addCOFItemLink(item, cb, description);
	}
}

void LLAppearanceMgr::addCOFItemLink(const LLInventoryItem *item,
									 LLPointer<LLInventoryCallback> cb,
									 const std::string description)
{
	const LLViewerInventoryItem *vitem = dynamic_cast<const LLViewerInventoryItem*>(item);
	if (!vitem)
	{
		LL_WARNS() << "not an llviewerinventoryitem, failed" << LL_ENDL;
		return;
	}

	gInventory.addChangedMask(LLInventoryObserver::LABEL, vitem->getLinkedUUID());

	LLInventoryModel::cat_array_t cat_array;
	LLInventoryModel::item_array_t item_array;
	gInventory.collectDescendents(LLAppearanceMgr::getCOF(),
								  cat_array,
								  item_array,
								  LLInventoryModel::EXCLUDE_TRASH);
	bool linked_already = false;
	for (S32 i=0; i<item_array.size(); i++)
	{
		// Are these links to the same object?
		const LLViewerInventoryItem* inv_item = item_array.at(i).get();
		const LLWearableType::EType wearable_type = inv_item->getWearableType();

		const bool is_body_part =    (wearable_type == LLWearableType::WT_SHAPE) 
								  || (wearable_type == LLWearableType::WT_HAIR) 
								  || (wearable_type == LLWearableType::WT_EYES)
								  || (wearable_type == LLWearableType::WT_SKIN);

		if (inv_item->getLinkedUUID() == vitem->getLinkedUUID())
		{
			linked_already = true;
		}
		// Are these links to different items of the same body part
		// type? If so, new item will replace old.
		else if ((vitem->isWearableType()) && (vitem->getWearableType() == wearable_type))
		{
			if (is_body_part && inv_item->getIsLinkType())
			{
				remove_inventory_item(inv_item->getUUID(), cb);
			}
			else if (!gAgentWearables.canAddWearable(wearable_type))
			{
				// MULTI-WEARABLES: make sure we don't go over clothing limits
				remove_inventory_item(inv_item->getUUID(), cb);
			}
		}
	}

	if (!linked_already)
	{
		LLViewerInventoryItem *copy_item = new LLViewerInventoryItem;
		copy_item->copyViewerItem(vitem);
		copy_item->setDescription(description);
		link_inventory_object(getCOF(), copy_item, cb);
	}
}

LLInventoryModel::item_array_t LLAppearanceMgr::findCOFItemLinks(const LLUUID& item_id)
{
	LLInventoryModel::item_array_t result;

    LLUUID linked_id = gInventory.getLinkedItemID(item_id);
    LLInventoryModel::cat_array_t cat_array;
    LLInventoryModel::item_array_t item_array;
    gInventory.collectDescendents(LLAppearanceMgr::getCOF(),
                                  cat_array,
                                  item_array,
                                  LLInventoryModel::EXCLUDE_TRASH);
    for (S32 i=0; i<item_array.size(); i++)
    {
        const LLViewerInventoryItem* inv_item = item_array.at(i).get();
        if (inv_item->getLinkedUUID() == linked_id)
        {
            result.push_back(item_array.at(i));
        }
    }
	return result;
}

bool LLAppearanceMgr::isLinkedInCOF(const LLUUID& item_id)
{
	LLInventoryModel::item_array_t links = LLAppearanceMgr::instance().findCOFItemLinks(item_id);
	return links.size() > 0;
}

void LLAppearanceMgr::removeAllClothesFromAvatar()
{
	// Fetch worn clothes (i.e. the ones in COF).
	LLInventoryModel::item_array_t clothing_items;
	LLInventoryModel::cat_array_t dummy;
	LLIsType is_clothing(LLAssetType::AT_CLOTHING);
	gInventory.collectDescendentsIf(getCOF(),
									dummy,
									clothing_items,
									LLInventoryModel::EXCLUDE_TRASH,
									is_clothing);
	uuid_vec_t item_ids;
	for (LLInventoryModel::item_array_t::iterator it = clothing_items.begin();
		it != clothing_items.end(); ++it)
	{
		item_ids.push_back((*it).get()->getLinkedUUID());
	}

	// Take them off by removing from COF.
	removeItemsFromAvatar(item_ids);
}

void LLAppearanceMgr::removeAllAttachmentsFromAvatar()
{
	if (!isAgentAvatarValid()) return;

	LLAgentWearables::llvo_vec_t objects_to_remove;
	
	for (LLVOAvatar::attachment_map_t::iterator iter = gAgentAvatarp->mAttachmentPoints.begin(); 
		 iter != gAgentAvatarp->mAttachmentPoints.end();)
	{
		LLVOAvatar::attachment_map_t::iterator curiter = iter++;
		LLViewerJointAttachment* attachment = curiter->second;
		for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
			 attachment_iter != attachment->mAttachedObjects.end();
			 ++attachment_iter)
		{
			LLViewerObject *attached_object = (*attachment_iter);
			if (attached_object)
			{
				objects_to_remove.push_back(attached_object);
			}
		}
	}
	uuid_vec_t ids_to_remove;
	for (LLAgentWearables::llvo_vec_t::iterator it = objects_to_remove.begin();
		 it != objects_to_remove.end();
		 ++it)
	{
		ids_to_remove.push_back((*it)->getAttachmentItemID());
	}
	removeItemsFromAvatar(ids_to_remove);
}

class LLUpdateOnCOFLinkRemove : public LLInventoryCallback
{
public:
	LLUpdateOnCOFLinkRemove(const LLUUID& remove_item_id, LLPointer<LLInventoryCallback> cb = NULL):
		mItemID(remove_item_id),
		mCB(cb)
	{
	}

	/* virtual */ void fire(const LLUUID& item_id)
	{
		// just removed cof link, "(wear)" suffix depends on presence of link, so update label
		gInventory.addChangedMask(LLInventoryObserver::LABEL, mItemID);
		if (mCB.notNull())
		{
			mCB->fire(item_id);
		}
	}

private:
	LLUUID mItemID;
	LLPointer<LLInventoryCallback> mCB;
};

void LLAppearanceMgr::removeCOFItemLinks(const LLUUID& item_id, LLPointer<LLInventoryCallback> cb)
{	LLInventoryModel::cat_array_t cat_array;
	LLInventoryModel::item_array_t item_array;
	gInventory.collectDescendents(LLAppearanceMgr::getCOF(),
								  cat_array,
								  item_array,
								  LLInventoryModel::EXCLUDE_TRASH);
	for (S32 i=0; i<item_array.size(); i++)
	{
		const LLInventoryItem* item = item_array.at(i).get();
		if (item->getIsLinkType() && item->getLinkedUUID() == item_id)
		{
			if (item->getType() == LLAssetType::AT_OBJECT)
			{
				// Immediate delete
				remove_inventory_item(item->getUUID(), cb, true);
				gInventory.addChangedMask(LLInventoryObserver::LABEL, item_id);
			}
			else
			{
				// Delayed delete
				// Pointless to update item_id label here since link still exists and first notifyObservers
				// call will restore (wear) suffix, mark for update after deletion
				LLPointer<LLUpdateOnCOFLinkRemove> cb_label = new LLUpdateOnCOFLinkRemove(item_id, cb);
				remove_inventory_item(item->getUUID(), cb_label, false);
			}
		}
	}
}

void LLAppearanceMgr::removeCOFLinksOfType(LLWearableType::EType type, LLPointer<LLInventoryCallback> cb)
{
	LLFindWearablesOfType filter_wearables_of_type(type);
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	LLInventoryModel::item_array_t::const_iterator it;

	gInventory.collectDescendentsIf(getCOF(), cats, items, true, filter_wearables_of_type);
	for (it = items.begin(); it != items.end(); ++it)
	{
		const LLViewerInventoryItem* item = *it;
		if (item->getIsLinkType()) // we must operate on links only
		{
			remove_inventory_item(item->getUUID(), cb);
		}
	}
}

bool sort_by_linked_uuid(const LLViewerInventoryItem* item1, const LLViewerInventoryItem* item2)
{
	if (!item1 || !item2)
	{
		LL_WARNS() << "item1, item2 cannot be null, something is very wrong" << LL_ENDL;
		return true;
	}

	return item1->getLinkedUUID() < item2->getLinkedUUID();
}

void LLAppearanceMgr::updateIsDirty()
{
	LLUUID cof = getCOF();
	LLUUID base_outfit;

	// find base outfit link 
	const LLViewerInventoryItem* base_outfit_item = getBaseOutfitLink();
	LLViewerInventoryCategory* catp = NULL;
	if (base_outfit_item && base_outfit_item->getIsLinkType())
	{
		catp = base_outfit_item->getLinkedCategory();
	}
	if(catp && catp->getPreferredType() == LLFolderType::FT_OUTFIT)
	{
		base_outfit = catp->getUUID();
	}

	// Set dirty to "false" if no base outfit found to disable "Save"
	// and leave only "Save As" enabled in My Outfits.
	mOutfitIsDirty = false;

	if (base_outfit.notNull())
	{
		LLIsValidItemLink collector;

		LLInventoryModel::cat_array_t cof_cats;
		LLInventoryModel::item_array_t cof_items;
		gInventory.collectDescendentsIf(cof, cof_cats, cof_items,
									  LLInventoryModel::EXCLUDE_TRASH, collector);

		LLInventoryModel::cat_array_t outfit_cats;
		LLInventoryModel::item_array_t outfit_items;
		gInventory.collectDescendentsIf(base_outfit, outfit_cats, outfit_items,
									  LLInventoryModel::EXCLUDE_TRASH, collector);

		for (U32 i = 0; i < outfit_items.size(); ++i)
		{
			LLViewerInventoryItem* linked_item = outfit_items.at(i)->getLinkedItem();
			if (linked_item != NULL && linked_item->getActualType() == LLAssetType::AT_TEXTURE)
			{
				outfit_items.erase(outfit_items.begin() + i);
				break;
			}
		}

		if(outfit_items.size() != cof_items.size())
		{
			LL_DEBUGS("Avatar") << "item count different - base " << outfit_items.size() << " cof " << cof_items.size() << LL_ENDL;
			// Current outfit folder should have one more item than the outfit folder.
			// this one item is the link back to the outfit folder itself.
			mOutfitIsDirty = true;
			return;
		}

		//"dirty" - also means a difference in linked UUIDs and/or a difference in wearables order (links' descriptions)
		std::sort(cof_items.begin(), cof_items.end(), sort_by_linked_uuid);
		std::sort(outfit_items.begin(), outfit_items.end(), sort_by_linked_uuid);

		for (U32 i = 0; i < cof_items.size(); ++i)
		{
			LLViewerInventoryItem *item1 = cof_items.at(i);
			LLViewerInventoryItem *item2 = outfit_items.at(i);

			if (item1->getLinkedUUID() != item2->getLinkedUUID() || 
				item1->getName() != item2->getName() ||
				item1->getActualDescription() != item2->getActualDescription())
			{
				if (item1->getLinkedUUID() != item2->getLinkedUUID())
				{
					LL_DEBUGS("Avatar") << "link id different " << LL_ENDL;
				}
				else
				{
					if (item1->getName() != item2->getName())
					{
						LL_DEBUGS("Avatar") << "name different " << item1->getName() << " " << item2->getName() << LL_ENDL;
					}
					if (item1->getActualDescription() != item2->getActualDescription())
					{
						LL_DEBUGS("Avatar") << "desc different " << item1->getActualDescription()
											<< " " << item2->getActualDescription() 
											<< " names " << item1->getName() << " " << item2->getName() << LL_ENDL;
					}
				}
				mOutfitIsDirty = true;
				return;
			}
		}
	}
	llassert(!mOutfitIsDirty);
	LL_DEBUGS("Avatar") << "clean" << LL_ENDL;
}

// *HACK: Must match name in Library or agent inventory
const std::string ROOT_GESTURES_FOLDER = "Gestures";
const std::string COMMON_GESTURES_FOLDER = "Common Gestures";
const std::string MALE_GESTURES_FOLDER = "Male Gestures";
const std::string FEMALE_GESTURES_FOLDER = "Female Gestures";
const std::string SPEECH_GESTURES_FOLDER = "Speech Gestures";
const std::string OTHER_GESTURES_FOLDER = "Other Gestures";

void LLAppearanceMgr::copyLibraryGestures()
{
	LL_INFOS("Avatar") << self_av_string() << "Copying library gestures" << LL_ENDL;

	// Copy gestures
	LLUUID lib_gesture_cat_id =
		gInventory.findLibraryCategoryUUIDForType(LLFolderType::FT_GESTURE,false);
	if (lib_gesture_cat_id.isNull())
	{
		LL_WARNS() << "Unable to copy gestures, source category not found" << LL_ENDL;
	}
	LLUUID dst_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_GESTURE);

	std::vector<std::string> gesture_folders_to_copy;
	gesture_folders_to_copy.push_back(MALE_GESTURES_FOLDER);
	gesture_folders_to_copy.push_back(FEMALE_GESTURES_FOLDER);
	gesture_folders_to_copy.push_back(COMMON_GESTURES_FOLDER);
	gesture_folders_to_copy.push_back(SPEECH_GESTURES_FOLDER);
	gesture_folders_to_copy.push_back(OTHER_GESTURES_FOLDER);

	for(std::vector<std::string>::iterator it = gesture_folders_to_copy.begin();
		it != gesture_folders_to_copy.end();
		++it)
	{
		std::string& folder_name = *it;

		LLPointer<LLInventoryCallback> cb(NULL);

		// After copying gestures, activate Common, Other, plus
		// Male and/or Female, depending upon the initial outfit gender.
		ESex gender = gAgentAvatarp->getSex();

		std::string activate_male_gestures;
		std::string activate_female_gestures;
		switch (gender) {
			case SEX_MALE:
				activate_male_gestures = MALE_GESTURES_FOLDER;
				break;
			case SEX_FEMALE:
				activate_female_gestures = FEMALE_GESTURES_FOLDER;
				break;
			case SEX_BOTH:
				activate_male_gestures = MALE_GESTURES_FOLDER;
				activate_female_gestures = FEMALE_GESTURES_FOLDER;
				break;
		}

		if (folder_name == activate_male_gestures ||
			folder_name == activate_female_gestures ||
			folder_name == COMMON_GESTURES_FOLDER ||
			folder_name == OTHER_GESTURES_FOLDER)
		{
			cb = new LLBoostFuncInventoryCallback(activate_gesture_cb);
		}

		LLUUID cat_id = findDescendentCategoryIDByName(lib_gesture_cat_id,folder_name);
		if (cat_id.isNull())
		{
			LL_WARNS() << self_av_string() << "failed to find gesture folder for " << folder_name << LL_ENDL;
		}
		else
		{
			LL_DEBUGS("Avatar") << self_av_string() << "initiating fetch and copy for " << folder_name << " cat_id " << cat_id << LL_ENDL;
			callAfterCategoryFetch(cat_id,
								   boost::bind(&LLAppearanceMgr::shallowCopyCategory,
											   &LLAppearanceMgr::instance(),
											   cat_id, dst_id, cb));
		}
	}
}

// Handler for anything that's deferred until avatar de-clouds.
void LLAppearanceMgr::onFirstFullyVisible()
{
	gAgentAvatarp->outputRezTiming("Avatar fully loaded");
	gAgentAvatarp->reportAvatarRezTime();
	gAgentAvatarp->debugAvatarVisible();

	// If this is the first time we've ever logged in,
	// then copy default gestures from the library.
	if (gAgent.isFirstLogin()) {
		copyLibraryGestures();
	}
}

// update "dirty" state - defined outside class to allow for calling
// after appearance mgr instance has been destroyed.
void appearance_mgr_update_dirty_state()
{
	if (LLAppearanceMgr::instanceExists())
	{
		LLAppearanceMgr& app_mgr = LLAppearanceMgr::instance();
		LLUUID image_id = app_mgr.getOutfitImage();
		if(image_id.notNull())
		{
			LLPointer<LLInventoryCallback> cb = NULL;
			link_inventory_object(app_mgr.getBaseOutfitUUID(), image_id, cb);
		}

		LLAppearanceMgr::getInstance()->updateIsDirty();
		LLAppearanceMgr::getInstance()->setOutfitLocked(false);
		gAgentWearables.notifyLoadingFinished();
	}
}

void update_base_outfit_after_ordering()
{
	LLAppearanceMgr& app_mgr = LLAppearanceMgr::instance();
	app_mgr.setOutfitImage(LLUUID());
	LLInventoryModel::cat_array_t sub_cat_array;
	LLInventoryModel::item_array_t outfit_item_array;
	gInventory.collectDescendents(app_mgr.getBaseOutfitUUID(),
								sub_cat_array,
								outfit_item_array,
								LLInventoryModel::EXCLUDE_TRASH);
	BOOST_FOREACH(LLViewerInventoryItem* outfit_item, outfit_item_array)
	{
		LLViewerInventoryItem* linked_item = outfit_item->getLinkedItem();
		if (linked_item != NULL)
		{
			if (linked_item->getActualType() == LLAssetType::AT_TEXTURE)
			{
				app_mgr.setOutfitImage(linked_item->getLinkedUUID());
				if (linked_item->getName() == LLAppearanceMgr::sExpectedTextureName)
				{
					// Images with "appropriate" name take priority
					break;
				}
			}
		}
		else if (outfit_item->getActualType() == LLAssetType::AT_TEXTURE)
		{
			app_mgr.setOutfitImage(outfit_item->getUUID());
			if (outfit_item->getName() == LLAppearanceMgr::sExpectedTextureName)
			{
				// Images with "appropriate" name take priority
				break;
			}
		}
	}

	LLPointer<LLInventoryCallback> dirty_state_updater =
		new LLBoostFuncInventoryCallback(no_op_inventory_func, appearance_mgr_update_dirty_state);

	//COF contains only links so we copy to the Base Outfit only links
	const LLUUID base_outfit_id = app_mgr.getBaseOutfitUUID();
	bool copy_folder_links = false;
	app_mgr.slamCategoryLinks(app_mgr.getCOF(), base_outfit_id, copy_folder_links, dirty_state_updater);

}

// Save COF changes - update the contents of the current base outfit
// to match the current COF. Fails if no current base outfit is set.
bool LLAppearanceMgr::updateBaseOutfit()
{
	if (isOutfitLocked())
	{
		// don't allow modify locked outfit
		llassert(!isOutfitLocked());
		return false;
	}

	setOutfitLocked(true);

	gAgentWearables.notifyLoadingStarted();

	const LLUUID base_outfit_id = getBaseOutfitUUID();
	if (base_outfit_id.isNull()) return false;
	LL_DEBUGS("Avatar") << "saving cof to base outfit " << base_outfit_id << LL_ENDL;

	LLPointer<LLInventoryCallback> cb =
		new LLBoostFuncInventoryCallback(no_op_inventory_func, update_base_outfit_after_ordering);
	// Really shouldn't be needed unless there's a race condition -
	// updateAppearanceFromCOF() already calls updateClothingOrderingInfo.
	updateClothingOrderingInfo(LLUUID::null, cb);

	return true;
}

void LLAppearanceMgr::divvyWearablesByType(const LLInventoryModel::item_array_t& items, wearables_by_type_t& items_by_type)
{
	items_by_type.resize(LLWearableType::WT_COUNT);
	if (items.empty()) return;

	for (S32 i=0; i<items.size(); i++)
	{
		LLViewerInventoryItem *item = items.at(i);
		if (!item)
		{
			LL_WARNS("Appearance") << "NULL item found" << LL_ENDL;
			continue;
		}
		// Ignore non-wearables.
		if (!item->isWearableType())
			continue;
		LLWearableType::EType type = item->getWearableType();
		if(type < 0 || type >= LLWearableType::WT_COUNT)
		{
			LL_WARNS("Appearance") << "Invalid wearable type. Inventory type does not match wearable flag bitfield." << LL_ENDL;
			continue;
		}
		items_by_type[type].push_back(item);
	}
}

std::string build_order_string(LLWearableType::EType type, U32 i)
{
		std::ostringstream order_num;
		order_num << ORDER_NUMBER_SEPARATOR << type * 100 + i;
		return order_num.str();
}

struct WearablesOrderComparator
{
	LOG_CLASS(WearablesOrderComparator);
	WearablesOrderComparator(const LLWearableType::EType type)
	{
		mControlSize = build_order_string(type, 0).size();
	};

	bool operator()(const LLInventoryItem* item1, const LLInventoryItem* item2)
	{
		const std::string& desc1 = item1->getActualDescription();
		const std::string& desc2 = item2->getActualDescription();
		
		bool item1_valid = (desc1.size() == mControlSize) && (ORDER_NUMBER_SEPARATOR == desc1[0]);
		bool item2_valid = (desc2.size() == mControlSize) && (ORDER_NUMBER_SEPARATOR == desc2[0]);

		if (item1_valid && item2_valid)
			return desc1 < desc2;

		//we need to sink down invalid items: items with empty descriptions, items with "Broken link" descriptions,
		//items with ordering information but not for the associated wearables type
		if (!item1_valid && item2_valid) 
			return false;
		else if (item1_valid && !item2_valid)
			return true;

		return item1->getName() < item2->getName();
	}

	U32 mControlSize;
};

void LLAppearanceMgr::getWearableOrderingDescUpdates(LLInventoryModel::item_array_t& wear_items,
													 desc_map_t& desc_map)
{
	wearables_by_type_t items_by_type(LLWearableType::WT_COUNT);
	divvyWearablesByType(wear_items, items_by_type);

	for (U32 type = LLWearableType::WT_SHIRT; type < LLWearableType::WT_COUNT; type++)
	{
		U32 size = items_by_type[type].size();
		if (!size) continue;
		
		//sinking down invalid items which need reordering
		std::sort(items_by_type[type].begin(), items_by_type[type].end(), WearablesOrderComparator((LLWearableType::EType) type));
		
		//requesting updates only for those links which don't have "valid" descriptions
		for (U32 i = 0; i < size; i++)
		{
			LLViewerInventoryItem* item = items_by_type[type][i];
			if (!item) continue;
			
			std::string new_order_str = build_order_string((LLWearableType::EType)type, i);
			if (new_order_str == item->getActualDescription()) continue;
			
			desc_map[item->getUUID()] = new_order_str;
		}
	}
}

bool LLAppearanceMgr::validateClothingOrderingInfo(LLUUID cat_id)
{
	// COF is processed if cat_id is not specified
	if (cat_id.isNull())
	{
		cat_id = getCOF();
	}

	LLInventoryModel::item_array_t wear_items;
	getDescendentsOfAssetType(cat_id, wear_items, LLAssetType::AT_CLOTHING);

	// Identify items for which desc needs to change.
	desc_map_t desc_map;
	getWearableOrderingDescUpdates(wear_items, desc_map);

	for (desc_map_t::const_iterator it = desc_map.begin();
		 it != desc_map.end(); ++it)
	{
		const LLUUID& item_id = it->first;
		const std::string& new_order_str = it->second;
		LLViewerInventoryItem *item = gInventory.getItem(item_id);
		LL_WARNS() << "Order validation fails: " << item->getName()
				<< " needs to update desc to: " << new_order_str
				<< " (from: " << item->getActualDescription() << ")" << LL_ENDL;
	}
	
	return desc_map.size() == 0;
}

void LLAppearanceMgr::updateClothingOrderingInfo(LLUUID cat_id,
												 LLPointer<LLInventoryCallback> cb)
{
	// COF is processed if cat_id is not specified
	if (cat_id.isNull())
	{
		cat_id = getCOF();
	}

	LLInventoryModel::item_array_t wear_items;
	getDescendentsOfAssetType(cat_id, wear_items, LLAssetType::AT_CLOTHING);

	// Identify items for which desc needs to change.
	desc_map_t desc_map;
	getWearableOrderingDescUpdates(wear_items, desc_map);

	for (desc_map_t::const_iterator it = desc_map.begin();
		 it != desc_map.end(); ++it)
	{
		LLSD updates;
		const LLUUID& item_id = it->first;
		const std::string& new_order_str = it->second;
		LLViewerInventoryItem *item = gInventory.getItem(item_id);
		LL_DEBUGS("Avatar") << item->getName() << " updating desc to: " << new_order_str
			<< " (was: " << item->getActualDescription() << ")" << LL_ENDL;
		updates["desc"] = new_order_str;
		update_inventory_item(item_id,updates,cb);
	}
		
}


LLSD LLAppearanceMgr::dumpCOF() const
{
	LLSD links = LLSD::emptyArray();
	LLMD5 md5;
	
	LLInventoryModel::cat_array_t cat_array;
	LLInventoryModel::item_array_t item_array;
	gInventory.collectDescendents(getCOF(),cat_array,item_array,LLInventoryModel::EXCLUDE_TRASH);
	for (S32 i=0; i<item_array.size(); i++)
	{
		const LLViewerInventoryItem* inv_item = item_array.at(i).get();
		LLSD item;
		LLUUID item_id(inv_item->getUUID());
		md5.update((unsigned char*)item_id.mData, 16);
		item["description"] = inv_item->getActualDescription();
		md5.update(inv_item->getActualDescription());
		item["asset_type"] = inv_item->getActualType();
		LLUUID linked_id(inv_item->getLinkedUUID());
		item["linked_id"] = linked_id;
		md5.update((unsigned char*)linked_id.mData, 16);

		if (LLAssetType::AT_LINK == inv_item->getActualType())
		{
			const LLViewerInventoryItem* linked_item = inv_item->getLinkedItem();
			if (NULL == linked_item)
			{
				LL_WARNS() << "Broken link for item '" << inv_item->getName()
						<< "' (" << inv_item->getUUID()
						<< ") during requestServerAppearanceUpdate" << LL_ENDL;
				continue;
			}
			// Some assets may be 'hidden' and show up as null in the viewer.
			//if (linked_item->getAssetUUID().isNull())
			//{
			//	LL_WARNS() << "Broken link (null asset) for item '" << inv_item->getName()
			//			<< "' (" << inv_item->getUUID()
			//			<< ") during requestServerAppearanceUpdate" << LL_ENDL;
			//	continue;
			//}
			LLUUID linked_asset_id(linked_item->getAssetUUID());
			md5.update((unsigned char*)linked_asset_id.mData, 16);
			U32 flags = linked_item->getFlags();
			md5.update(boost::lexical_cast<std::string>(flags));
		}
		else if (LLAssetType::AT_LINK_FOLDER != inv_item->getActualType())
		{
			LL_WARNS() << "Non-link item '" << inv_item->getName()
					<< "' (" << inv_item->getUUID()
					<< ") type " << (S32) inv_item->getActualType()
					<< " during requestServerAppearanceUpdate" << LL_ENDL;
			continue;
		}
		links.append(item);
	}
	LLSD result = LLSD::emptyMap();
	result["cof_contents"] = links;
	char cof_md5sum[MD5HEX_STR_SIZE];
	md5.finalize();
	md5.hex_digest(cof_md5sum);
	result["cof_md5sum"] = std::string(cof_md5sum);
	return result;
}

// static
void LLAppearanceMgr::onIdle(void *)
{
    LLAppearanceMgr* mgr = LLAppearanceMgr::getInstance();
    if (mgr->mRerequestAppearanceBake)
    {
        mgr->requestServerAppearanceUpdate();
    }
}

void LLAppearanceMgr::requestServerAppearanceUpdate()
{
    // Workaround: we shouldn't request update from server prior to uploading all attachments, but it is
    // complicated to check for pending attachment uploads, so we are just waiting for uploads to complete
    if (!mOutstandingAppearanceBakeRequest && gAssetStorage->getNumPendingUploads() == 0)
    {
        mRerequestAppearanceBake = false;
        LLCoprocedureManager::CoProcedure_t proc = boost::bind(&LLAppearanceMgr::serverAppearanceUpdateCoro, this, _1);
        LLCoprocedureManager::instance().enqueueCoprocedure("AIS", "LLAppearanceMgr::serverAppearanceUpdateCoro", proc);
    }
    else
    {
        // Shedule update
        mRerequestAppearanceBake = true;
    }
}

void LLAppearanceMgr::serverAppearanceUpdateCoro(LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t &httpAdapter)
{
    BoolSetter outstanding(mOutstandingAppearanceBakeRequest);
    if (!gAgent.getRegion())
    {
        LL_WARNS("Avatar") << "Region not set, cannot request server appearance update" << LL_ENDL;
        return;
    }
    if (gAgent.getRegion()->getCentralBakeVersion() == 0)
    {
        LL_WARNS("Avatar") << "Region does not support baking" << LL_ENDL;
        return;
    }

    std::string url = gAgent.getRegion()->getCapability("UpdateAvatarAppearance");
    if (url.empty())
    {
        LL_WARNS("Agent") << "Could not retrieve region capability \"UpdateAvatarAppearance\"" << LL_ENDL;
        return;
    }

    //----------------
    if (gAgentAvatarp->isEditingAppearance())
    {
        LL_WARNS("Avatar") << "Avatar editing appearance, not sending request." << LL_ENDL;
        // don't send out appearance updates if in appearance editing mode
        return;
    }

    llcoro::suspend();
    S32 retryCount(0);
    bool bRetry;
    do
    {
        // If we have already received an update for this or higher cof version, 
        // put a warning in the log and cancel the request.
        S32 cofVersion = getCOFVersion();
        S32 lastRcv = gAgentAvatarp->mLastUpdateReceivedCOFVersion;
        S32 lastReq = gAgentAvatarp->mLastUpdateRequestCOFVersion;

        LL_INFOS("Avatar") << "Requesting COF version " << cofVersion <<
            " (Last Received:" << lastRcv << ")" <<
            " (Last Requested:" << lastReq << ")" << LL_ENDL;

        if (cofVersion == LLViewerInventoryCategory::VERSION_UNKNOWN)
        {
            LL_WARNS("AVatar") << "COF version is unknown... not requesting until COF version is known." << LL_ENDL;
            return;
        }
        else
        {
            if (cofVersion <= lastRcv)
            {
                LL_WARNS("Avatar") << "Have already received update for cof version " << lastRcv
                    << " but requesting for " << cofVersion << LL_ENDL;
                return;
            }
            if (lastReq >= cofVersion)
            {
                LL_WARNS("Avatar") << "Request already in flight for cof version " << lastReq
                    << " but requesting for " << cofVersion << LL_ENDL;
                return;
            }
        }

        // Actually send the request.
        LL_DEBUGS("Avatar") << "Will send request for cof_version " << cofVersion << LL_ENDL;

        bRetry = false;
        LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest());

        if (gSavedSettings.getBOOL("DebugForceAppearanceRequestFailure"))
        {
            cofVersion += 999;
            LL_WARNS("Avatar") << "Forcing version failure on COF Baking" << LL_ENDL;
        }

        LL_INFOS("Avatar") << "Requesting bake for COF version " << cofVersion << LL_ENDL;

        LLSD postData;
        if (gSavedSettings.getBOOL("DebugAvatarExperimentalServerAppearanceUpdate"))
        {
            postData = dumpCOF();
        }
        else
        {
            postData["cof_version"] = cofVersion;
        }

        gAgentAvatarp->mLastUpdateRequestCOFVersion = cofVersion;

        LLSD result = httpAdapter->postAndSuspend(httpRequest, url, postData);

        LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
        LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);

        if (!status || !result["success"].asBoolean())
        {
            std::string message = (result.has("error")) ? result["error"].asString() : status.toString();
            LL_WARNS("Avatar") << "Appearance Failure. server responded with \"" << message << "\"" << LL_ENDL;

            // We may have requested a bake for a stale COF (especially if the inventory 
            // is still updating.  If that is the case re send the request with the 
            // corrected COF version.  (This may also be the case if the viewer is running 
            // on multiple machines.
            if (result.has("expected"))
            {
                S32 expectedCofVersion = result["expected"].asInteger();
                LL_WARNS("Avatar") << "Server expected " << expectedCofVersion << " as COF version" << LL_ENDL;

                // Force an update texture request for ourself.  The message will return
                // through the UDP and be handled in LLVOAvatar::processAvatarAppearance
                // this should ensure that we receive a new canonical COF from the sim
                // host. Hopefully it will return before the timeout.
                LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(gAgent.getID());

                bRetry = true;
                // Wait for a 1/2 second before trying again.  Just to keep from asking too quickly.
                if (++retryCount > BAKE_RETRY_MAX_COUNT)
                {
                    LL_WARNS("Avatar") << "Bake retry count exceeded!" << LL_ENDL;
                    break;
                }
                F32 timeout = pow(BAKE_RETRY_TIMEOUT, static_cast<float>(retryCount)) - 1.0;

                LL_WARNS("Avatar") << "Bake retry #" << retryCount << " in " << timeout << " seconds." << LL_ENDL;

                llcoro::suspendUntilTimeout(timeout); 
                bRetry = true;
                continue;
            }
            else
            {
                LL_WARNS("Avatar") << "No retry attempted." << LL_ENDL;
                break;
            }
        }

        LL_DEBUGS("Avatar") << "succeeded" << LL_ENDL;
        if (gSavedSettings.getBOOL("DebugAvatarAppearanceMessage"))
        {
            dump_sequential_xml(gAgentAvatarp->getFullname() + "_appearance_request_ok", result);
        }

    } while (bRetry);
}

/*static*/
void LLAppearanceMgr::debugAppearanceUpdateCOF(const LLSD& content)
{
    dump_sequential_xml(gAgentAvatarp->getFullname() + "_appearance_request_error", content);

    LL_INFOS("Avatar") << "AIS COF, version received: " << content["expected"].asInteger()
        << " ================================= " << LL_ENDL;
    std::set<LLUUID> ais_items, local_items;
    const LLSD& cof_raw = content["cof_raw"];
    for (LLSD::array_const_iterator it = cof_raw.beginArray();
        it != cof_raw.endArray(); ++it)
    {
        const LLSD& item = *it;
        if (item["parent_id"].asUUID() == LLAppearanceMgr::instance().getCOF())
        {
            ais_items.insert(item["item_id"].asUUID());
            if (item["type"].asInteger() == 24) // link
            {
                LL_INFOS("Avatar") << "AIS Link: item_id: " << item["item_id"].asUUID()
                    << " linked_item_id: " << item["asset_id"].asUUID()
                    << " name: " << item["name"].asString()
                    << LL_ENDL;
            }
            else if (item["type"].asInteger() == 25) // folder link
            {
                LL_INFOS("Avatar") << "AIS Folder link: item_id: " << item["item_id"].asUUID()
                    << " linked_item_id: " << item["asset_id"].asUUID()
                    << " name: " << item["name"].asString()
                    << LL_ENDL;
            }
            else
            {
                LL_INFOS("Avatar") << "AIS Other: item_id: " << item["item_id"].asUUID()
                    << " linked_item_id: " << item["asset_id"].asUUID()
                    << " name: " << item["name"].asString()
                    << " type: " << item["type"].asInteger()
                    << LL_ENDL;
            }
        }
    }
    LL_INFOS("Avatar") << LL_ENDL;
    LL_INFOS("Avatar") << "Local COF, version requested: " << content["observed"].asInteger()
        << " ================================= " << LL_ENDL;
    LLInventoryModel::cat_array_t cat_array;
    LLInventoryModel::item_array_t item_array;
    gInventory.collectDescendents(LLAppearanceMgr::instance().getCOF(),
        cat_array, item_array, LLInventoryModel::EXCLUDE_TRASH);
    for (S32 i = 0; i < item_array.size(); i++)
    {
        const LLViewerInventoryItem* inv_item = item_array.at(i).get();
        local_items.insert(inv_item->getUUID());
        LL_INFOS("Avatar") << "LOCAL: item_id: " << inv_item->getUUID()
            << " linked_item_id: " << inv_item->getLinkedUUID()
            << " name: " << inv_item->getName()
            << " parent: " << inv_item->getParentUUID()
            << LL_ENDL;
    }
    LL_INFOS("Avatar") << " ================================= " << LL_ENDL;
    S32 local_only = 0, ais_only = 0;
    for (std::set<LLUUID>::iterator it = local_items.begin(); it != local_items.end(); ++it)
    {
        if (ais_items.find(*it) == ais_items.end())
        {
            LL_INFOS("Avatar") << "LOCAL ONLY: " << *it << LL_ENDL;
            local_only++;
        }
    }
    for (std::set<LLUUID>::iterator it = ais_items.begin(); it != ais_items.end(); ++it)
    {
        if (local_items.find(*it) == local_items.end())
        {
            LL_INFOS("Avatar") << "AIS ONLY: " << *it << LL_ENDL;
            ais_only++;
        }
    }
    if (local_only == 0 && ais_only == 0)
    {
        LL_INFOS("Avatar") << "COF contents identical, only version numbers differ (req "
            << content["observed"].asInteger()
            << " rcv " << content["expected"].asInteger()
            << ")" << LL_ENDL;
    }
}


std::string LLAppearanceMgr::getAppearanceServiceURL() const
{
	if (gSavedSettings.getString("DebugAvatarAppearanceServiceURLOverride").empty())
	{
		return mAppearanceServiceURL;
	}
	return gSavedSettings.getString("DebugAvatarAppearanceServiceURLOverride");
}

void show_created_outfit(LLUUID& folder_id, bool show_panel = true)
{
	if (!LLApp::isRunning())
	{
		LL_WARNS() << "called during shutdown, skipping" << LL_ENDL;
		return;
	}
	
	LL_DEBUGS("Avatar") << "called" << LL_ENDL;
	LLSD key;
	
	//EXT-7727. For new accounts inventory callback is created during login process
	// and may be processed after login process is finished
	if (show_panel)
	{
		LL_DEBUGS("Avatar") << "showing panel" << LL_ENDL;
		LLFloaterSidePanelContainer::showPanel("appearance", "panel_outfits_inventory", key);
		
	}
	LLOutfitsList *outfits_list =
		dynamic_cast<LLOutfitsList*>(LLFloaterSidePanelContainer::getPanel("appearance", "outfitslist_tab"));
	if (outfits_list)
	{
		outfits_list->setSelectedOutfitByUUID(folder_id);
	}
	
	LLAppearanceMgr::getInstance()->updateIsDirty();
	gAgentWearables.notifyLoadingFinished(); // New outfit is saved.
	LLAppearanceMgr::getInstance()->updatePanelOutfitName("");

	// For SSB, need to update appearance after we add a base outfit
	// link, since, the COF version has changed. There is a race
	// condition in initial outfit setup which can lead to rez
	// failures - SH-3860.
	LL_DEBUGS("Avatar") << "requesting appearance update after createBaseOutfitLink" << LL_ENDL;
	LLPointer<LLInventoryCallback> cb = new LLUpdateAppearanceOnDestroy;
	LLAppearanceMgr::getInstance()->createBaseOutfitLink(folder_id, cb);
}

void LLAppearanceMgr::onOutfitFolderCreated(const LLUUID& folder_id, bool show_panel)
{
	LLPointer<LLInventoryCallback> cb =
		new LLBoostFuncInventoryCallback(no_op_inventory_func,
										 boost::bind(&LLAppearanceMgr::onOutfitFolderCreatedAndClothingOrdered,this,folder_id,show_panel));
	updateClothingOrderingInfo(LLUUID::null, cb);
}

void LLAppearanceMgr::onOutfitFolderCreatedAndClothingOrdered(const LLUUID& folder_id, bool show_panel)
{
	LLPointer<LLInventoryCallback> cb =
		new LLBoostFuncInventoryCallback(no_op_inventory_func,
										 boost::bind(show_created_outfit,folder_id,show_panel));
	bool copy_folder_links = false;
	slamCategoryLinks(getCOF(), folder_id, copy_folder_links, cb);
}

void LLAppearanceMgr::makeNewOutfitLinks(const std::string& new_folder_name, bool show_panel)
{
	if (!isAgentAvatarValid()) return;

	LL_DEBUGS("Avatar") << "creating new outfit" << LL_ENDL;

	gAgentWearables.notifyLoadingStarted();

	// First, make a folder in the My Outfits directory.
	const LLUUID parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MY_OUTFITS);
    if (AISAPI::isAvailable())
	{
		// cap-based category creation was buggy until recently. use
		// existence of AIS as an indicator the fix is present. Does
		// not actually use AIS to create the category.
		inventory_func_type func = boost::bind(&LLAppearanceMgr::onOutfitFolderCreated,this,_1,show_panel);
		LLUUID folder_id = gInventory.createNewCategory(
			parent_id,
			LLFolderType::FT_OUTFIT,
			new_folder_name,
			func);
	}
	else
	{		
		LLUUID folder_id = gInventory.createNewCategory(
			parent_id,
			LLFolderType::FT_OUTFIT,
			new_folder_name);
		onOutfitFolderCreated(folder_id, show_panel);
	}
}

void LLAppearanceMgr::wearBaseOutfit()
{
	const LLUUID& base_outfit_id = getBaseOutfitUUID();
	if (base_outfit_id.isNull()) return;
	
	updateCOF(base_outfit_id);
}

void LLAppearanceMgr::removeItemsFromAvatar(const uuid_vec_t& ids_to_remove)
{
	if (ids_to_remove.empty())
	{
		LL_WARNS() << "called with empty list, nothing to do" << LL_ENDL;
		return;
	}
	LLPointer<LLInventoryCallback> cb = new LLUpdateAppearanceOnDestroy;
	for (uuid_vec_t::const_iterator it = ids_to_remove.begin(); it != ids_to_remove.end(); ++it)
	{
		const LLUUID& id_to_remove = *it;
		const LLUUID& linked_item_id = gInventory.getLinkedItemID(id_to_remove);
		LLViewerInventoryItem *item = gInventory.getItem(linked_item_id);
		if (item && item->getType() == LLAssetType::AT_OBJECT)
		{
			LL_DEBUGS("Avatar") << "ATT removing attachment " << item->getName() << " id " << item->getUUID() << LL_ENDL;
		}
		if (item && item->getType() == LLAssetType::AT_BODYPART)
		{
		    continue;
		}
		removeCOFItemLinks(linked_item_id, cb);
		addDoomedTempAttachment(linked_item_id);
	}
}

void LLAppearanceMgr::removeItemFromAvatar(const LLUUID& id_to_remove)
{
	uuid_vec_t ids_to_remove;
	ids_to_remove.push_back(id_to_remove);
	removeItemsFromAvatar(ids_to_remove);
}


// Adds the given item ID to mDoomedTempAttachmentIDs iff it's a temp attachment
void LLAppearanceMgr::addDoomedTempAttachment(const LLUUID& id_to_remove)
{
	LLViewerObject * attachmentp = gAgentAvatarp->findAttachmentByID(id_to_remove);
	if (attachmentp &&
		attachmentp->isTempAttachment())
	{	// If this is a temp attachment and we want to remove it, record the ID 
		// so it will be deleted when attachments are synced up with COF
		mDoomedTempAttachmentIDs.insert(id_to_remove);
		//LL_INFOS() << "Will remove temp attachment id " << id_to_remove << LL_ENDL;
	}
}

// Find AND REMOVES the given UUID from mDoomedTempAttachmentIDs
bool LLAppearanceMgr::shouldRemoveTempAttachment(const LLUUID& item_id)
{
	doomed_temp_attachments_t::iterator iter = mDoomedTempAttachmentIDs.find(item_id);
	if (iter != mDoomedTempAttachmentIDs.end())
	{
		mDoomedTempAttachmentIDs.erase(iter);
		return true;
	}
	return false;
}


bool LLAppearanceMgr::moveWearable(LLViewerInventoryItem* item, bool closer_to_body)
{
	if (!item || !item->isWearableType()) return false;
	if (item->getType() != LLAssetType::AT_CLOTHING) return false;
	if (!gInventory.isObjectDescendentOf(item->getUUID(), getCOF())) return false;

	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	LLFindWearablesOfType filter_wearables_of_type(item->getWearableType());
	gInventory.collectDescendentsIf(getCOF(), cats, items, true, filter_wearables_of_type);
	if (items.empty()) return false;

	// We assume that the items have valid descriptions.
	std::sort(items.begin(), items.end(), WearablesOrderComparator(item->getWearableType()));

	if (closer_to_body && items.front() == item) return false;
	if (!closer_to_body && items.back() == item) return false;
	
	LLInventoryModel::item_array_t::iterator it = std::find(items.begin(), items.end(), item);
	if (items.end() == it) return false;


	//swapping descriptions
	closer_to_body ? --it : ++it;
	LLViewerInventoryItem* swap_item = *it;
	if (!swap_item) return false;
	std::string tmp = swap_item->getActualDescription();
	swap_item->setDescription(item->getActualDescription());
	item->setDescription(tmp);

	// LL_DEBUGS("Inventory") << "swap, item "
	// 					   << ll_pretty_print_sd(item->asLLSD())
	// 					   << " swap_item "
	// 					   << ll_pretty_print_sd(swap_item->asLLSD()) << LL_ENDL;

	// FIXME switch to use AISv3 where supported.
	//items need to be updated on a dataserver
	item->setComplete(TRUE);
	item->updateServer(FALSE);
	gInventory.updateItem(item);

	swap_item->setComplete(TRUE);
	swap_item->updateServer(FALSE);
	gInventory.updateItem(swap_item);

	//to cause appearance of the agent to be updated
	bool result = false;
	if ((result = gAgentWearables.moveWearable(item, closer_to_body)))
	{
		gAgentAvatarp->wearableUpdated(item->getWearableType());
	}

	setOutfitDirty(true);

	//*TODO do we need to notify observers here in such a way?
	gInventory.notifyObservers();

	return result;
}

//static
void LLAppearanceMgr::sortItemsByActualDescription(LLInventoryModel::item_array_t& items)
{
	if (items.size() < 2) return;

	std::sort(items.begin(), items.end(), sort_by_actual_description);
}

//#define DUMP_CAT_VERBOSE

void LLAppearanceMgr::dumpCat(const LLUUID& cat_id, const std::string& msg)
{
	LLInventoryModel::cat_array_t cats;
	LLInventoryModel::item_array_t items;
	gInventory.collectDescendents(cat_id, cats, items, LLInventoryModel::EXCLUDE_TRASH);

#ifdef DUMP_CAT_VERBOSE
	LL_INFOS() << LL_ENDL;
	LL_INFOS() << str << LL_ENDL;
	S32 hitcount = 0;
	for(S32 i=0; i<items.size(); i++)
	{
		LLViewerInventoryItem *item = items.get(i);
		if (item)
			hitcount++;
		LL_INFOS() << i <<" "<< item->getName() <<LL_ENDL;
	}
#endif
	LL_INFOS() << msg << " count " << items.size() << LL_ENDL;
}

void LLAppearanceMgr::dumpItemArray(const LLInventoryModel::item_array_t& items,
									const std::string& msg)
{
	for (S32 i=0; i<items.size(); i++)
	{
		LLViewerInventoryItem *item = items.at(i);
		LLViewerInventoryItem *linked_item = item ? item->getLinkedItem() : NULL;
		LLUUID asset_id;
		if (linked_item)
		{
			asset_id = linked_item->getAssetUUID();
		}
		LL_DEBUGS("Avatar") << self_av_string() << msg << " " << i <<" " << (item ? item->getName() : "(nullitem)") << " " << asset_id.asString() << LL_ENDL;
	}
}

bool LLAppearanceMgr::mActive = true;

LLAppearanceMgr::LLAppearanceMgr():
	mAttachmentInvLinkEnabled(false),
	mOutfitIsDirty(false),
	mOutfitLocked(false),
	mInFlightTimer(),
	mIsInUpdateAppearanceFromCOF(false),
    mOutstandingAppearanceBakeRequest(false),
    mRerequestAppearanceBake(false)
{
	LLOutfitObserver& outfit_observer = LLOutfitObserver::instance();
	// unlock outfit on save operation completed
	outfit_observer.addCOFSavedCallback(boost::bind(
			&LLAppearanceMgr::setOutfitLocked, this, false));

	mUnlockOutfitTimer.reset(new LLOutfitUnLockTimer(gSavedSettings.getS32(
			"OutfitOperationsTimeout")));

	gIdleCallbacks.addFunction(&LLAttachmentsMgr::onIdle, NULL);
	gIdleCallbacks.addFunction(&LLAppearanceMgr::onIdle, NULL); //sheduling appearance update requests
}

LLAppearanceMgr::~LLAppearanceMgr()
{
	mActive = false;
}

void LLAppearanceMgr::setAttachmentInvLinkEnable(bool val)
{
	LL_DEBUGS("Avatar") << "setAttachmentInvLinkEnable => " << (int) val << LL_ENDL;
	mAttachmentInvLinkEnabled = val;
}
boost::signals2::connection LLAppearanceMgr::setAttachmentsChangedCallback(attachments_changed_callback_t cb)
{
	return mAttachmentsChangeSignal.connect(cb);
}

void dumpAttachmentSet(const std::set<LLUUID>& atts, const std::string& msg)
{
       LL_INFOS() << msg << LL_ENDL;
       for (std::set<LLUUID>::const_iterator it = atts.begin();
               it != atts.end();
               ++it)
       {
               LLUUID item_id = *it;
               LLViewerInventoryItem *item = gInventory.getItem(item_id);
               if (item)
                       LL_INFOS() << "atts " << item->getName() << LL_ENDL;
               else
                       LL_INFOS() << "atts " << "UNKNOWN[" << item_id.asString() << "]" << LL_ENDL;
       }
       LL_INFOS() << LL_ENDL;
}

void LLAppearanceMgr::registerAttachment(const LLUUID& item_id)
{
	LLViewerInventoryItem *item = gInventory.getItem(item_id);
	LL_DEBUGS("Avatar") << "ATT registering attachment "
						<< (item ? item->getName() : "UNKNOWN") << " " << item_id << LL_ENDL;
	gInventory.addChangedMask(LLInventoryObserver::LABEL, item_id);

	LLAttachmentsMgr::instance().onAttachmentArrived(item_id);

	mAttachmentsChangeSignal();
}

void LLAppearanceMgr::unregisterAttachment(const LLUUID& item_id)
{
	LLViewerInventoryItem *item = gInventory.getItem(item_id);
	LL_DEBUGS("Avatar") << "ATT unregistering attachment "
						<< (item ? item->getName() : "UNKNOWN") << " " << item_id << LL_ENDL;
	gInventory.addChangedMask(LLInventoryObserver::LABEL, item_id);

    LLAttachmentsMgr::instance().onDetachCompleted(item_id);
	if (mAttachmentInvLinkEnabled && isLinkedInCOF(item_id))
	{
		LL_DEBUGS("Avatar") << "ATT removing COF link for attachment "
							<< (item ? item->getName() : "UNKNOWN") << " " << item_id << LL_ENDL;
		LLAppearanceMgr::removeCOFItemLinks(item_id);
	}
	else
	{
		//LL_INFOS() << "no link changes, inv link not enabled" << LL_ENDL;
	}

	mAttachmentsChangeSignal();
}

BOOL LLAppearanceMgr::getIsInCOF(const LLUUID& obj_id) const
{
	const LLUUID& cof = getCOF();
	if (obj_id == cof)
		return TRUE;
	const LLInventoryObject* obj = gInventory.getObject(obj_id);
	if (obj && obj->getParentUUID() == cof)
		return TRUE;
	return FALSE;
}

BOOL LLAppearanceMgr::getIsProtectedCOFItem(const LLUUID& obj_id) const
{
	if (!getIsInCOF(obj_id)) return FALSE;

	// If a non-link somehow ended up in COF, allow deletion.
	const LLInventoryObject *obj = gInventory.getObject(obj_id);
	if (obj && !obj->getIsLinkType())
	{
		return FALSE;
	}

	// For now, don't allow direct deletion from the COF.  Instead, force users
	// to choose "Detach" or "Take Off".
	return TRUE;
}

class CallAfterCategoryFetchStage2: public LLInventoryFetchItemsObserver
{
public:
	CallAfterCategoryFetchStage2(const uuid_vec_t& ids,
								 nullary_func_t callable) :
		LLInventoryFetchItemsObserver(ids),
		mCallable(callable)
	{
	}
	~CallAfterCategoryFetchStage2()
	{
	}
	virtual void done()
	{
		LL_INFOS() << this << " done with incomplete " << mIncomplete.size()
				<< " complete " << mComplete.size() <<  " calling callable" << LL_ENDL;

		gInventory.removeObserver(this);
		doOnIdleOneTime(mCallable);
		delete this;
	}
protected:
	nullary_func_t mCallable;
};

class CallAfterCategoryFetchStage1: public LLInventoryFetchDescendentsObserver
{
public:
	CallAfterCategoryFetchStage1(const LLUUID& cat_id, nullary_func_t callable) :
		LLInventoryFetchDescendentsObserver(cat_id),
		mCallable(callable)
	{
	}
	~CallAfterCategoryFetchStage1()
	{
	}
	virtual void done()
	{
		// What we do here is get the complete information on the
		// items in the requested category, and set up an observer
		// that will wait for that to happen.
		LLInventoryModel::cat_array_t cat_array;
		LLInventoryModel::item_array_t item_array;
		gInventory.collectDescendents(mComplete.front(),
									  cat_array,
									  item_array,
									  LLInventoryModel::EXCLUDE_TRASH);
		S32 count = item_array.size();
		if(!count)
		{
			LL_WARNS() << "Nothing fetched in category " << mComplete.front()
					<< LL_ENDL;
			gInventory.removeObserver(this);
			doOnIdleOneTime(mCallable);

			delete this;
			return;
		}

		LL_INFOS() << "stage1 got " << item_array.size() << " items, passing to stage2 " << LL_ENDL;
		uuid_vec_t ids;
		for(S32 i = 0; i < count; ++i)
		{
			ids.push_back(item_array.at(i)->getUUID());
		}
		
		gInventory.removeObserver(this);
		
		// do the fetch
		CallAfterCategoryFetchStage2 *stage2 = new CallAfterCategoryFetchStage2(ids, mCallable);
		stage2->startFetch();
		if(stage2->isFinished())
		{
			// everything is already here - call done.
			stage2->done();
		}
		else
		{
			// it's all on it's way - add an observer, and the inventory
			// will call done for us when everything is here.
			gInventory.addObserver(stage2);
		}
		delete this;
	}
protected:
	nullary_func_t mCallable;
};

void callAfterCategoryFetch(const LLUUID& cat_id, nullary_func_t cb)
{
	CallAfterCategoryFetchStage1 *stage1 = new CallAfterCategoryFetchStage1(cat_id, cb);
	stage1->startFetch();
	if (stage1->isFinished())
	{
		stage1->done();
	}
	else
	{
		gInventory.addObserver(stage1);
	}
}

void add_wearable_type_counts(const uuid_vec_t& ids,
                              S32& clothing_count,
                              S32& bodypart_count,
                              S32& object_count,
                              S32& other_count)
{
    for (uuid_vec_t::const_iterator it = ids.begin(); it != ids.end(); ++it)
    {
        const LLUUID& item_id_to_wear = *it;
        LLViewerInventoryItem* item_to_wear = gInventory.getItem(item_id_to_wear);
        if (item_to_wear)
        {
            if (item_to_wear->getType() == LLAssetType::AT_CLOTHING)
            {
                clothing_count++;
            }
            else if (item_to_wear->getType() == LLAssetType::AT_BODYPART)
            {
                bodypart_count++;
            }
            else if (item_to_wear->getType() == LLAssetType::AT_OBJECT)
            {
                object_count++;
            }
            else
            {
                other_count++;
            }
        }
        else
        {
            other_count++;
        }
    }
}

void wear_multiple(const uuid_vec_t& ids, bool replace)
{
    S32 clothing_count = 0;
    S32 bodypart_count = 0;
    S32 object_count = 0;
    S32 other_count = 0;
    add_wearable_type_counts(ids, clothing_count, bodypart_count, object_count, other_count);

    LLPointer<LLInventoryCallback> cb = NULL;
    if (clothing_count > 0 || bodypart_count > 0)
    {
        cb = new LLUpdateAppearanceOnDestroy;
    }
	LLAppearanceMgr::instance().wearItemsOnAvatar(ids, true, replace, cb);
}

// SLapp for easy-wearing of a stock (library) avatar
//
class LLWearFolderHandler : public LLCommandHandler
{
public:
	// not allowed from outside the app
	LLWearFolderHandler() : LLCommandHandler("wear_folder", UNTRUSTED_BLOCK) { }

	bool handle(const LLSD& tokens, const LLSD& query_map,
				LLMediaCtrl* web)
	{
		LLSD::UUID folder_uuid;

		if (folder_uuid.isNull() && query_map.has("folder_name"))
		{
			std::string outfit_folder_name = query_map["folder_name"];
			folder_uuid = findDescendentCategoryIDByName(
				gInventory.getLibraryRootFolderID(),
				outfit_folder_name);	
		}
		if (folder_uuid.isNull() && query_map.has("folder_id"))
		{
			folder_uuid = query_map["folder_id"].asUUID();
		}
		
		if (folder_uuid.notNull())
		{
			LLPointer<LLInventoryCategory> category = new LLInventoryCategory(folder_uuid,
																			  LLUUID::null,
																			  LLFolderType::FT_CLOTHING,
																			  "Quick Appearance");
			if ( gInventory.getCategory( folder_uuid ) != NULL )
			{
				LLAppearanceMgr::getInstance()->wearInventoryCategory(category, true, false);
				
				// *TODOw: This may not be necessary if initial outfit is chosen already -- josh
				gAgent.setOutfitChosen(TRUE);
			}
		}

		// release avatar picker keyboard focus
		gFocusMgr.setKeyboardFocus( NULL );

		return true;
	}
};

LLWearFolderHandler gWearFolderHandler;