summaryrefslogtreecommitdiff
path: root/indra/newview/llinventorygallery.cpp
blob: 200a9b2a91f00b26bd081ebe9558f652b7c242e4 (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
/**
 * @file llinventorygallery.cpp
 * @brief LLInventoryGallery class implementation
 *
 * $LicenseInfo:firstyear=2023&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2023, 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 "llinventorygallery.h"
#include "llinventorygallerymenu.h"

#include "llclipboard.h"
#include "llcommonutils.h"
#include "lliconctrl.h"
#include "llinventorybridge.h"
#include "llinventoryfunctions.h"
#include "llinventoryicon.h"
#include "llinventorymodel.h"
#include "llthumbnailctrl.h"
#include "lltextbox.h"
#include "llviewerfoldertype.h"

#include "llagent.h"
#include "llappearancemgr.h"
#include "llenvironment.h"
#include "llfriendcard.h"
#include "llgesturemgr.h"
#include "llmarketplacefunctions.h"
#include "llnotificationsutil.h"
#include "lloutfitobserver.h"
#include "lltrans.h"
#include "llviewerassettype.h"
#include "llviewermessage.h"
#include "llviewerobjectlist.h"
#include "llvoavatarself.h"

static LLPanelInjector<LLInventoryGallery> t_inventory_gallery("inventory_gallery");

const S32 GALLERY_ITEMS_PER_ROW_MIN = 2;

// Helper dnd functions
BOOL dragCategoryIntoFolder(LLUUID dest_id, LLInventoryCategory* inv_cat, BOOL drop, std::string& tooltip_msg, BOOL is_link);
BOOL dragItemIntoFolder(LLUUID folder_id, LLInventoryItem* inv_item, BOOL drop, std::string& tooltip_msg, BOOL user_confirm);
void dropToMyOutfits(LLInventoryCategory* inv_cat);

//-----------------------------
// LLInventoryGallery
//-----------------------------

LLInventoryGallery::LLInventoryGallery(const LLInventoryGallery::Params& p)
    : LLPanel(),
      mScrollPanel(NULL),
      mGalleryPanel(NULL),
      mLastRowPanel(NULL),
      mGalleryCreated(false),
      mRowCount(0),
      mItemsAddedCount(0),
      mRowPanelHeight(p.row_panel_height),
      mVerticalGap(p.vertical_gap),
      mHorizontalGap(p.horizontal_gap),
      mItemWidth(p.item_width),
      mItemHeight(p.item_height),
      mItemHorizontalGap(p.item_horizontal_gap),
      mItemsInRow(p.items_in_row),
      mRowPanWidthFactor(p.row_panel_width_factor),
      mGalleryWidthFactor(p.gallery_width_factor),
      mIsInitialized(false),
      mRootDirty(false),
      mNeedsArrange(false),
      mSearchType(LLInventoryFilter::SEARCHTYPE_NAME)
{
    updateGalleryWidth();
    mFilter = new LLInventoryFilter();
    mCategoriesObserver = new LLInventoryCategoriesObserver();
    mThumbnailsObserver = new LLThumbnailsObserver();
    gInventory.addObserver(mThumbnailsObserver);

    mGestureObserver = new LLGalleryGestureObserver(this);
    LLGestureMgr::instance().addObserver(mGestureObserver);

    mUsername = gAgentUsername;
    LLStringUtil::toUpper(mUsername);
}

LLInventoryGallery::Params::Params()
    : row_panel_height("row_panel_height", 180),
      vertical_gap("vertical_gap", 10),
      horizontal_gap("horizontal_gap", 10),
      item_width("item_width", 150),
      item_height("item_height", 175),
      item_horizontal_gap("item_horizontal_gap", 16),
      items_in_row("items_in_row", GALLERY_ITEMS_PER_ROW_MIN),
      row_panel_width_factor("row_panel_width_factor", 166),
      gallery_width_factor("gallery_width_factor", 163)
{
    addSynonym(row_panel_height, "row_height");
}

const LLInventoryGallery::Params& LLInventoryGallery::getDefaultParams()
{
    return LLUICtrlFactory::getDefaultParams<LLInventoryGallery>();
}

BOOL LLInventoryGallery::postBuild()
{
    mScrollPanel = getChild<LLScrollContainer>("gallery_scroll_panel");
    LLPanel::Params params = LLPanel::getDefaultParams();
    mGalleryPanel = LLUICtrlFactory::create<LLPanel>(params);
    mMessageTextBox = getChild<LLTextBox>("empty_txt");
    mInventoryGalleryMenu = new LLInventoryGalleryContextMenu(this);
    mRootGalleryMenu = new LLInventoryGalleryContextMenu(this);
    mRootGalleryMenu->setRootFolder(true);
    return TRUE;
}

LLInventoryGallery::~LLInventoryGallery()
{
    if (gEditMenuHandler == this)
    {
        gEditMenuHandler = NULL;
    }

    delete mInventoryGalleryMenu;
    delete mRootGalleryMenu;
    delete mFilter;
    
    gIdleCallbacks.deleteFunction(onIdle, this);

    while (!mUnusedRowPanels.empty())
    {
        LLPanel* panelp = mUnusedRowPanels.back();
        mUnusedRowPanels.pop_back();
        panelp->die();
    }
    while (!mUnusedItemPanels.empty())
    {
        LLPanel* panelp = mUnusedItemPanels.back();
        mUnusedItemPanels.pop_back();
        panelp->die();
    }
    while (!mHiddenItems.empty())
    {
        LLPanel* panelp = mHiddenItems.back();
        mHiddenItems.pop_back();
        panelp->die();
    }
    

    if (gInventory.containsObserver(mCategoriesObserver))
    {
        gInventory.removeObserver(mCategoriesObserver);
    }
    delete mCategoriesObserver;

    if (gInventory.containsObserver(mThumbnailsObserver))
    {
        gInventory.removeObserver(mThumbnailsObserver);
    }
    delete mThumbnailsObserver;
    
    LLGestureMgr::instance().removeObserver(mGestureObserver);
    delete mGestureObserver;
}

void LLInventoryGallery::setRootFolder(const LLUUID cat_id)
{
    gIdleCallbacks.deleteFunction(onIdle, this);

    LLViewerInventoryCategory* category = gInventory.getCategory(cat_id);
    if(!category || (mFolderID == cat_id))
    {
        return;
    }
    if(mFolderID.notNull())
    {
        mBackwardFolders.push_back(mFolderID);
    }
    mFolderID = cat_id;
    dirtyRootFolder();
}

void LLInventoryGallery::dirtyRootFolder()
{
    if (getVisible())
    {
        updateRootFolder();
    }
    else
    {
        mRootDirty = true;
    }
}

void LLInventoryGallery::updateRootFolder()
{
    llassert(mFolderID.notNull());
    if (mIsInitialized && mFolderID.notNull())
    {
        S32 count = mItemsAddedCount;
        for (S32 i = count - 1; i >= 0; i--)
        {
            updateRemovedItem(mItems[i]->getUUID());
        }
        S32 hidden_count = mHiddenItems.size();
        for (S32 i = hidden_count - 1; i >= 0; i--)
        {
            updateRemovedItem(mHiddenItems[i]->getUUID());
        }
        mItemBuildQuery.clear();
        
        if (gInventory.containsObserver(mCategoriesObserver))
        {
            gInventory.removeObserver(mCategoriesObserver);
        }
        delete mCategoriesObserver;

        mCategoriesObserver = new LLInventoryCategoriesObserver();

        if (gInventory.containsObserver(mThumbnailsObserver))
        {
            gInventory.removeObserver(mThumbnailsObserver);
        }
        delete mThumbnailsObserver;
        mThumbnailsObserver = new LLThumbnailsObserver();
        gInventory.addObserver(mThumbnailsObserver);
    }
    {
        mRootChangedSignal();

        gInventory.addObserver(mCategoriesObserver);
        
        // Start observing changes in selected category.
        mCategoriesObserver->addCategory(mFolderID,
            boost::bind(&LLInventoryGallery::refreshList, this, mFolderID));

        LLViewerInventoryCategory* category = gInventory.getCategory(mFolderID);
        //If not all items are fetched now
        // the observer will refresh the list as soon as the new items
        // arrive.
        category->fetch();
        
        //refreshList(cat_id);
        LLInventoryModel::cat_array_t* cat_array;
        LLInventoryModel::item_array_t* item_array;

        gInventory.getDirectDescendentsOf(mFolderID, cat_array, item_array);

        // Creating a vector of newly collected sub-categories UUIDs.
        for (LLInventoryModel::cat_array_t::const_iterator iter = cat_array->begin();
            iter != cat_array->end();
            iter++)
        {
            mItemBuildQuery.insert((*iter)->getUUID());
        }
        
        for (LLInventoryModel::item_array_t::const_iterator iter = item_array->begin();
            iter != item_array->end();
            iter++)
        {
            mItemBuildQuery.insert((*iter)->getUUID());
        }
        mIsInitialized = true;
        mRootDirty = false;

        if (mScrollPanel)
        {
            mScrollPanel->goToTop();
        }
    }

    LLOutfitObserver::instance().addCOFChangedCallback(boost::bind(&LLInventoryGallery::onCOFChanged, this));

    if (!mGalleryCreated)
    {
        initGallery();
    }

    if (!mItemBuildQuery.empty())
    {
        gIdleCallbacks.addFunction(onIdle, (void*)this);
    }
}

void LLInventoryGallery::initGallery()
{
    if (!mGalleryCreated)
    {
        uuid_vec_t cats;
        getCurrentCategories(cats);
        int n = cats.size();
        buildGalleryPanel(n);
        mScrollPanel->addChild(mGalleryPanel);
        for (int i = 0; i < n; i++)
        {
            addToGallery(mItemMap[cats[i]]);
        }
        reArrangeRows();
        mGalleryCreated = true;
    }
}

void LLInventoryGallery::draw()
{
    LLPanel::draw();
    if (mGalleryCreated)
    {
        if(!updateRowsIfNeeded())
        {
            handleModifiedFilter();
        }
    }
}

void LLInventoryGallery::onVisibilityChange(BOOL new_visibility)
{
    if (new_visibility && mRootDirty)
    {
        updateRootFolder();
    }
    LLPanel::onVisibilityChange(new_visibility);
}

bool LLInventoryGallery::updateRowsIfNeeded()
{
    S32 scroll_content_width = mScrollPanel ? mScrollPanel->getVisibleContentRect().getWidth() : getRect().getWidth();
    if(((scroll_content_width - mRowPanelWidth) > mItemWidth)
       && mRowCount > 1)
    {
        reArrangeRows(1);
        return true;
    }
    else if((mRowPanelWidth > (scroll_content_width + mItemHorizontalGap))
            && mItemsInRow > GALLERY_ITEMS_PER_ROW_MIN)
    {
        reArrangeRows(-1);
        return true;
    }
    return false;
}

bool compareGalleryItem(LLInventoryGalleryItem* item1, LLInventoryGalleryItem* item2)
{
    if (item1->getSortGroup() != item2->getSortGroup())
    {
        return (item1->getSortGroup() < item2->getSortGroup());
    }
    if(((item1->isDefaultImage() && item2->isDefaultImage()) || (!item1->isDefaultImage() && !item2->isDefaultImage())))
    {
        std::string name1 = item1->getItemName();
        std::string name2 = item2->getItemName();

        return (LLStringUtil::compareDict(name1, name2) < 0);
    }
    else
    {
        return item2->isDefaultImage();
    }
}

void LLInventoryGallery::reArrangeRows(S32 row_diff)
{
    std::vector<LLInventoryGalleryItem*> buf_items = mItems;
    for (std::vector<LLInventoryGalleryItem*>::const_reverse_iterator it = buf_items.rbegin(); it != buf_items.rend(); ++it)
    {
        removeFromGalleryLast(*it, false);
    }
    for (std::vector<LLInventoryGalleryItem*>::const_reverse_iterator it = mHiddenItems.rbegin(); it != mHiddenItems.rend(); ++it)
    {
        buf_items.push_back(*it);
    }
    mHiddenItems.clear();
    
    mItemsInRow+= row_diff;
    updateGalleryWidth();
    std::sort(buf_items.begin(), buf_items.end(), compareGalleryItem);
    
    for (std::vector<LLInventoryGalleryItem*>::const_iterator it = buf_items.begin(); it != buf_items.end(); ++it)
    {
        (*it)->setHidden(false);
        applyFilter(*it, mFilterSubString);
        addToGallery(*it);
    }
    mFilter->clearModified();
    updateMessageVisibility();
}

void LLInventoryGallery::updateGalleryWidth()
{
    mRowPanelWidth = mRowPanWidthFactor * mItemsInRow - mItemHorizontalGap;
    mGalleryWidth = mGalleryWidthFactor * mItemsInRow - mItemHorizontalGap;
}

LLPanel* LLInventoryGallery::addLastRow()
{
    mRowCount++;
    int row = 0;
    int vgap = mVerticalGap * row;
    LLPanel* result = buildRowPanel(0, row * mRowPanelHeight + vgap);
    mGalleryPanel->addChild(result);
    return result;
}

void LLInventoryGallery::moveRowUp(int row)
{
    moveRow(row, mRowCount - 1 - row + 1);
}

void LLInventoryGallery::moveRowDown(int row)
{
    moveRow(row, mRowCount - 1 - row - 1);
}

void LLInventoryGallery::moveRow(int row, int pos)
{
    int vgap = mVerticalGap * pos;
    moveRowPanel(mRowPanels[row], 0, pos * mRowPanelHeight + vgap);
}

void LLInventoryGallery::removeLastRow()
{
    mRowCount--;
    mGalleryPanel->removeChild(mLastRowPanel);
    mUnusedRowPanels.push_back(mLastRowPanel);
    mRowPanels.pop_back();
    if (mRowPanels.size() > 0)
    {
        // Just removed last row
        mLastRowPanel = mRowPanels.back();
    }
    else
    {
        mLastRowPanel = NULL;
    }
}

LLPanel* LLInventoryGallery::addToRow(LLPanel* row_stack, LLInventoryGalleryItem* item, int pos, int hgap)
{
    LLPanel* lpanel = buildItemPanel(pos * mItemWidth + hgap);
    lpanel->addChild(item);
    row_stack->addChild(lpanel);
    mItemPanels.push_back(lpanel);
    return lpanel;
}

void LLInventoryGallery::addToGallery(LLInventoryGalleryItem* item)
{
    if(item->isHidden())
    {
        mHiddenItems.push_back(item);
        return;
    }
    mItemIndexMap[item] = mItemsAddedCount;
    mIndexToItemMap[mItemsAddedCount] = item;
    mItemsAddedCount++;
    int n = mItemsAddedCount;
    int row_count = (n % mItemsInRow) == 0 ? n / mItemsInRow : n / mItemsInRow + 1;
    int n_prev = n - 1;
    int row_count_prev = (n_prev % mItemsInRow) == 0 ? n_prev / mItemsInRow : n_prev / mItemsInRow + 1;

    bool add_row = row_count != row_count_prev;
    int pos = 0;
    if (add_row)
    {
        for (int i = 0; i < row_count_prev; i++)
        {
            moveRowUp(i);
        }
        mLastRowPanel = addLastRow();
        mRowPanels.push_back(mLastRowPanel);
    }
    pos = (n - 1) % mItemsInRow;
    mItems.push_back(item);
    addToRow(mLastRowPanel, item, pos, mHorizontalGap * pos);
    reshapeGalleryPanel(row_count);
}


void LLInventoryGallery::removeFromGalleryLast(LLInventoryGalleryItem* item, bool needs_reshape)
{
    if(item->isHidden())
    {
        mHiddenItems.pop_back();
        // Note: item still exists!!!
        return;
    }
    int n_prev = mItemsAddedCount;
    int n = mItemsAddedCount - 1;
    int row_count = (n % mItemsInRow) == 0 ? n / mItemsInRow : n / mItemsInRow + 1;
    int row_count_prev = (n_prev % mItemsInRow) == 0 ? n_prev / mItemsInRow : n_prev / mItemsInRow + 1;
    mItemsAddedCount--;
    mIndexToItemMap.erase(mItemsAddedCount);

    bool remove_row = row_count != row_count_prev;
    removeFromLastRow(mItems[mItemsAddedCount]);
    mItems.pop_back();
    if (remove_row)
    {
        for (int i = 0; i < row_count_prev - 1; i++)
        {
            moveRowDown(i);
        }
        removeLastRow();
    }
    if (needs_reshape)
    {
        reshapeGalleryPanel(row_count);
    }
}


void LLInventoryGallery::removeFromGalleryMiddle(LLInventoryGalleryItem* item)
{
    if(item->isHidden())
    {
        mHiddenItems.erase(std::remove(mHiddenItems.begin(), mHiddenItems.end(), item), mHiddenItems.end());
        // item still exists and needs to be deleted or used!!!
        return;
    }
    int n = mItemIndexMap[item];
    mItemIndexMap.erase(item);
    mIndexToItemMap.erase(n);
    std::vector<LLInventoryGalleryItem*> saved;
    for (int i = mItemsAddedCount - 1; i > n; i--)
    {
        saved.push_back(mItems[i]);
        removeFromGalleryLast(mItems[i]);
    }
    removeFromGalleryLast(mItems[n]);
    int saved_count = saved.size();
    for (int i = 0; i < saved_count; i++)
    {
        addToGallery(saved.back());
        saved.pop_back();
    }
}

void LLInventoryGallery::removeFromLastRow(LLInventoryGalleryItem* item)
{
    mItemPanels.back()->removeChild(item);
    mLastRowPanel->removeChild(mItemPanels.back());
    mUnusedItemPanels.push_back(mItemPanels.back());
    mItemPanels.pop_back();
}

LLInventoryGalleryItem* LLInventoryGallery::buildGalleryItem(std::string name, LLUUID item_id, LLAssetType::EType type, LLUUID thumbnail_id, LLInventoryType::EType inventory_type, U32 flags, bool is_link, bool is_worn)
{
    LLInventoryGalleryItem::Params giparams;
    giparams.visible = true;
    giparams.follows.flags(FOLLOWS_LEFT | FOLLOWS_TOP);
    giparams.rect(LLRect(0,mItemHeight, mItemWidth, 0));
    LLInventoryGalleryItem* gitem = LLUICtrlFactory::create<LLInventoryGalleryItem>(giparams);
    gitem->setItemName(name);
    gitem->setUUID(item_id);
    gitem->setGallery(this);
    gitem->setType(type, inventory_type, flags, is_link);
    gitem->setThumbnail(thumbnail_id);
    gitem->setWorn(is_worn);
    gitem->setCreatorName(get_searchable_creator_name(&gInventory, item_id));
    gitem->setDescription(get_searchable_description(&gInventory, item_id));
    gitem->setAssetIDStr(get_searchable_UUID(&gInventory, item_id));
    return gitem;
}

void LLInventoryGallery::buildGalleryPanel(int row_count)
{
    LLPanel::Params params;
    params.follows.flags(FOLLOWS_LEFT | FOLLOWS_TOP);
    params.visible = true;
    params.use_bounding_rect = false;
    mGalleryPanel = LLUICtrlFactory::create<LLPanel>(params);
    reshapeGalleryPanel(row_count);
}

void LLInventoryGallery::reshapeGalleryPanel(int row_count)
{
    int bottom = 0;
    int left = 0;
    int height = row_count * (mRowPanelHeight + mVerticalGap);
    LLRect rect = LLRect(left, bottom + height, left + mGalleryWidth, bottom);
    mGalleryPanel->setRect(rect);
    mGalleryPanel->reshape(mGalleryWidth, height);
}

LLPanel* LLInventoryGallery::buildItemPanel(int left)
{
    int top = 0;
    LLPanel* lpanel = NULL;
    if(mUnusedItemPanels.empty())
    {
        LLPanel::Params lpparams;
        lpparams.follows.flags(FOLLOWS_LEFT | FOLLOWS_TOP);
        lpparams.visible = true;
        lpparams.rect(LLRect(left, top + mItemHeight, left + mItemWidth + mItemHorizontalGap, top));
        lpparams.use_bounding_rect = false;
        lpanel = LLUICtrlFactory::create<LLPanel>(lpparams);
    }
    else
    {
        lpanel = mUnusedItemPanels.back();
        mUnusedItemPanels.pop_back();

        LLRect rect = LLRect(left, top + mItemHeight, left + mItemWidth + mItemHorizontalGap, top);
        lpanel->setShape(rect, false);
    }
    return lpanel;
}

LLPanel* LLInventoryGallery::buildRowPanel(int left, int bottom)
{
    LLPanel* stack = NULL;
    if(mUnusedRowPanels.empty())
    {
        LLPanel::Params sparams;
        sparams.follows.flags(FOLLOWS_LEFT | FOLLOWS_TOP);
        sparams.use_bounding_rect = false;
        sparams.visible = true;
        stack = LLUICtrlFactory::create<LLPanel>(sparams);
    }
    else
    {
        stack = mUnusedRowPanels.back();
        mUnusedRowPanels.pop_back();
    }
    moveRowPanel(stack, left, bottom);
    return stack;
}

void LLInventoryGallery::moveRowPanel(LLPanel* stack, int left, int bottom)
{
    LLRect rect = LLRect(left, bottom + mRowPanelHeight, left + mRowPanelWidth, bottom);
    stack->setRect(rect);
    stack->reshape(mRowPanelWidth, mRowPanelHeight);
}

void LLInventoryGallery::setFilterSubString(const std::string& string)
{
    mFilterSubString = string;
    mFilter->setFilterSubString(string);
    
    //reArrangeRows();
}

bool LLInventoryGallery::applyFilter(LLInventoryGalleryItem* item, const std::string& filter_substring)
{
    if(item)
    {
        bool visible = checkAgainstFilters(item, filter_substring);
        item->setHidden(!visible);
        return visible;
    }
    return false;
}

bool LLInventoryGallery::checkAgainstFilters(LLInventoryGalleryItem* item, const std::string& filter_substring)
{
    if (!item) return false;

    if (item->isFolder() && (mFilter->getShowFolderState() == LLInventoryFilter::SHOW_ALL_FOLDERS))
    {
        return true;
    }

    if(item->isLink() && ((mFilter->getSearchVisibilityTypes() & LLInventoryFilter::VISIBILITY_LINKS) == 0) && !filter_substring.empty())
    {
        return false;
    }
    
    bool hidden = false;

    if(mFilter->getFilterCreatorType() == LLInventoryFilter::FILTERCREATOR_SELF)
    {
        hidden = (item->getCreatorName() == mUsername) || item->isFolder();
    }
    else if(mFilter->getFilterCreatorType() == LLInventoryFilter::FILTERCREATOR_OTHERS)
    {
        hidden = (item->getCreatorName() != mUsername) || item->isFolder();
    }
    if(hidden)
    {
        return false;
    }

    if(!mFilter->checkAgainstFilterThumbnails(item->getUUID()))
    {
        return false;
    }

    if(!checkAgainstFilterType(item->getUUID()))
    {
        return false;
    }

    std::string desc;
    switch(mSearchType)
    {
        case LLInventoryFilter::SEARCHTYPE_CREATOR:
            desc = item->getCreatorName();
            break;
        case LLInventoryFilter::SEARCHTYPE_DESCRIPTION:
            desc = item->getDescription();
            break;
        case LLInventoryFilter::SEARCHTYPE_UUID:
            desc = item->getAssetIDStr();
            break;
        case LLInventoryFilter::SEARCHTYPE_NAME:
        default:
            desc = item->getItemName() + item->getItemNameSuffix();
            break;
    }
    
    LLStringUtil::toUpper(desc);

    std::string cur_filter = filter_substring;
    LLStringUtil::toUpper(cur_filter);

    hidden = (std::string::npos == desc.find(cur_filter));
    return !hidden;
}

void LLInventoryGallery::onIdle(void* userdata)
{
    LLInventoryGallery* self = (LLInventoryGallery*)userdata;

    if (!self->mIsInitialized || !self->mGalleryCreated)
    {
        self->mNeedsArrange = false;
        return;
    }

    const F64 MAX_TIME_VISIBLE = 0.020f;
    const F64 MAX_TIME_HIDDEN = 0.001f; // take it slow
    const F64 max_time = self->getVisible() ? MAX_TIME_VISIBLE : MAX_TIME_HIDDEN;
    F64 curent_time = LLTimer::getTotalSeconds();
    const F64 end_time = curent_time + max_time;

    while (!self->mItemBuildQuery.empty() && end_time > curent_time)
    {
        uuid_set_t::iterator iter = self->mItemBuildQuery.begin();
        LLUUID item_id = *iter;
        self->mNeedsArrange |= self->updateAddedItem(item_id);
        self->mItemBuildQuery.erase(iter);
        curent_time = LLTimer::getTotalSeconds();
    }

    if (self->mNeedsArrange)
    {
        self->mNeedsArrange = false;
        self->reArrangeRows();
        self->updateMessageVisibility();
    }

    if (self->mItemToSelect.notNull())
    {
        LLUUID item_to_select = self->mItemToSelect;
        self->mItemToSelect = LLUUID::null;
        self->changeItemSelection(item_to_select, true);
    }

    if (self->mItemToSelect.isNull() && self->mItemBuildQuery.empty())
    {
        gIdleCallbacks.deleteFunction(onIdle, (void*)self);
    }
}

void LLInventoryGallery::setSearchType(LLInventoryFilter::ESearchType type)
{
    if(mSearchType != type)
    {
        mSearchType = type;
        if(!mFilterSubString.empty())
        {
            reArrangeRows();
        }
    }
}

void LLInventoryGallery::getCurrentCategories(uuid_vec_t& vcur)
{
    for (gallery_item_map_t::const_iterator iter = mItemMap.begin();
        iter != mItemMap.end();
        iter++)
    {
        if ((*iter).second != NULL)
        {
            vcur.push_back((*iter).first);
        }
    }
}

bool LLInventoryGallery::updateAddedItem(LLUUID item_id)
{
    LLInventoryObject* obj = gInventory.getObject(item_id);
    if (!obj)
    {
        LL_WARNS("InventoryGallery") << "Failed to find item: " << item_id << LL_ENDL;
        return false;
    }

    std::string name = obj->getName();
    LLUUID thumbnail_id = obj->getThumbnailUUID();;
    LLInventoryType::EType inventory_type(LLInventoryType::IT_CATEGORY);
    U32 misc_flags = 0;
    bool is_worn = false;
    LLInventoryItem* inv_item = gInventory.getItem(item_id);
    if (inv_item)
    {
        inventory_type = inv_item->getInventoryType();
        misc_flags = inv_item->getFlags();
        if (LLAssetType::AT_GESTURE == obj->getType())
        {
            is_worn = LLGestureMgr::instance().isGestureActive(item_id);
        }
        else
        {
            is_worn = LLAppearanceMgr::instance().isLinkedInCOF(item_id);
        }
    }
    else if (LLAssetType::AT_CATEGORY == obj->getType())
    {
        name = get_localized_folder_name(item_id);
        if(thumbnail_id.isNull())
        {
            thumbnail_id = getOutfitImageID(item_id);
        }
    }

    bool res = false;
    LLInventoryGalleryItem* item = buildGalleryItem(name, item_id, obj->getType(), thumbnail_id, inventory_type, misc_flags, obj->getIsLinkType(), is_worn);
    mItemMap.insert(LLInventoryGallery::gallery_item_map_t::value_type(item_id, item));
    item->setRightMouseDownCallback(boost::bind(&LLInventoryGallery::showContextMenu, this, _1, _2, _3, item_id));
    item->setFocusReceivedCallback(boost::bind(&LLInventoryGallery::changeItemSelection, this, item_id, false));
    if (mGalleryCreated)
    {
        res = applyFilter(item, mFilterSubString);
        addToGallery(item);
    }

    mThumbnailsObserver->addItem(item_id,
        boost::bind(&LLInventoryGallery::updateItemThumbnail, this, item_id));
    return res;
}

void LLInventoryGallery::updateRemovedItem(LLUUID item_id)
{
    gallery_item_map_t::iterator item_iter = mItemMap.find(item_id);
    if (item_iter != mItemMap.end())
    {
        mThumbnailsObserver->removeItem(item_id);

        LLInventoryGalleryItem* item = item_iter->second;

        deselectItem(item_id);
        mItemMap.erase(item_iter);
        removeFromGalleryMiddle(item);

        // kill removed item
        if (item != NULL)
        {
            // Todo: instead of deleting, store somewhere to reuse later
            item->die();
        }
    }

    mItemBuildQuery.erase(item_id);
}

void LLInventoryGallery::updateChangedItemName(LLUUID item_id, std::string name)
{
    gallery_item_map_t::iterator iter = mItemMap.find(item_id);
    if (iter != mItemMap.end())
    {
        LLInventoryGalleryItem* item = iter->second;
        if (item)
        {
            item->setItemName(name);
        }
    }
}

void LLInventoryGallery::updateWornItem(LLUUID item_id, bool is_worn)
{
    gallery_item_map_t::iterator iter = mItemMap.find(item_id);
    if (iter != mItemMap.end())
    {
        LLInventoryGalleryItem* item = iter->second;
        if (item)
        {
            item->setWorn(is_worn);
        }
    }
}

void LLInventoryGallery::updateItemThumbnail(LLUUID item_id)
{
    LLInventoryObject* obj = gInventory.getObject(item_id);
    if (!obj)
    {
        return;
    }
    LLUUID thumbnail_id = obj->getThumbnailUUID();

    if ((LLAssetType::AT_CATEGORY == obj->getType()) && thumbnail_id.isNull())
    {
        thumbnail_id = getOutfitImageID(item_id);
    }

    if (mItemMap[item_id])
    {
        mItemMap[item_id]->setThumbnail(thumbnail_id);

        bool passes_filter = checkAgainstFilters(mItemMap[item_id], mFilterSubString);
        if((mItemMap[item_id]->isHidden() && passes_filter)
           || (!mItemMap[item_id]->isHidden() && !passes_filter))
        {
            reArrangeRows();
        }
    }
}

BOOL LLInventoryGallery::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
    if(mItemMap[mSelectedItemID])
    {
        mItemMap[mSelectedItemID]->setFocus(false);
        setFocus(true);
    }
    clearSelection();
    BOOL res = LLPanel::handleRightMouseDown(x, y, mask);

    if (mSelectedItemID.isNull())
    {
        if (mInventoryGalleryMenu && mFolderID.notNull())
        {
            uuid_vec_t selected_uuids;
            selected_uuids.push_back(mFolderID);
            mRootGalleryMenu->show(this, selected_uuids, x, y);
            return TRUE;
        }
    }
    return res;
}


BOOL LLInventoryGallery::handleKeyHere(KEY key, MASK mask)
{
    BOOL handled = FALSE;
    switch (key)
    {
        case KEY_RETURN:
            // Open selected items if enter key hit on the inventory panel
            if (mask == MASK_NONE && mInventoryGalleryMenu && mSelectedItemID.notNull())
            {
                LLViewerInventoryCategory* category = gInventory.getCategory(mSelectedItemID);
                if (category)
                {
                    setRootFolder(mSelectedItemID);
                    handled = TRUE;
                }
                else
                {
                    LLViewerInventoryItem* item = gInventory.getItem(mSelectedItemID);
                    if (item)
                    {
                        LLInvFVBridgeAction::doAction(item->getType(), mSelectedItemID, &gInventory);
                    }
                }
            }
            break;
        case KEY_DELETE:
#if LL_DARWIN
        case KEY_BACKSPACE:
#endif
            // Delete selected items if delete or backspace key hit on the inventory panel
            // Note: on Mac laptop keyboards, backspace and delete are one and the same
            if (canDeleteSelection())
            {
                deleteSelection();
            }
            break;

        case KEY_F2:
            mFilterSubString.clear();
            if (mInventoryGalleryMenu && mSelectedItemID.notNull())
            {
                mInventoryGalleryMenu->doToSelected("rename", mSelectedItemID);
            }
            handled = TRUE;
            break;

        case KEY_PAGE_UP:
            mFilterSubString.clear();
            if (mScrollPanel)
            {
                mScrollPanel->pageUp(30);
            }
            handled = TRUE;
            break;

        case KEY_PAGE_DOWN:
            mFilterSubString.clear();
            if (mScrollPanel)
            {
                mScrollPanel->pageDown(30);
            }
            handled = TRUE;
            break;

        case KEY_HOME:
            mFilterSubString.clear();
            if (mScrollPanel)
            {
                mScrollPanel->goToTop();
            }
            handled = TRUE;
            break;

        case KEY_END:
            mFilterSubString.clear();
            if (mScrollPanel)
            {
                mScrollPanel->goToBottom();
            }
            handled = TRUE;
            break;

        case KEY_LEFT:
            moveLeft();
            handled = TRUE;
            break;

        case KEY_RIGHT:
            moveRight();
            handled = TRUE;
            break;

        case KEY_UP:
            moveUp();
            handled = TRUE;
            break;

        case KEY_DOWN:
            moveDown();
            handled = TRUE;
            break;

        default:
            break;
    }

    if (handled)
    {
        mInventoryGalleryMenu->hide();
    }

    return handled;
}

void LLInventoryGallery::moveUp()
{
    mFilterSubString.clear();

    if (mInventoryGalleryMenu && mSelectedItemID.notNull() && mItemsAddedCount > 1)
    {
        LLInventoryGalleryItem* item = getSelectedItem();
        if (item)
        {
            S32 n = mItemIndexMap[item];
            n -= mItemsInRow;
            if (n >= 0)
            {
                item = mIndexToItemMap[n];
                LLUUID item_id = item->getUUID();
                changeItemSelection(item_id, true);
                item->setFocus(TRUE);
                claimEditHandler();
            }
        }
    }
}

void LLInventoryGallery::moveDown()
{
    mFilterSubString.clear();

    if (mInventoryGalleryMenu && mSelectedItemID.notNull() && mItemsAddedCount > 1)
    {
        LLInventoryGalleryItem* item = getSelectedItem();
        if (item)
        {
            S32 n = mItemIndexMap[item];
            n += mItemsInRow;
            if (n < mItemsAddedCount)
            {
                item = mIndexToItemMap[n];
                LLUUID item_id = item->getUUID();
                changeItemSelection(item_id, true);
                item->setFocus(TRUE);
                claimEditHandler();
            }
        }
    }
}

void LLInventoryGallery::moveLeft()
{
    mFilterSubString.clear();

    if (mInventoryGalleryMenu && mSelectedItemID.notNull() && mItemsAddedCount > 1)
    {
        LLInventoryGalleryItem* item = getSelectedItem();
        if (item)
        {
            // Might be better to get item from panel
            S32 n = mItemIndexMap[item];
            n--;
            if (n < 0)
            {
                n = mItemsAddedCount - 1;
            }
            item = mIndexToItemMap[n];
            LLUUID item_id = item->getUUID();
            changeItemSelection(item_id, true);
            item->setFocus(TRUE);
            claimEditHandler();
        }
    }
}

void LLInventoryGallery::moveRight()
{
    mFilterSubString.clear();

    if (mInventoryGalleryMenu && mSelectedItemID.notNull() && mItemsAddedCount > 1)
    {
        LLInventoryGalleryItem* item = getSelectedItem();
        if (item)
        {
            S32 n = mItemIndexMap[item];
            n++;
            if (n == mItemsAddedCount)
            {
                n = 0;
            }
            item = mIndexToItemMap[n];
            LLUUID item_id = item->getUUID();
            changeItemSelection(item_id, true);
            item->setFocus(TRUE);
            claimEditHandler();
        }
    }
}

void LLInventoryGallery::showContextMenu(LLUICtrl* ctrl, S32 x, S32 y, const LLUUID& item_id)
{
    if (mInventoryGalleryMenu && item_id.notNull())
    {
        uuid_vec_t selected_uuids;
        selected_uuids.push_back(item_id);
        mInventoryGalleryMenu->show(ctrl, selected_uuids, x, y);
    }
}

void LLInventoryGallery::changeItemSelection(const LLUUID& item_id, bool scroll_to_selection)
{
    if ((mItemMap.count(item_id) == 0) || mNeedsArrange)
    {
        mItemToSelect = item_id;
        return;
    }
    if (mSelectedItemID == item_id)
    {
        return;
    }
    if (mNeedsArrange && item_id.notNull())
    {
        mItemToSelect = item_id;
        return;
    }

    if (mItemMap[mSelectedItemID])
    {
        mItemMap[mSelectedItemID]->setSelected(FALSE);
    }
    if (mItemMap[item_id])
    {
        mItemMap[item_id]->setSelected(TRUE);
    }
    mSelectedItemID = item_id;
    signalSelectionItemID(item_id);

    if (scroll_to_selection)
    {
        scrollToShowItem(mSelectedItemID);
    }
}

void LLInventoryGallery::scrollToShowItem(const LLUUID& item_id)
{
    LLInventoryGalleryItem* item = mItemMap[item_id];
    if(item)
    {
        const LLRect visible_content_rect = mScrollPanel->getVisibleContentRect();

        LLRect item_rect;
        item->localRectToOtherView(item->getLocalRect(), &item_rect, mScrollPanel);
        LLRect overlap_rect(item_rect);
        overlap_rect.intersectWith(visible_content_rect);

        //Scroll when the selected item is outside the visible area
        if (overlap_rect.getHeight() + 5 < item->getRect().getHeight())
        {
            LLRect content_rect = mScrollPanel->getContentWindowRect();
            LLRect constraint_rect;
            constraint_rect.setOriginAndSize(0, 0, content_rect.getWidth(), content_rect.getHeight());

            LLRect item_doc_rect;
            item->localRectToOtherView(item->getLocalRect(), &item_doc_rect, mGalleryPanel);

            mScrollPanel->scrollToShowRect( item_doc_rect, constraint_rect );
        }
    }
}

LLInventoryGalleryItem* LLInventoryGallery::getSelectedItem()
{
    return mItemMap[mSelectedItemID];
}

void LLInventoryGallery::copy()
{
    LLClipboard::instance().reset();
    if (getVisible() && getEnabled() && mSelectedItemID.notNull())
    {
        LLClipboard::instance().addToClipboard(mSelectedItemID);
    }
    mFilterSubString.clear();
}

BOOL LLInventoryGallery::canCopy() const
{
    if (!getVisible() || !getEnabled() || mSelectedItemID.isNull())
    {
        return FALSE;
    }

    if (!isItemCopyable(mSelectedItemID))
    {
        return FALSE;
    }

    return TRUE;
}

void LLInventoryGallery::cut()
{
    // clear the inventory clipboard
    LLClipboard::instance().reset();
    if (getVisible() && getEnabled() && mSelectedItemID.notNull())
    {
        // todo: fade out selected item
        LLClipboard::instance().setCutMode(true);
        LLClipboard::instance().addToClipboard(mSelectedItemID);
    }
    mFilterSubString.clear();
}

BOOL LLInventoryGallery::canCut() const
{
    if (!getVisible() || !getEnabled() || mSelectedItemID.isNull())
    {
        return FALSE;
    }

    LLViewerInventoryCategory* cat = gInventory.getCategory(mSelectedItemID);
    if (cat)
    {
        if (!get_is_category_removable(&gInventory, mSelectedItemID))
        {
            return FALSE;
        }
    }
    else if (!get_is_item_removable(&gInventory, mSelectedItemID))
    {
        return FALSE;
    }

    return TRUE;
}

void LLInventoryGallery::paste()
{
    if (!LLClipboard::instance().hasContents())
    {
        return;
    }

    const LLUUID& marketplacelistings_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS);
    if (gInventory.isObjectDescendentOf(mSelectedItemID, marketplacelistings_id))
    {
        return;
    }

    LLInventoryObject* obj = gInventory.getObject(mSelectedItemID);
    bool is_folder = obj && (obj->getType() == LLAssetType::AT_CATEGORY);
    LLUUID dest = is_folder ? mSelectedItemID : mFolderID;
    bool is_cut_mode = LLClipboard::instance().isCutMode();

    std::vector<LLUUID> objects;
    LLClipboard::instance().pasteFromClipboard(objects);

    LLHandle<LLPanel> handle = getHandle();
    std::function <void(const LLUUID)> on_copy_callback = [handle](const LLUUID& inv_item)
    {
        LLInventoryGallery* panel = (LLInventoryGallery*)handle.get();
        if (panel)
        {
            // Scroll to pasted item and highlight it
            // Should it only highlight the last one?
            panel->changeItemSelection(inv_item, true);
        }
    };
    LLPointer<LLInventoryCallback> cb = new LLBoostFuncInventoryCallback(on_copy_callback);

    for (std::vector<LLUUID>::const_iterator iter = objects.begin(); iter != objects.end(); ++iter)
    {
        const LLUUID& item_id = (*iter);
        if (gInventory.isObjectDescendentOf(item_id, marketplacelistings_id) && (LLMarketplaceData::instance().isInActiveFolder(item_id) ||
                                                                                 LLMarketplaceData::instance().isListedAndActive(item_id)))
        {
            return;
        }
        LLViewerInventoryCategory* cat = gInventory.getCategory(item_id);
        if (cat)
        {
            if (is_cut_mode)
            {
                gInventory.changeCategoryParent(cat, dest, false);
                // Don't select immediately, wait for item to arrive
                mItemToSelect = item_id;
            }
            else
            {
                copy_inventory_category(&gInventory, cat, dest, LLUUID::null, false, on_copy_callback);
            }
        }
        else
        {
            LLViewerInventoryItem* item = gInventory.getItem(item_id);
            if (item)
            {
                if (is_cut_mode)
                {
                    gInventory.changeItemParent(item, dest, false);
                    // Don't select immediately, wait for item to arrive
                    mItemToSelect = item_id;
                }
                else
                {
                    if (item->getIsLinkType())
                    {
                        link_inventory_object(dest, item_id, cb);
                    }
                    else
                    {
                        copy_inventory_item(
                            gAgent.getID(),
                            item->getPermissions().getOwner(),
                            item->getUUID(),
                            dest,
                            std::string(),
                            cb);
                    }
                }
            }
        }
    }

    LLClipboard::instance().setCutMode(false);
}

BOOL LLInventoryGallery::canPaste() const
{
    // Return FALSE on degenerated cases: empty clipboard, no inventory, no agent
    if (!LLClipboard::instance().hasContents())
    {
        return FALSE;
    }

    // In cut mode, whatever is on the clipboard is always pastable
    if (LLClipboard::instance().isCutMode())
    {
        return TRUE;
    }

    // In normal mode, we need to check each element of the clipboard to know if we can paste or not
    std::vector<LLUUID> objects;
    LLClipboard::instance().pasteFromClipboard(objects);
    S32 count = objects.size();
    for (S32 i = 0; i < count; i++)
    {
        const LLUUID& item_id = objects.at(i);

        // Each item must be copyable to be pastable
        if (!isItemCopyable(item_id))
        {
            return FALSE;
        }
    }
    return TRUE;
}

void LLInventoryGallery::onDelete(const LLSD& notification, const LLSD& response, const LLUUID& selected_id)
{
    S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
    if (option == 0)
    {
        LLInventoryObject* obj = gInventory.getObject(selected_id);
        if (!obj)
        {
            return;
        }
        if (obj->getType() == LLAssetType::AT_CATEGORY)
        {
            if (get_is_category_removable(&gInventory, selected_id))
            {
                gInventory.removeCategory(selected_id);
            }
        }
        else
        {
            if (get_is_item_removable(&gInventory, selected_id))
            {
                gInventory.removeItem(selected_id);
            }
        }
    }
}

void LLInventoryGallery::deleteSelection()
{
    if (!LLInventoryAction::sDeleteConfirmationDisplayed) // ask for the confirmation at least once per session
    {
        LLNotifications::instance().setIgnored("DeleteItems", false);
        LLInventoryAction::sDeleteConfirmationDisplayed = true;
    }

    LLSD args;
    args["QUESTION"] = LLTrans::getString("DeleteItem");
    LLNotificationsUtil::add("DeleteItems", args, LLSD(), boost::bind(&LLInventoryGallery::onDelete, _1, _2, mSelectedItemID));
}

bool LLInventoryGallery::canDeleteSelection()
{
    if (mSelectedItemID.isNull())
    {
        return false;
    }

    LLViewerInventoryCategory* cat = gInventory.getCategory(mSelectedItemID);
    if (cat)
    {
        if (!get_is_category_removable(&gInventory, mSelectedItemID))
        {
            return false;
        }
    }
    else if (!get_is_item_removable(&gInventory, mSelectedItemID))
    {
        return false;
    }

    const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
    return !gInventory.isObjectDescendentOf(mSelectedItemID, trash_id);
}

void LLInventoryGallery::pasteAsLink()
{
    if (!LLClipboard::instance().hasContents())
    {
        return;
    }

    const LLUUID& current_outfit_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_CURRENT_OUTFIT);
    const LLUUID& marketplacelistings_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS);
    const LLUUID& my_outifts_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MY_OUTFITS);

    LLUUID dest;
    LLInventoryObject* obj = gInventory.getObject(mSelectedItemID);
    if (obj && obj->getType() == LLAssetType::AT_CATEGORY)
    {
        dest = mSelectedItemID;
    }
    else
    {
        dest = mFolderID;
    }

    const BOOL move_is_into_current_outfit = (dest == current_outfit_id);
    const BOOL move_is_into_my_outfits = (dest == my_outifts_id) || gInventory.isObjectDescendentOf(dest, my_outifts_id);
    const BOOL move_is_into_marketplacelistings = gInventory.isObjectDescendentOf(dest, marketplacelistings_id);

    if (move_is_into_marketplacelistings || move_is_into_current_outfit || move_is_into_my_outfits)
    {
        return;
    }
    std::vector<LLUUID> objects;
    LLClipboard::instance().pasteFromClipboard(objects);

    LLHandle<LLPanel> handle = getHandle();
    std::function <void(const LLUUID)> on_link_callback = [handle](const LLUUID& inv_item)
    {
        LLInventoryGallery *panel = (LLInventoryGallery*)handle.get();
        if (panel)
        {
            // Scroll to pasted item and highlight it
            // Should it only highlight the last one?
            panel->changeItemSelection(inv_item, true);
        }
    };
    LLPointer<LLInventoryCallback> cb = new LLBoostFuncInventoryCallback(on_link_callback);

    for (std::vector<LLUUID>::const_iterator iter = objects.begin();
         iter != objects.end();
         ++iter)
    {
        const LLUUID& object_id = (*iter);
        if (LLConstPointer<LLInventoryObject> link_obj = gInventory.getObject(object_id))
        {
            link_inventory_object(dest, link_obj, cb);
        }
    }

    LLClipboard::instance().setCutMode(false);
}

void LLInventoryGallery::claimEditHandler()
{
    gEditMenuHandler = this;
}

bool LLInventoryGallery::isItemCopyable(const LLUUID & item_id)
{
    const LLInventoryCategory* cat = gInventory.getCategory(item_id);
    if (cat)
    {
        // Folders are copyable if items in them are, recursively, copyable.
        // Get the content of the folder
        LLInventoryModel::cat_array_t* cat_array;
        LLInventoryModel::item_array_t* item_array;
        gInventory.getDirectDescendentsOf(item_id, cat_array, item_array);

        // Check the items
        LLInventoryModel::item_array_t item_array_copy = *item_array;
        for (LLInventoryModel::item_array_t::iterator iter = item_array_copy.begin(); iter != item_array_copy.end(); iter++)
        {
            LLInventoryItem* item = *iter;
            if (!isItemCopyable(item->getUUID()))
            {
                return false;
            }
        }

        // Check the folders
        LLInventoryModel::cat_array_t cat_array_copy = *cat_array;
        for (LLInventoryModel::cat_array_t::iterator iter = cat_array_copy.begin(); iter != cat_array_copy.end(); iter++)
        {
            LLViewerInventoryCategory* category = *iter;
            if (!isItemCopyable(category->getUUID()))
            {
                return false;
            }
        }

        return true;
    }

    LLViewerInventoryItem* item = gInventory.getItem(item_id);
    if (item)
    {
        // Can't copy worn objects.
        // Worn objects are tied to their inworld conterparts
        // Copy of modified worn object will return object with obsolete asset and inventory
        if (get_is_item_worn(item_id))
        {
            return false;
        }

        static LLCachedControl<bool> inventory_linking(gSavedSettings, "InventoryLinking", true);
        return (item->getIsLinkType() && inventory_linking)
            || item->getPermissions().allowCopyBy(gAgent.getID());
    }

    return false;
}

void LLInventoryGallery::updateMessageVisibility()
{

    mMessageTextBox->setVisible(mItems.empty());
    if(mItems.empty())
    {
        mMessageTextBox->setText(hasDescendents(mFolderID) ? LLTrans::getString("InventorySingleFolderEmpty") : LLTrans::getString("InventorySingleFolderNoMatches"));
    }

    mScrollPanel->setVisible(!mItems.empty());
}

void LLInventoryGallery::refreshList(const LLUUID& category_id)
{
    LLInventoryModel::cat_array_t* cat_array;
    LLInventoryModel::item_array_t* item_array;

    gInventory.getDirectDescendentsOf(category_id, cat_array, item_array);
    uuid_vec_t vadded;
    uuid_vec_t vremoved;

    // Create added and removed items vectors.
    computeDifference(*cat_array, *item_array, vadded, vremoved);

    // Handle added tabs.
    for (uuid_vec_t::const_iterator iter = vadded.begin();
        iter != vadded.end();
        ++iter)
    {
        const LLUUID cat_id = (*iter);
        updateAddedItem(cat_id);
        mNeedsArrange = true;
    }

    // Handle removed tabs.
    for (uuid_vec_t::const_iterator iter = vremoved.begin(); iter != vremoved.end(); ++iter)
    {
        const LLUUID cat_id = (*iter);
        updateRemovedItem(cat_id);
    }

    const LLInventoryModel::changed_items_t& changed_items = gInventory.getChangedIDs();
    for (LLInventoryModel::changed_items_t::const_iterator items_iter = changed_items.begin();
        items_iter != changed_items.end();
        ++items_iter)
    {
        LLInventoryObject* obj = gInventory.getObject(*items_iter);
        if(!obj)
        {
            return;
        }

        updateChangedItemName(*items_iter, obj->getName());
        mNeedsArrange = true;
    }

    if(mNeedsArrange || mItemToSelect.notNull())
    {
        // Don't scroll to target/arrange immediately
        // since more updates might be pending
        gIdleCallbacks.addFunction(onIdle, (void*)this);
    }
    updateMessageVisibility();
}

void LLInventoryGallery::computeDifference(
    const LLInventoryModel::cat_array_t vcats,
    const LLInventoryModel::item_array_t vitems,
    uuid_vec_t& vadded,
    uuid_vec_t& vremoved)
{
    uuid_vec_t vnew;
    // Creating a vector of newly collected UUIDs.
    for (LLInventoryModel::cat_array_t::const_iterator iter = vcats.begin();
        iter != vcats.end();
        iter++)
    {
        vnew.push_back((*iter)->getUUID());
    }
    for (LLInventoryModel::item_array_t::const_iterator iter = vitems.begin();
        iter != vitems.end();
        iter++)
    {
        vnew.push_back((*iter)->getUUID());
    }

    uuid_vec_t vcur;
    getCurrentCategories(vcur);
    std::copy(mItemBuildQuery.begin(), mItemBuildQuery.end(), std::back_inserter(vcur));

    LLCommonUtils::computeDifference(vnew, vcur, vadded, vremoved);
}

void LLInventoryGallery::onCOFChanged()
{
    LLInventoryModel::cat_array_t cat_array;
    LLInventoryModel::item_array_t item_array;

    gInventory.collectDescendents(
        LLAppearanceMgr::instance().getCOF(),
        cat_array,
        item_array,
        LLInventoryModel::EXCLUDE_TRASH);

    uuid_vec_t vnew;
    uuid_vec_t vadded;
    uuid_vec_t vremoved;

    for (LLInventoryModel::item_array_t::const_iterator iter = item_array.begin();
        iter != item_array.end();
        ++iter)
    {
        vnew.push_back((*iter)->getLinkedUUID());
    }

    // We need to update only items that were added or removed from COF.
    LLCommonUtils::computeDifference(vnew, mCOFLinkedItems, vadded, vremoved);

    mCOFLinkedItems = vnew;
    
    for (uuid_vec_t::const_iterator iter = vadded.begin();
        iter != vadded.end();
        ++iter)
    {
        updateWornItem(*iter, true);
    }

    for (uuid_vec_t::const_iterator iter = vremoved.begin(); iter != vremoved.end(); ++iter)
    {
        updateWornItem(*iter, false);
    }
}

void LLInventoryGallery::onGesturesChanged()
{
    uuid_vec_t vnew;
    uuid_vec_t vadded;
    uuid_vec_t vremoved;

    const LLGestureMgr::item_map_t& active_gestures = LLGestureMgr::instance().getActiveGestures();
    for (LLGestureMgr::item_map_t::const_iterator iter = active_gestures.begin();
        iter != active_gestures.end();
        ++iter)
    {
        vnew.push_back(iter->first);
    }

    LLCommonUtils::computeDifference(vnew, mActiveGestures, vadded, vremoved);

    mActiveGestures = vnew;
    
    for (uuid_vec_t::const_iterator iter = vadded.begin();
        iter != vadded.end();
        ++iter)
    {
        updateWornItem(*iter, true);
    }

    for (uuid_vec_t::const_iterator iter = vremoved.begin(); iter != vremoved.end(); ++iter)
    {
        updateWornItem(*iter, false);
    }
}

void LLInventoryGallery::deselectItem(const LLUUID& category_id)
{
    // Reset selection if the item is selected.
    if (category_id == mSelectedItemID)
    {
        mSelectedItemID = LLUUID::null;
        signalSelectionItemID(mSelectedItemID);
    }
}

void LLInventoryGallery::clearSelection()
{
    if(mSelectedItemID != LLUUID::null)
    {
        changeItemSelection(LLUUID::null);
    }
}

void LLInventoryGallery::signalSelectionItemID(const LLUUID& category_id)
{
    mSelectionChangeSignal(category_id);
}

boost::signals2::connection LLInventoryGallery::setSelectionChangeCallback(selection_change_callback_t cb)
{
    return mSelectionChangeSignal.connect(cb);
}

LLUUID LLInventoryGallery::getOutfitImageID(LLUUID outfit_id)
{
    LLUUID thumbnail_id;
    LLViewerInventoryCategory* cat = gInventory.getCategory(outfit_id);
    if (cat && cat->getPreferredType() == LLFolderType::FT_OUTFIT)
    {
        LLInventoryModel::cat_array_t cats;
        LLInventoryModel::item_array_t items;
        // Not LLIsOfAssetType, because we allow links
        LLIsTextureType f;
        gInventory.getDirectDescendentsOf(outfit_id, cats, items, f);

        // Exactly one texture found => show the texture as thumbnail
        if (1 == items.size())
        {
            LLViewerInventoryItem* item = items.front();
            if (item && item->getIsLinkType())
            {
                item = item->getLinkedItem();
            }
            if (item)
            {
                thumbnail_id = item->getAssetUUID();
            }
        }
    }
    return thumbnail_id;
}

boost::signals2::connection LLInventoryGallery::setRootChangedCallback(callback_t cb)
{
    return mRootChangedSignal.connect(cb);
}

void LLInventoryGallery::onForwardFolder()
{
    if(isForwardAvailable())
    {
        mBackwardFolders.push_back(mFolderID);
        mFolderID = mForwardFolders.back();
        mForwardFolders.pop_back();
        dirtyRootFolder();
    }
}

void LLInventoryGallery::onBackwardFolder()
{
    if(isBackwardAvailable())
    {
        mForwardFolders.push_back(mFolderID);
        mFolderID = mBackwardFolders.back();
        mBackwardFolders.pop_back();
        dirtyRootFolder();
    }
}

void LLInventoryGallery::clearNavigationHistory()
{
    mForwardFolders.clear();
    mBackwardFolders.clear();
}

bool LLInventoryGallery::isBackwardAvailable()
{
    return (!mBackwardFolders.empty() && (mFolderID != mBackwardFolders.back()));
}

bool LLInventoryGallery::isForwardAvailable()
{
    return (!mForwardFolders.empty() && (mFolderID != mForwardFolders.back()));
}

BOOL LLInventoryGallery::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
                                           EDragAndDropType cargo_type, void* cargo_data,
                                           EAcceptance* accept, std::string& tooltip_msg)
{
    // have children handle it first
    BOOL handled = LLView::handleDragAndDrop(x, y, mask, drop, cargo_type, cargo_data,
                                            accept, tooltip_msg);

    // when drop is not handled by child, it should be handled by the root folder .
    if (!handled || (*accept == ACCEPT_NO))
    {
        handled = baseHandleDragAndDrop(mFolderID, drop, cargo_type, cargo_data, accept, tooltip_msg);
    }

    return handled;
}

bool LLInventoryGallery::areViewsInitialized()
{
    return mGalleryCreated && mItemBuildQuery.empty();
}

bool LLInventoryGallery::hasDescendents(const LLUUID& cat_id)
{
    LLInventoryModel::cat_array_t* cats;
    LLInventoryModel::item_array_t* items;
    gInventory.getDirectDescendentsOf(cat_id, cats, items);

    return (cats->empty() && items->empty());
}

bool LLInventoryGallery::checkAgainstFilterType(const LLUUID& object_id)
{
    const LLInventoryObject *object = gInventory.getObject(object_id);
    if(!object) return false;

    LLInventoryType::EType object_type = LLInventoryType::IT_CATEGORY;
    LLInventoryItem* inv_item = gInventory.getItem(object_id);
    if (inv_item)
    {
        object_type = inv_item->getInventoryType();
    }
    const U32 filterTypes = mFilter->getFilterTypes();

    if ((filterTypes & LLInventoryFilter::FILTERTYPE_OBJECT) && inv_item)
    {
        switch (object_type)
        {
        case LLInventoryType::IT_NONE:
            // If it has no type, pass it, unless it's a link.
            if (object && object->getIsLinkType())
            {
                return false;
            }
            break;
        case LLInventoryType::IT_UNKNOWN:
            {
                // Unknows are only shown when we show every type.
                // Unknows are 255 and won't fit in 64 bits.
                if (mFilter->getFilterObjectTypes() != 0xffffffffffffffffULL)
                {
                    return false;
                }
                break;
            }
        default:
            if ((1LL << object_type & mFilter->getFilterObjectTypes()) == U64(0))
            {
                return false;
            }
            break;
        }
    }
    
    if (filterTypes & LLInventoryFilter::FILTERTYPE_DATE)
    {
        const U16 HOURS_TO_SECONDS = 3600;
        time_t earliest = time_corrected() - mFilter->getHoursAgo() * HOURS_TO_SECONDS;

        if (mFilter->getMinDate() > time_min() && mFilter->getMinDate() < earliest)
        {
            earliest = mFilter->getMinDate();
        }
        else if (!mFilter->getHoursAgo())
        {
            earliest = 0;
        }

        if (LLInventoryFilter::FILTERDATEDIRECTION_NEWER == mFilter->getDateSearchDirection() || mFilter->isSinceLogoff())
        {
            if (object->getCreationDate() < earliest ||
                object->getCreationDate() > mFilter->getMaxDate())
                return false;
        }
        else
        {
            if (object->getCreationDate() > earliest ||
                object->getCreationDate() > mFilter->getMaxDate())
                return false;
        }
    }
    return true;
}

bool LLInventoryGallery::hasVisibleItems()
{
    return mItemsAddedCount > 0;
}

void LLInventoryGallery::handleModifiedFilter()
{
    if(mFilter->isModified())
    {
        reArrangeRows();
    }
}

//-----------------------------
// LLInventoryGalleryItem
//-----------------------------

static LLDefaultChildRegistry::Register<LLInventoryGalleryItem> r("inventory_gallery_item");

LLInventoryGalleryItem::LLInventoryGalleryItem(const Params& p)
    : LLPanel(p),
    mSelected(false),
    mDefaultImage(true),
    mItemName(""),
    mWornSuffix(""),
    mPermSuffix(""),
    mUUID(LLUUID()),
    mIsFolder(true),
    mIsLink(false),
    mHidden(false),
    mGallery(NULL),
    mType(LLAssetType::AT_NONE),
    mSortGroup(SG_ITEM)
{
    buildFromFile("panel_inventory_gallery_item.xml");
}

LLInventoryGalleryItem::~LLInventoryGalleryItem()
{
}

BOOL LLInventoryGalleryItem::postBuild()
{
    mNameText = getChild<LLTextBox>("item_name");
    mTextBgPanel = getChild<LLPanel>("text_bg_panel");

    return TRUE;
}

void LLInventoryGalleryItem::setType(LLAssetType::EType type, LLInventoryType::EType inventory_type, U32 flags, bool is_link)
{
    mType = type;
    mIsFolder = (mType == LLAssetType::AT_CATEGORY);
    mIsLink = is_link;

    std::string icon_name = LLInventoryIcon::getIconName(mType, inventory_type, flags);
    if(mIsFolder)
    {
        mSortGroup = SG_NORMAL_FOLDER;
        LLUUID folder_id = mUUID;
        if(mIsLink)
        {
            LLInventoryObject* obj = gInventory.getObject(mUUID);
            if (obj)
            {
                folder_id = obj->getLinkedUUID();
            }
        }
        LLViewerInventoryCategory* cat = gInventory.getCategory(folder_id);
        if (cat)
        {
            LLFolderType::EType preferred_type = cat->getPreferredType();
            icon_name = LLViewerFolderType::lookupIconName(preferred_type);

            if (preferred_type == LLFolderType::FT_TRASH)
            {
                mSortGroup = SG_TRASH_FOLDER;
            }
            else if(LLFolderType::lookupIsProtectedType(cat->getPreferredType()))
            {
                mSortGroup = SG_SYSTEM_FOLDER;
            }
        }
    }
    else
    {
        const LLInventoryItem *item = gInventory.getItem(mUUID);
        if(item && (LLAssetType::AT_CALLINGCARD != item->getType()) && !mIsLink)
        {
            std::string delim(" --");
            bool copy = item->getPermissions().allowCopyBy(gAgent.getID());
            if (!copy)
            {
                mPermSuffix += delim;
                mPermSuffix += LLTrans::getString("no_copy_lbl");
            }
            bool mod = item->getPermissions().allowModifyBy(gAgent.getID());
            if (!mod)
            {
                mPermSuffix += mPermSuffix.empty() ? delim : ",";
                mPermSuffix += LLTrans::getString("no_modify_lbl");
            }
            bool xfer = item->getPermissions().allowOperationBy(PERM_TRANSFER, gAgent.getID());
            if (!xfer)
            {
                mPermSuffix += mPermSuffix.empty() ? delim : ",";
                mPermSuffix += LLTrans::getString("no_transfer_lbl");
            }
        }
    }

    getChild<LLIconCtrl>("item_type")->setValue(icon_name);
    getChild<LLIconCtrl>("link_overlay")->setVisible(is_link);
}

void LLInventoryGalleryItem::setThumbnail(LLUUID id)
{
    mDefaultImage = id.isNull();
    if(mDefaultImage)
    {
        getChild<LLThumbnailCtrl>("preview_thumbnail")->clearTexture();
    }
    else
    {
        getChild<LLThumbnailCtrl>("preview_thumbnail")->setValue(id);
    }
}

void LLInventoryGalleryItem::draw()
{
    LLPanel::draw();

    // Draw border
    LLUIColor border_color = LLUIColorTable::instance().getColor(mSelected ? "MenuItemHighlightBgColor" : "TextFgTentativeColor", LLColor4::white);
    LLRect border = getChildView("preview_thumbnail")->getRect();
    border.mRight = border.mRight + 1;
    gl_rect_2d(border, border_color.get(), FALSE);
}

void LLInventoryGalleryItem::setItemName(std::string name)
{
    mItemName = name;
    updateNameText();
}

void LLInventoryGalleryItem::setSelected(bool value)
{
    mSelected = value;
    mTextBgPanel->setBackgroundVisible(value);
}

BOOL LLInventoryGalleryItem::handleMouseDown(S32 x, S32 y, MASK mask)
{
    setFocus(TRUE);
    mGallery->claimEditHandler();

    gFocusMgr.setMouseCapture(this);
    S32 screen_x;
    S32 screen_y;
    localPointToScreen(x, y, &screen_x, &screen_y );
    LLToolDragAndDrop::getInstance()->setDragStart(screen_x, screen_y);
    return TRUE;
}

BOOL LLInventoryGalleryItem::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
    setFocus(TRUE);
    mGallery->claimEditHandler();

    LLUICtrl::handleRightMouseDown(x, y, mask);
    return TRUE;
}

BOOL LLInventoryGalleryItem::handleMouseUp(S32 x, S32 y, MASK mask)
{
    if(hasMouseCapture())
    {
        gFocusMgr.setMouseCapture(NULL);
        return TRUE;
    }
    return LLPanel::handleMouseUp(x, y, mask);
}

BOOL LLInventoryGalleryItem::handleHover(S32 x, S32 y, MASK mask)
{
    if(hasMouseCapture())
    {
        S32 screen_x;
        S32 screen_y;
        localPointToScreen(x, y, &screen_x, &screen_y );

        if(LLToolDragAndDrop::getInstance()->isOverThreshold(screen_x, screen_y))
        {
            const LLInventoryItem *item = gInventory.getItem(mUUID);
            if(item)
            {
                EDragAndDropType type = LLViewerAssetType::lookupDragAndDropType(item->getType());
                LLToolDragAndDrop::ESource src = LLToolDragAndDrop::SOURCE_LIBRARY;
                if(item->getPermissions().getOwner() == gAgent.getID())
                {
                    src = LLToolDragAndDrop::SOURCE_AGENT;
                }
                LLToolDragAndDrop::getInstance()->beginDrag(type, item->getUUID(), src);
                return LLToolDragAndDrop::getInstance()->handleHover(x, y, mask );
            }

            const LLInventoryCategory *cat = gInventory.getCategory(mUUID);
            if(cat && gInventory.isObjectDescendentOf(mUUID, gInventory.getRootFolderID())
                   && !LLFolderType::lookupIsProtectedType((cat)->getPreferredType()))
            {
                LLToolDragAndDrop::getInstance()->beginDrag(LLViewerAssetType::lookupDragAndDropType(cat->getType()), cat->getUUID(), LLToolDragAndDrop::SOURCE_AGENT);
                return LLToolDragAndDrop::getInstance()->handleHover(x, y, mask );
            }
        }
    }
    return LLUICtrl::handleHover(x,y,mask);
}

BOOL LLInventoryGalleryItem::handleDoubleClick(S32 x, S32 y, MASK mask)
{
    if (mIsFolder && mGallery)
    {
        mGallery->setRootFolder(mUUID);
    }
    else
    {
        LLInvFVBridgeAction::doAction(mUUID, &gInventory);
    }

    return TRUE;
}

BOOL LLInventoryGalleryItem::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
                       EDragAndDropType cargo_type,
                       void* cargo_data,
                       EAcceptance* accept,
                       std::string& tooltip_msg)
{
    if (!mIsFolder)
    {
        return FALSE;
    }
    return mGallery->baseHandleDragAndDrop(mUUID, drop, cargo_type, cargo_data, accept, tooltip_msg);
}

BOOL LLInventoryGalleryItem::handleKeyHere(KEY key, MASK mask)
{
    if (!mGallery)
    {
        return FALSE;
    }

    BOOL handled = FALSE;
    switch (key)
    {
        case KEY_LEFT:
            mGallery->moveLeft();
            handled = true;
            break;

        case KEY_RIGHT:
            mGallery->moveRight();
            handled = true;
            break;

        case KEY_UP:
            mGallery->moveUp();
            handled = true;
            break;

        case KEY_DOWN:
            mGallery->moveDown();
            handled = true;
            break;

        default:
            break;
    }
    return handled;
}

void LLInventoryGalleryItem::setWorn(bool value)
{
    mWorn = value;

    if(mWorn)
    {
        mWornSuffix = (mType == LLAssetType::AT_GESTURE) ? LLTrans::getString("active") : LLTrans::getString("worn");
    }
    else
    {
        mWornSuffix = "";
    }

    updateNameText();
}

LLFontGL* LLInventoryGalleryItem::getTextFont()
{
    if(mWorn)
    {
        return LLFontGL::getFontSansSerifSmallBold();
    }
    return mIsLink ? LLFontGL::getFontSansSerifSmallItalic() : LLFontGL::getFontSansSerifSmall();
}

void LLInventoryGalleryItem::updateNameText()
{
    mNameText->setFont(getTextFont());
    mNameText->setText(mItemName + mPermSuffix + mWornSuffix);
    mNameText->setToolTip(mItemName + mPermSuffix + mWornSuffix);
    getChild<LLThumbnailCtrl>("preview_thumbnail")->setToolTip(mItemName + mPermSuffix + mWornSuffix);
}

//-----------------------------
// LLThumbnailsObserver
//-----------------------------

void LLThumbnailsObserver::changed(U32 mask)
{
    std::vector<LLUUID> deleted_ids;
    for (item_map_t::iterator iter = mItemMap.begin();
         iter != mItemMap.end();
         ++iter)
    {
        const LLUUID& obj_id = (*iter).first;
        LLItemData& data = (*iter).second;
        
        LLInventoryObject* obj = gInventory.getObject(obj_id);
        if (!obj)
        {
            deleted_ids.push_back(obj_id);
            continue;
        }

        const LLUUID thumbnail_id = obj->getThumbnailUUID();
        if (data.mThumbnailID != thumbnail_id)
        {
            data.mThumbnailID = thumbnail_id;
            data.mCallback();
        }
    }

    // Remove deleted items from the list
    for (std::vector<LLUUID>::iterator deleted_id = deleted_ids.begin(); deleted_id != deleted_ids.end(); ++deleted_id)
    {
        removeItem(*deleted_id);
    }
}

bool LLThumbnailsObserver::addItem(const LLUUID& obj_id, callback_t cb)
{
    LLInventoryObject* obj = gInventory.getObject(obj_id);
    if (obj)
    {
        mItemMap.insert(item_map_value_t(obj_id, LLItemData(obj_id, obj->getThumbnailUUID(), cb)));
        return true;
    }
    return false;
}

void LLThumbnailsObserver::removeItem(const LLUUID& obj_id)
{
    mItemMap.erase(obj_id);
}

//-----------------------------
// Helper drag&drop functions
//-----------------------------

BOOL LLInventoryGallery::baseHandleDragAndDrop(LLUUID dest_id, BOOL drop,
                       EDragAndDropType cargo_type,
                       void* cargo_data,
                       EAcceptance* accept,
                       std::string& tooltip_msg)
{
    LLInventoryItem* inv_item = (LLInventoryItem*)cargo_data;

    BOOL accepted = FALSE;
    switch(cargo_type)
    {
        case DAD_TEXTURE:
        case DAD_SOUND:
        case DAD_CALLINGCARD:
        case DAD_LANDMARK:
        case DAD_SCRIPT:
        case DAD_CLOTHING:
        case DAD_OBJECT:
        case DAD_NOTECARD:
        case DAD_BODYPART:
        case DAD_ANIMATION:
        case DAD_GESTURE:
        case DAD_MESH:
        case DAD_SETTINGS:
            accepted = dragItemIntoFolder(dest_id, inv_item, drop, tooltip_msg, true);
            if (accepted && drop)
            {
                // Don't select immediately, wait for item to arrive
                mItemToSelect = inv_item->getUUID();
            }
            break;
        case DAD_LINK:
            // DAD_LINK type might mean one of two asset types: AT_LINK or AT_LINK_FOLDER.
            // If we have an item of AT_LINK_FOLDER type we should process the linked
            // category being dragged or dropped into folder.
            if (inv_item && LLAssetType::AT_LINK_FOLDER == inv_item->getActualType())
            {
                LLInventoryCategory* linked_category = gInventory.getCategory(inv_item->getLinkedUUID());
                if (linked_category)
                {
                    accepted = dragCategoryIntoFolder(dest_id, (LLInventoryCategory*)linked_category, drop, tooltip_msg, TRUE);
                }
            }
            else
            {
                accepted = dragItemIntoFolder(dest_id, inv_item, drop, tooltip_msg, TRUE);
            }
            if (accepted && drop && inv_item)
            {
                mItemToSelect = inv_item->getUUID();
            }
            break;
        case DAD_CATEGORY:
            if (LLFriendCardsManager::instance().isAnyFriendCategory(dest_id))
            {
                accepted = FALSE;
            }
            else
            {
                LLInventoryCategory* cat_ptr = (LLInventoryCategory*)cargo_data;
                accepted = dragCategoryIntoFolder(dest_id, cat_ptr, drop, tooltip_msg, FALSE);
                if (accepted && drop)
                {
                    mItemToSelect = cat_ptr->getUUID();
                }
            }
            break;
        case DAD_ROOT_CATEGORY:
        case DAD_NONE:
            break;
        default:
            LL_WARNS() << "Unhandled cargo type for drag&drop " << cargo_type << LL_ENDL;
            break;
    }
    if (accepted)
    {
        *accept = ACCEPT_YES_MULTI;
    }
    else
    {
        *accept = ACCEPT_NO;
    }
    return accepted;
}

// copy of LLFolderBridge::dragItemIntoFolder
BOOL dragItemIntoFolder(LLUUID folder_id, LLInventoryItem* inv_item, BOOL drop, std::string& tooltip_msg, BOOL user_confirm)
{
    LLViewerInventoryCategory * cat = gInventory.getCategory(folder_id);
    if (!cat)
    {
        return FALSE;
    }
    LLInventoryModel* model = &gInventory;

    if (!model || !inv_item) return FALSE;

    // cannot drag into library
    if((gInventory.getRootFolderID() != folder_id) && !model->isObjectDescendentOf(folder_id, gInventory.getRootFolderID()))
    {
        return FALSE;
    }
    if (!isAgentAvatarValid()) return FALSE;

    const LLUUID &current_outfit_id = model->findCategoryUUIDForType(LLFolderType::FT_CURRENT_OUTFIT);
    const LLUUID &favorites_id = model->findCategoryUUIDForType(LLFolderType::FT_FAVORITE);
    const LLUUID &landmarks_id = model->findCategoryUUIDForType(LLFolderType::FT_LANDMARK);
    const LLUUID &marketplacelistings_id = model->findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS);
    const LLUUID &my_outifts_id = model->findCategoryUUIDForType(LLFolderType::FT_MY_OUTFITS);

    const BOOL move_is_into_current_outfit = (folder_id == current_outfit_id);
    const BOOL move_is_into_favorites = (folder_id == favorites_id);
    const BOOL move_is_into_my_outfits = (folder_id == my_outifts_id) || model->isObjectDescendentOf(folder_id, my_outifts_id);
    const BOOL move_is_into_outfit = move_is_into_my_outfits || (cat && cat->getPreferredType()==LLFolderType::FT_OUTFIT);
    const BOOL move_is_into_landmarks = (folder_id == landmarks_id) || model->isObjectDescendentOf(folder_id, landmarks_id);
    const BOOL move_is_into_marketplacelistings = model->isObjectDescendentOf(folder_id, marketplacelistings_id);
    const BOOL move_is_from_marketplacelistings = model->isObjectDescendentOf(inv_item->getUUID(), marketplacelistings_id);

    LLToolDragAndDrop::ESource source = LLToolDragAndDrop::getInstance()->getSource();
    BOOL accept = FALSE;
    LLViewerObject* object = NULL;
    if(LLToolDragAndDrop::SOURCE_AGENT == source)
    {
        const LLUUID &trash_id = model->findCategoryUUIDForType(LLFolderType::FT_TRASH);

        const BOOL move_is_into_trash = (folder_id == trash_id) || model->isObjectDescendentOf(folder_id, trash_id);
        const BOOL move_is_outof_current_outfit = LLAppearanceMgr::instance().getIsInCOF(inv_item->getUUID());

        //--------------------------------------------------------------------------------
        // Determine if item can be moved.
        //

        BOOL is_movable = TRUE;

        switch (inv_item->getActualType())
        {
            case LLAssetType::AT_CATEGORY:
                is_movable = !LLFolderType::lookupIsProtectedType(((LLInventoryCategory*)inv_item)->getPreferredType());
                break;
            default:
                break;
        }
        // Can't explicitly drag things out of the COF.
        if (move_is_outof_current_outfit)
        {
            is_movable = FALSE;
        }
        if (move_is_into_trash)
        {
            is_movable &= inv_item->getIsLinkType() || !get_is_item_worn(inv_item->getUUID());
        }
        if (is_movable)
        {
            // Don't allow creating duplicates in the Calling Card/Friends
            // subfolders, see bug EXT-1599. Check is item direct descendent
            // of target folder and forbid item's movement if it so.
            // Note: isItemDirectDescendentOfCategory checks if
            // passed category is in the Calling Card/Friends folder
            is_movable &= !LLFriendCardsManager::instance().isObjDirectDescendentOfCategory(inv_item, cat);
        }

        //
        //--------------------------------------------------------------------------------
        
        //--------------------------------------------------------------------------------
        // Determine if item can be moved & dropped
        // Note: if user_confirm is false, we already went through those accept logic test and can skip them

        accept = TRUE;

        if (user_confirm && !is_movable)
        {
            accept = FALSE;
        }
        else if (user_confirm && (folder_id == inv_item->getParentUUID()) && !move_is_into_favorites)
        {
            accept = FALSE;
        }
        else if (user_confirm && (move_is_into_current_outfit || move_is_into_outfit))
        {
            accept = can_move_to_outfit(inv_item, move_is_into_current_outfit);
        }
        else if (user_confirm && (move_is_into_favorites || move_is_into_landmarks))
        {
            accept = can_move_to_landmarks(inv_item);
        }
        else if (user_confirm && move_is_into_marketplacelistings)
        {
            //disable dropping in or out of marketplace for now
            return FALSE;
            
            /*const LLViewerInventoryCategory * master_folder = model->getFirstDescendantOf(marketplacelistings_id, folder_id);
            LLViewerInventoryCategory * dest_folder = cat;
            accept = can_move_item_to_marketplace(master_folder, dest_folder, inv_item, tooltip_msg, LLToolDragAndDrop::instance().getCargoCount() - LLToolDragAndDrop::instance().getCargoIndex());*/
        }

        // Check that the folder can accept this item based on folder/item type compatibility (e.g. stock folder compatibility)
        if (user_confirm && accept)
        {
            LLViewerInventoryCategory * dest_folder = cat;
            accept = dest_folder->acceptItem(inv_item);
        }
        
        LLInventoryPanel* active_panel = LLInventoryPanel::getActiveInventoryPanel(FALSE);

        if (accept && drop)
        {
            if (inv_item->getType() == LLAssetType::AT_GESTURE
                && LLGestureMgr::instance().isGestureActive(inv_item->getUUID()) && move_is_into_trash)
            {
                LLGestureMgr::instance().deactivateGesture(inv_item->getUUID());
            }
            // If an item is being dragged between windows, unselect everything in the active window
            // so that we don't follow the selection to its new location (which is very annoying).
                        // RN: a better solution would be to deselect automatically when an   item is moved
            // and then select any item that is dropped only in the panel that it   is dropped in
            if (active_panel)
            {
                active_panel->unSelectAll();
            }
            // Dropping in or out of marketplace needs (sometimes) confirmation
            if (user_confirm && (move_is_from_marketplacelistings || move_is_into_marketplacelistings))
            {
                //disable dropping in or out of marketplace for now
                return FALSE;
            }

            //--------------------------------------------------------------------------------
            // Destination folder logic
            //

            // FAVORITES folder
            // (copy the item)
            else if (move_is_into_favorites)
            {
                copy_inventory_item(
                    gAgent.getID(),
                    inv_item->getPermissions().getOwner(),
                    inv_item->getUUID(),
                    folder_id,
                    std::string(),
                    LLPointer<LLInventoryCallback>(NULL));
            }
            // CURRENT OUTFIT or OUTFIT folder
            // (link the item)
            else if (move_is_into_current_outfit || move_is_into_outfit)
            {
                if (move_is_into_current_outfit)
                {
                    LLAppearanceMgr::instance().wearItemOnAvatar(inv_item->getUUID(), true, true);
                }
                else
                {
                    LLPointer<LLInventoryCallback> cb = NULL;
                    link_inventory_object(folder_id, LLConstPointer<LLInventoryObject>(inv_item), cb);
                }
            }
            // MARKETPLACE LISTINGS folder
            // Move the item
            else if (move_is_into_marketplacelistings)
            {
                //move_item_to_marketplacelistings(inv_item, mUUID);
                return FALSE;
            }
            // NORMAL or TRASH folder
            // (move the item, restamp if into trash)
            else
            {
                // set up observer to select item once drag and drop from inbox is complete
                if (gInventory.isObjectDescendentOf(inv_item->getUUID(), gInventory.findCategoryUUIDForType(LLFolderType::FT_INBOX)))
                {
                    set_dad_inbox_object(inv_item->getUUID());
                }

                gInventory.changeItemParent((LLViewerInventoryItem*)inv_item, folder_id, move_is_into_trash);
            }
            
            if (move_is_from_marketplacelistings)
            {
                // If we move from an active (listed) listing, checks that it's still valid, if not, unlist
                /*LLUUID version_folder_id = LLMarketplaceData::instance().getActiveFolder(from_folder_uuid);
                if (version_folder_id.notNull())
                {
                    LLMarketplaceValidator::getInstance()->validateMarketplaceListings(
                        version_folder_id,
                        [version_folder_id](bool result)
                    {
                        if (!result)
                        {
                            LLMarketplaceData::instance().activateListing(version_folder_id, false);
                        }
                    });
                }*/
                return FALSE;
            }

            //
            //--------------------------------------------------------------------------------
        }
    }
    else if (LLToolDragAndDrop::SOURCE_WORLD == source)
    {
        // Make sure the object exists. If we allowed dragging from
        // anonymous objects, it would be possible to bypass
        // permissions.
        object = gObjectList.findObject(inv_item->getParentUUID());
        if (!object)
        {
            LL_INFOS() << "Object not found for drop." << LL_ENDL;
            return FALSE;
        }

        // coming from a task. Need to figure out if the person can
        // move/copy this item.
        LLPermissions perm(inv_item->getPermissions());
        if ((perm.allowCopyBy(gAgent.getID(), gAgent.getGroupID())
            && perm.allowTransferTo(gAgent.getID())))
            // || gAgent.isGodlike())
        {
            accept = TRUE;
        }
        else if(object->permYouOwner())
        {
            // If the object cannot be copied, but the object the
            // inventory is owned by the agent, then the item can be
            // moved from the task to agent inventory.
            accept = TRUE;
        }

        // Don't allow placing an original item into Current Outfit or an outfit folder
        // because they must contain only links to wearable items.
        if (move_is_into_current_outfit || move_is_into_outfit)
        {
            accept = FALSE;
        }
        // Don't allow to move a single item to Favorites or Landmarks
        // if it is not a landmark or a link to a landmark.
        else if ((move_is_into_favorites || move_is_into_landmarks)
                 && !can_move_to_landmarks(inv_item))
        {
            accept = FALSE;
        }
        else if (move_is_into_marketplacelistings)
        {
            tooltip_msg = LLTrans::getString("TooltipOutboxNotInInventory");
            accept = FALSE;
        }

        if (accept && drop)
        {
            //todo: dnd from SOURCE_WORLD

            /*boost::shared_ptr<LLMoveInv> move_inv (new LLMoveInv());
            move_inv->mObjectID = inv_item->getParentUUID();
            std::pair<LLUUID, LLUUID> item_pair(folder_id, inv_item->getUUID());
            move_inv->mMoveList.push_back(item_pair);
            move_inv->mCallback = NULL;
            move_inv->mUserData = NULL;
            if(is_move)
            {
                warn_move_inventory(object, move_inv);
            }
            else
            {
                // store dad inventory item to select added one later. See EXT-4347
                set_dad_inventory_item(inv_item, folder_id);

                LLNotification::Params params("MoveInventoryFromObject");
                params.functor.function(boost::bind(move_task_inventory_callback, _1, _2, move_inv));
                LLNotifications::instance().forceResponse(params, 0);
            }*/
        }
    }
    else if(LLToolDragAndDrop::SOURCE_NOTECARD == source)
    {
        if (move_is_into_marketplacelistings)
        {
            tooltip_msg = LLTrans::getString("TooltipOutboxNotInInventory");
            accept = FALSE;
        }
        else if ((inv_item->getActualType() == LLAssetType::AT_SETTINGS) && !LLEnvironment::instance().isInventoryEnabled())
        {
            tooltip_msg = LLTrans::getString("NoEnvironmentSettings");
            accept = FALSE;
        }
        else
        {
            // Don't allow placing an original item from a notecard to Current Outfit or an outfit folder
            // because they must contain only links to wearable items.
            accept = !(move_is_into_current_outfit || move_is_into_outfit);
        }

        if (accept && drop)
        {
            copy_inventory_from_notecard(folder_id,  // Drop to the chosen destination folder
                                         LLToolDragAndDrop::getInstance()->getObjectID(),
                                         LLToolDragAndDrop::getInstance()->getSourceID(),
                                         inv_item);
        }
    }
    else if(LLToolDragAndDrop::SOURCE_LIBRARY == source)
    {
        LLViewerInventoryItem* item = (LLViewerInventoryItem*)inv_item;
        if(item && item->isFinished())
        {
            accept = TRUE;

            if (move_is_into_marketplacelistings)
            {
                tooltip_msg = LLTrans::getString("TooltipOutboxNotInInventory");
                accept = FALSE;
            }
            else if (move_is_into_current_outfit || move_is_into_outfit)
            {
                accept = can_move_to_outfit(inv_item, move_is_into_current_outfit);
            }
            // Don't allow to move a single item to Favorites or Landmarks
            // if it is not a landmark or a link to a landmark.
            else if (move_is_into_favorites || move_is_into_landmarks)
            {
                accept = can_move_to_landmarks(inv_item);
            }

            if (accept && drop)
            {
                // FAVORITES folder
                // (copy the item)
                if (move_is_into_favorites)
                {
                    copy_inventory_item(
                        gAgent.getID(),
                        inv_item->getPermissions().getOwner(),
                        inv_item->getUUID(),
                        folder_id,
                        std::string(),
                        LLPointer<LLInventoryCallback>(NULL));
                }
                // CURRENT OUTFIT or OUTFIT folder
                // (link the item)
                else if (move_is_into_current_outfit || move_is_into_outfit)
                {
                    if (move_is_into_current_outfit)
                    {
                        LLAppearanceMgr::instance().wearItemOnAvatar(inv_item->getUUID(), true, true);
                    }
                    else
                    {
                        LLPointer<LLInventoryCallback> cb = NULL;
                        link_inventory_object(folder_id, LLConstPointer<LLInventoryObject>(inv_item), cb);
                    }
                }
                else
                {
                    copy_inventory_item(
                        gAgent.getID(),
                        inv_item->getPermissions().getOwner(),
                        inv_item->getUUID(),
                        folder_id,
                        std::string(),
                        LLPointer<LLInventoryCallback>(NULL));
                }
            }
        }
    }
    else
    {
        LL_WARNS() << "unhandled drag source" << LL_ENDL;
    }
    return accept;
}

// copy of LLFolderBridge::dragCategoryIntoFolder
BOOL dragCategoryIntoFolder(LLUUID dest_id, LLInventoryCategory* inv_cat,
                            BOOL drop, std::string& tooltip_msg, BOOL is_link)
{
    BOOL user_confirm = TRUE;
    LLInventoryModel* model = &gInventory;
    LLViewerInventoryCategory * dest_cat = gInventory.getCategory(dest_id);
    if (!dest_cat)
    {
        return FALSE;
    }

    if (!inv_cat) return FALSE; // shouldn't happen, but in case item is incorrectly parented in which case inv_cat will be NULL

    if (!isAgentAvatarValid()) return FALSE;
    // cannot drag into library
    if((gInventory.getRootFolderID() != dest_id) && !model->isObjectDescendentOf(dest_id, gInventory.getRootFolderID()))
    {
        return FALSE;
    }

    const LLUUID &cat_id = inv_cat->getUUID();
    const LLUUID &current_outfit_id = model->findCategoryUUIDForType(LLFolderType::FT_CURRENT_OUTFIT);
    const LLUUID &marketplacelistings_id = model->findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS);
    //const LLUUID from_folder_uuid = inv_cat->getParentUUID();
    
    const BOOL move_is_into_current_outfit = (dest_id == current_outfit_id);
    const BOOL move_is_into_marketplacelistings = model->isObjectDescendentOf(dest_id, marketplacelistings_id);
    const BOOL move_is_from_marketplacelistings = model->isObjectDescendentOf(cat_id, marketplacelistings_id);

    // check to make sure source is agent inventory, and is represented there.
    LLToolDragAndDrop::ESource source = LLToolDragAndDrop::getInstance()->getSource();
    const BOOL is_agent_inventory = (model->getCategory(cat_id) != NULL)
        && (LLToolDragAndDrop::SOURCE_AGENT == source);

    BOOL accept = FALSE;

    if (is_agent_inventory)
    {
        const LLUUID &trash_id = model->findCategoryUUIDForType(LLFolderType::FT_TRASH);
        const LLUUID &landmarks_id = model->findCategoryUUIDForType(LLFolderType::FT_LANDMARK);
        const LLUUID &my_outifts_id = model->findCategoryUUIDForType(LLFolderType::FT_MY_OUTFITS);
        const LLUUID &lost_and_found_id = model->findCategoryUUIDForType(LLFolderType::FT_LOST_AND_FOUND);

        const BOOL move_is_into_trash = (dest_id == trash_id) || model->isObjectDescendentOf(dest_id, trash_id);
        const BOOL move_is_into_my_outfits = (dest_id == my_outifts_id) || model->isObjectDescendentOf(dest_id, my_outifts_id);
        const BOOL move_is_into_outfit = move_is_into_my_outfits || (dest_cat && dest_cat->getPreferredType()==LLFolderType::FT_OUTFIT);
        const BOOL move_is_into_current_outfit = (dest_cat && dest_cat->getPreferredType()==LLFolderType::FT_CURRENT_OUTFIT);
        const BOOL move_is_into_landmarks = (dest_id == landmarks_id) || model->isObjectDescendentOf(dest_id, landmarks_id);
        const BOOL move_is_into_lost_and_found = model->isObjectDescendentOf(dest_id, lost_and_found_id);

        //--------------------------------------------------------------------------------
        // Determine if folder can be moved.
        //

        BOOL is_movable = TRUE;

        if (is_movable && (marketplacelistings_id == cat_id))
        {
            is_movable = FALSE;
            tooltip_msg = LLTrans::getString("TooltipOutboxCannotMoveRoot");
        }
        if (is_movable && move_is_from_marketplacelistings)
            //&& LLMarketplaceData::instance().getActivationState(cat_id))
        {
            // If the incoming folder is listed and active (and is therefore either the listing or the version folder),
            // then moving is *not* allowed
            is_movable = FALSE;
            tooltip_msg = LLTrans::getString("TooltipOutboxDragActive");
        }
        if (is_movable && (dest_id == cat_id))
        {
            is_movable = FALSE;
            tooltip_msg = LLTrans::getString("TooltipDragOntoSelf");
        }
        if (is_movable && (model->isObjectDescendentOf(dest_id, cat_id)))
        {
            is_movable = FALSE;
            tooltip_msg = LLTrans::getString("TooltipDragOntoOwnChild");
        }
        if (is_movable && LLFolderType::lookupIsProtectedType(inv_cat->getPreferredType()))
        {
            is_movable = FALSE;
            // tooltip?
        }

        U32 max_items_to_wear = gSavedSettings.getU32("WearFolderLimit");
        if (is_movable && move_is_into_outfit)
        {
            if (dest_id == my_outifts_id)
            {
                if (source != LLToolDragAndDrop::SOURCE_AGENT || move_is_from_marketplacelistings)
                {
                    tooltip_msg = LLTrans::getString("TooltipOutfitNotInInventory");
                    is_movable = false;
                }
                else if (can_move_to_my_outfits(model, inv_cat, max_items_to_wear))
                {
                    is_movable = true;
                }
                else
                {
                    tooltip_msg = LLTrans::getString("TooltipCantCreateOutfit");
                    is_movable = false;
                }
            }
            else if(dest_cat && dest_cat->getPreferredType() == LLFolderType::FT_NONE)
            {
                is_movable = ((inv_cat->getPreferredType() == LLFolderType::FT_NONE) || (inv_cat->getPreferredType() == LLFolderType::FT_OUTFIT));
            }
            else
            {
                is_movable = false;
            }
        }
        if(is_movable && move_is_into_current_outfit && is_link)
        {
            is_movable = FALSE;
        }
        if (is_movable && move_is_into_lost_and_found)
        {
            is_movable = FALSE;
        }
        if (is_movable && (dest_id == model->findCategoryUUIDForType(LLFolderType::FT_FAVORITE)))
        {
            is_movable = FALSE;
            // tooltip?
        }
        if (is_movable && (dest_cat->getPreferredType() == LLFolderType::FT_MARKETPLACE_STOCK))
        {
            // One cannot move a folder into a stock folder
            is_movable = FALSE;
            // tooltip?
        }
        
        LLInventoryModel::cat_array_t descendent_categories;
        LLInventoryModel::item_array_t descendent_items;
        if (is_movable)
        {
            model->collectDescendents(cat_id, descendent_categories, descendent_items, FALSE);
            for (S32 i=0; i < descendent_categories.size(); ++i)
            {
                LLInventoryCategory* category = descendent_categories[i];
                if(LLFolderType::lookupIsProtectedType(category->getPreferredType()))
                {
                    // Can't move "special folders" (e.g. Textures Folder).
                    is_movable = FALSE;
                    break;
                }
            }
        }
        if (is_movable
            && move_is_into_current_outfit
            && descendent_items.size() > max_items_to_wear)
        {
            LLInventoryModel::cat_array_t cats;
            LLInventoryModel::item_array_t items;
            LLFindWearablesEx not_worn(/*is_worn=*/ false, /*include_body_parts=*/ false);
            gInventory.collectDescendentsIf(cat_id,
                cats,
                items,
                LLInventoryModel::EXCLUDE_TRASH,
                not_worn);

            if (items.size() > max_items_to_wear)
            {
                // Can't move 'large' folders into current outfit: MAINT-4086
                is_movable = FALSE;
                LLStringUtil::format_map_t args;
                args["AMOUNT"] = llformat("%d", max_items_to_wear);
                tooltip_msg = LLTrans::getString("TooltipTooManyWearables",args);
            }
        }
        if (is_movable && move_is_into_trash)
        {
            for (S32 i=0; i < descendent_items.size(); ++i)
            {
                LLInventoryItem* item = descendent_items[i];
                if (get_is_item_worn(item->getUUID()))
                {
                    is_movable = FALSE;
                    break; // It's generally movable, but not into the trash.
                }
            }
        }
        if (is_movable && move_is_into_landmarks)
        {
            for (S32 i=0; i < descendent_items.size(); ++i)
            {
                LLViewerInventoryItem* item = descendent_items[i];

                // Don't move anything except landmarks and categories into Landmarks folder.
                // We use getType() instead of getActua;Type() to allow links to landmarks and folders.
                if (LLAssetType::AT_LANDMARK != item->getType() && LLAssetType::AT_CATEGORY != item->getType())
                {
                    is_movable = FALSE;
                    break; // It's generally movable, but not into Landmarks.
                }
            }
        }
        
        if (is_movable && move_is_into_marketplacelistings)
        {
            const LLViewerInventoryCategory * master_folder = model->getFirstDescendantOf(marketplacelistings_id, dest_id);
            LLViewerInventoryCategory * dest_folder = dest_cat;
            S32 bundle_size = (drop ? 1 : LLToolDragAndDrop::instance().getCargoCount());
            is_movable = can_move_folder_to_marketplace(master_folder, dest_folder, inv_cat, tooltip_msg, bundle_size);
        }

        //
        //--------------------------------------------------------------------------------

        accept = is_movable;

        if (accept && drop)
        {
            // Dropping in or out of marketplace needs (sometimes) confirmation
            if (user_confirm && (move_is_from_marketplacelistings || move_is_into_marketplacelistings))
            {
                //disable dropping in or out of marketplace for now
                return FALSE;
            }
            // Look for any gestures and deactivate them
            if (move_is_into_trash)
            {
                for (S32 i=0; i < descendent_items.size(); i++)
                {
                    LLInventoryItem* item = descendent_items[i];
                    if (item->getType() == LLAssetType::AT_GESTURE
                        && LLGestureMgr::instance().isGestureActive(item->getUUID()))
                    {
                        LLGestureMgr::instance().deactivateGesture(item->getUUID());
                    }
                }
            }

            if (dest_id == my_outifts_id)
            {
                // Category can contains objects,
                // create a new folder and populate it with links to original objects
                dropToMyOutfits(inv_cat);
            }
            // if target is current outfit folder we use link
            else if (move_is_into_current_outfit &&
                (inv_cat->getPreferredType() == LLFolderType::FT_NONE ||
                inv_cat->getPreferredType() == LLFolderType::FT_OUTFIT))
            {
                // traverse category and add all contents to currently worn.
                BOOL append = true;
                LLAppearanceMgr::instance().wearInventoryCategory(inv_cat, false, append);
            }
            else if (move_is_into_marketplacelistings)
            {
                //move_folder_to_marketplacelistings(inv_cat, dest_id);
            }
            else
            {
                if (model->isObjectDescendentOf(cat_id, model->findCategoryUUIDForType(LLFolderType::FT_INBOX)))
                {
                    set_dad_inbox_object(cat_id);
                }

                // Reparent the folder and restamp children if it's moving
                // into trash.
                gInventory.changeCategoryParent(
                    (LLViewerInventoryCategory*)inv_cat,
                    dest_id,
                    move_is_into_trash);
            }
            if (move_is_from_marketplacelistings)
            {
                //disable dropping in or out of marketplace for now
                return FALSE;
                
                // If we are moving a folder at the listing folder level (i.e. its parent is the marketplace listings folder)
                /*if (from_folder_uuid == marketplacelistings_id)
                {
                    // Clear the folder from the marketplace in case it is a listing folder
                    if (LLMarketplaceData::instance().isListed(cat_id))
                    {
                        LLMarketplaceData::instance().clearListing(cat_id);
                    }
                }
                else
                {
                    // If we move from within an active (listed) listing, checks that it's still valid, if not, unlist
                    LLUUID version_folder_id = LLMarketplaceData::instance().getActiveFolder(from_folder_uuid);
                    if (version_folder_id.notNull())
                    {
                        LLMarketplaceValidator::getInstance()->validateMarketplaceListings(
                            version_folder_id,
                            [version_folder_id](bool result)
                        {
                            if (!result)
                            {
                                LLMarketplaceData::instance().activateListing(version_folder_id, false);
                            }
                        }
                        );
                    }
                    // In all cases, update the listing we moved from so suffix are updated
                    update_marketplace_category(from_folder_uuid);
                }*/
            }
        }
    }
    else if (LLToolDragAndDrop::SOURCE_WORLD == source)
    {
        if (move_is_into_marketplacelistings)
        {
            tooltip_msg = LLTrans::getString("TooltipOutboxNotInInventory");
            accept = FALSE;
        }
        else
        {
            //todo: dnd from SOURCE_WORLD
            accept = FALSE;
            //accept = move_inv_category_world_to_agent(cat_id, mUUID, drop, NULL, NULL, filter);
        }
    }
    else if (LLToolDragAndDrop::SOURCE_LIBRARY == source)
    {
        if (move_is_into_marketplacelistings)
        {
            tooltip_msg = LLTrans::getString("TooltipOutboxNotInInventory");
            accept = FALSE;
        }
        else
        {
            // Accept folders that contain complete outfits.
            accept = move_is_into_current_outfit && LLAppearanceMgr::instance().getCanMakeFolderIntoOutfit(cat_id);
        }

        if (accept && drop)
        {
            LLAppearanceMgr::instance().wearInventoryCategory(inv_cat, true, false);
        }
    }

    return accept;
}

void outfitFolderCreatedCallback(LLUUID cat_source_id, LLUUID cat_dest_id)
{
    LLInventoryModel::cat_array_t* categories;
    LLInventoryModel::item_array_t* items;
    gInventory.getDirectDescendentsOf(cat_source_id, categories, items);

    LLInventoryObject::const_object_list_t link_array;


    LLInventoryModel::item_array_t::iterator iter = items->begin();
    LLInventoryModel::item_array_t::iterator end = items->end();
    while (iter!=end)
    {
        const LLViewerInventoryItem* item = (*iter);
        // By this point everything is supposed to be filtered,
        // but there was a delay to create folder so something could have changed
        LLInventoryType::EType inv_type = item->getInventoryType();
        if ((inv_type == LLInventoryType::IT_WEARABLE) ||
            (inv_type == LLInventoryType::IT_GESTURE) ||
            (inv_type == LLInventoryType::IT_ATTACHMENT) ||
            (inv_type == LLInventoryType::IT_OBJECT) ||
            (inv_type == LLInventoryType::IT_SNAPSHOT) ||
            (inv_type == LLInventoryType::IT_TEXTURE))
        {
            link_array.push_back(LLConstPointer<LLInventoryObject>(item));
        }
        iter++;
    }

    if (!link_array.empty())
    {
        LLPointer<LLInventoryCallback> cb = NULL;
        link_inventory_array(cat_dest_id, link_array, cb);
    }
}

void dropToMyOutfits(LLInventoryCategory* inv_cat)
{
    // make a folder in the My Outfits directory.
    const LLUUID dest_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MY_OUTFITS);

    // Note: creation will take time, so passing folder id to callback is slightly unreliable,
    // but so is collecting and passing descendants' ids
    inventory_func_type func = boost::bind(&outfitFolderCreatedCallback, inv_cat->getUUID(), _1);
    gInventory.createNewCategory(dest_id, LLFolderType::FT_OUTFIT, inv_cat->getName(), func, inv_cat->getThumbnailUUID());
}