summaryrefslogtreecommitdiff
path: root/indra/newview/llinventorypanel.cpp
blob: 82f791a1713dfffad6e473f15140ec3a968a87c5 (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
/* 
 * @file llinventorypanel.cpp
 * @brief Implementation of the inventory panel and associated stuff.
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"
#include "llinventorypanel.h"

#include <utility> // for std::pair<>

#include "llagent.h"
#include "llagentwearables.h"
#include "llappearancemgr.h"
#include "llavataractions.h"
#include "llclipboard.h"
#include "llfloaterreg.h"
#include "llfloatersidepanelcontainer.h"
#include "llfolderview.h"
#include "llfolderviewitem.h"
#include "llfloaterimcontainer.h"
#include "llimview.h"
#include "llinspecttexture.h"
#include "llinventorybridge.h"
#include "llinventoryfunctions.h"
#include "llinventorymodelbackgroundfetch.h"
#include "llnotificationsutil.h"
#include "llpanelmaininventory.h"
#include "llpreview.h"
#include "llsidepanelinventory.h"
#include "llstartup.h"
#include "lltrans.h"
#include "llviewerassettype.h"
#include "llviewerattachmenu.h"
#include "llviewerfoldertype.h"
#include "llvoavatarself.h"

class LLInventoryRecentItemsPanel;
class LLAssetFilteredInventoryPanel;

static LLDefaultChildRegistry::Register<LLInventoryPanel> r("inventory_panel");
static LLDefaultChildRegistry::Register<LLInventoryRecentItemsPanel> t_recent_inventory_panel("recent_inventory_panel");
static LLDefaultChildRegistry::Register<LLAssetFilteredInventoryPanel> t_asset_filtered_inv_panel("asset_filtered_inv_panel");

const std::string LLInventoryPanel::DEFAULT_SORT_ORDER = std::string("InventorySortOrder");
const std::string LLInventoryPanel::RECENTITEMS_SORT_ORDER = std::string("RecentItemsSortOrder");
const std::string LLInventoryPanel::INHERIT_SORT_ORDER = std::string("");
static const LLInventoryFolderViewModelBuilder INVENTORY_BRIDGE_BUILDER;

// statics 
bool LLInventoryPanel::sColorSetInitialized = false;
LLUIColor LLInventoryPanel::sDefaultColor;
LLUIColor LLInventoryPanel::sDefaultHighlightColor;
LLUIColor LLInventoryPanel::sLibraryColor;
LLUIColor LLInventoryPanel::sLinkColor;

const LLColor4U DEFAULT_WHITE(255, 255, 255);

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class LLInventoryPanelObserver
//
// Bridge to support knowing when the inventory has changed.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

class LLInventoryPanelObserver : public LLInventoryObserver
{
public:
	LLInventoryPanelObserver(LLInventoryPanel* ip) : mIP(ip) {}
	virtual ~LLInventoryPanelObserver() {}
	virtual void changed(U32 mask) 
	{
		mIP->modelChanged(mask);
	}
protected:
	LLInventoryPanel* mIP;
};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class LLInvPanelComplObserver
//
// Calls specified callback when all specified items become complete.
//
// Usage:
// observer = new LLInvPanelComplObserver(boost::bind(onComplete));
// inventory->addObserver(observer);
// observer->reset(); // (optional)
// observer->watchItem(incomplete_item1_id);
// observer->watchItem(incomplete_item2_id);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

class LLInvPanelComplObserver : public LLInventoryCompletionObserver
{
public:
	typedef boost::function<void()> callback_t;

	LLInvPanelComplObserver(callback_t cb)
	:	mCallback(cb)
	{
	}

	void reset();

private:
	/*virtual*/ void done();

	/// Called when all the items are complete.
	callback_t	mCallback;
};

void LLInvPanelComplObserver::reset()
{
	mIncomplete.clear();
	mComplete.clear();
}

void LLInvPanelComplObserver::done()
{
	mCallback();
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class LLInventoryPanel
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

LLInventoryPanel::LLInventoryPanel(const LLInventoryPanel::Params& p) :	
	LLPanel(p),
	mInventoryObserver(NULL),
	mCompletionObserver(NULL),
	mScroller(NULL),
	mSortOrderSetting(p.sort_order_setting),
	mInventory(p.inventory), //inventory("", &gInventory)
	mAcceptsDragAndDrop(p.accepts_drag_and_drop),
	mAllowMultiSelect(p.allow_multi_select),
	mAllowDrag(p.allow_drag),
	mShowItemLinkOverlays(p.show_item_link_overlays),
	mShowEmptyMessage(p.show_empty_message),
	mSuppressFolderMenu(p.suppress_folder_menu),
	mSuppressOpenItemAction(false),
	mBuildViewsOnInit(p.preinitialize_views),
	mViewsInitialized(VIEWS_UNINITIALIZED),
	mInvFVBridgeBuilder(NULL),
	mInventoryViewModel(p.name),
	mGroupedItemBridge(new LLFolderViewGroupedItemBridge),
	mFocusSelection(false)
{
	mInvFVBridgeBuilder = &INVENTORY_BRIDGE_BUILDER;

	if (!sColorSetInitialized)
	{
		sDefaultColor = LLUIColorTable::instance().getColor("InventoryItemColor", DEFAULT_WHITE);
		sDefaultHighlightColor = LLUIColorTable::instance().getColor("MenuItemHighlightFgColor", DEFAULT_WHITE);
		sLibraryColor = LLUIColorTable::instance().getColor("InventoryItemLibraryColor", DEFAULT_WHITE);
		sLinkColor = LLUIColorTable::instance().getColor("InventoryItemLinkColor", DEFAULT_WHITE);
		sColorSetInitialized = true;
	}
	
	// context menu callbacks
	mCommitCallbackRegistrar.add("Inventory.DoToSelected", boost::bind(&LLInventoryPanel::doToSelected, this, _2));
	mCommitCallbackRegistrar.add("Inventory.EmptyTrash", boost::bind(&LLInventoryModel::emptyFolderType, &gInventory, "ConfirmEmptyTrash", LLFolderType::FT_TRASH));
	mCommitCallbackRegistrar.add("Inventory.EmptyLostAndFound", boost::bind(&LLInventoryModel::emptyFolderType, &gInventory, "ConfirmEmptyLostAndFound", LLFolderType::FT_LOST_AND_FOUND));
	mCommitCallbackRegistrar.add("Inventory.DoCreate", boost::bind(&LLInventoryPanel::doCreate, this, _2));
	mCommitCallbackRegistrar.add("Inventory.AttachObject", boost::bind(&LLInventoryPanel::attachObject, this, _2));
	mCommitCallbackRegistrar.add("Inventory.BeginIMSession", boost::bind(&LLInventoryPanel::beginIMSession, this));
	mCommitCallbackRegistrar.add("Inventory.Share",  boost::bind(&LLAvatarActions::shareWithAvatars, this));
	mCommitCallbackRegistrar.add("Inventory.FileUploadLocation", boost::bind(&LLInventoryPanel::fileUploadLocation, this, _2));
    mCommitCallbackRegistrar.add("Inventory.OpenNewFolderWindow", boost::bind(&LLInventoryPanel::openSingleViewInventory, this, LLUUID()));
}

LLFolderView * LLInventoryPanel::createFolderRoot(LLUUID root_id )
{
    LLFolderView::Params p(mParams.folder_view);
    p.name = getName();
    p.title = getLabel();
    p.rect = LLRect(0, 0, getRect().getWidth(), 0);
    p.parent_panel = this;
    p.tool_tip = p.name;
    p.listener = mInvFVBridgeBuilder->createBridge(	LLAssetType::AT_CATEGORY,
																	LLAssetType::AT_CATEGORY,
																	LLInventoryType::IT_CATEGORY,
																	this,
																	&mInventoryViewModel,
																	NULL,
																	root_id);
    p.view_model = &mInventoryViewModel;
	p.grouped_item_model = mGroupedItemBridge;
    p.use_label_suffix = mParams.use_label_suffix;
    p.allow_multiselect = mAllowMultiSelect;
    p.allow_drag = mAllowDrag;
    p.show_empty_message = mShowEmptyMessage;
    p.suppress_folder_menu = mSuppressFolderMenu;
    p.show_item_link_overlays = mShowItemLinkOverlays;
    p.root = NULL;
    p.allow_drop = mParams.allow_drop_on_root;
    p.options_menu = "menu_inventory.xml";

	LLFolderView* fv = LLUICtrlFactory::create<LLFolderView>(p);
	fv->setCallbackRegistrar(&mCommitCallbackRegistrar);
	fv->setEnableRegistrar(&mEnableCallbackRegistrar);

	return fv;
}

void LLInventoryPanel::clearFolderRoot()
{
	gIdleCallbacks.deleteFunction(idle, this);
    gIdleCallbacks.deleteFunction(onIdle, this);
    
    if (mInventoryObserver)
    {
        mInventory->removeObserver(mInventoryObserver);
        delete mInventoryObserver;
        mInventoryObserver = NULL;
    }
    if (mCompletionObserver)
    {
        mInventory->removeObserver(mCompletionObserver);
        delete mCompletionObserver;
        mCompletionObserver = NULL;
    }
    
    if (mScroller)
    {
        removeChild(mScroller);
        delete mScroller;
        mScroller = NULL;
    }
}

void LLInventoryPanel::initFromParams(const LLInventoryPanel::Params& params)
{
	// save off copy of params
	mParams = params;
	// Clear up the root view
	// Note: This needs to be done *before* we build the new folder view 
	LLUUID root_id = getRootFolderID();
	if (mFolderRoot.get())
	{
		removeItemID(root_id);
		mFolderRoot.get()->destroyView();
	}

	mCommitCallbackRegistrar.pushScope(); // registered as a widget; need to push callback scope ourselves
	{
		// Determine the root folder in case specified, and
		// build the views starting with that folder.
        LLFolderView* folder_view = createFolderRoot(root_id);
		mFolderRoot = folder_view->getHandle();
	
		addItemID(root_id, mFolderRoot.get());
	}
	mCommitCallbackRegistrar.popScope();
	mFolderRoot.get()->setCallbackRegistrar(&mCommitCallbackRegistrar);
	mFolderRoot.get()->setEnableRegistrar(&mEnableCallbackRegistrar);
	
	// Scroller
		LLRect scroller_view_rect = getRect();
		scroller_view_rect.translate(-scroller_view_rect.mLeft, -scroller_view_rect.mBottom);
	LLScrollContainer::Params scroller_params(mParams.scroll());
		scroller_params.rect(scroller_view_rect);
		mScroller = LLUICtrlFactory::create<LLFolderViewScrollContainer>(scroller_params);
		addChild(mScroller);
		mScroller->addChild(mFolderRoot.get());
		mFolderRoot.get()->setScrollContainer(mScroller);
		mFolderRoot.get()->setFollowsAll();
		mFolderRoot.get()->addChild(mFolderRoot.get()->mStatusTextBox);

	// Set up the callbacks from the inventory we're viewing, and then build everything.
	mInventoryObserver = new LLInventoryPanelObserver(this);
	mInventory->addObserver(mInventoryObserver);

	mCompletionObserver = new LLInvPanelComplObserver(boost::bind(&LLInventoryPanel::onItemsCompletion, this));
	mInventory->addObserver(mCompletionObserver);

    if (mBuildViewsOnInit && mViewsInitialized == VIEWS_UNINITIALIZED)
    {
        // Build view of inventory if we need default full hierarchy and inventory is ready, otherwise do in onIdle.
        // Initializing views takes a while so always do it onIdle if viewer already loaded.
        if (mInventory->isInventoryUsable()            
            && LLStartUp::getStartupState() <= STATE_WEARABLES_WAIT)
        {
            // Usually this happens on login, so we have less time constraits, but too long and we can cause a disconnect
            const F64 max_time = 20.f;
            initializeViews(max_time);
        }
        else
        {
            mViewsInitialized = VIEWS_INITIALIZING;
            gIdleCallbacks.addFunction(onIdle, (void*)this);
        }
    }

	if (mSortOrderSetting != INHERIT_SORT_ORDER)
	{
		setSortOrder(gSavedSettings.getU32(mSortOrderSetting));
	}
	else
	{
		setSortOrder(gSavedSettings.getU32(DEFAULT_SORT_ORDER));
	}

	// hide inbox
	if (!gSavedSettings.getBOOL("InventoryOutboxMakeVisible"))
	{
		getFilter().setFilterCategoryTypes(getFilter().getFilterCategoryTypes() & ~(1ULL << LLFolderType::FT_INBOX));
	}
    // hide marketplace listing box, unless we are a marketplace panel
	if (!gSavedSettings.getBOOL("InventoryOutboxMakeVisible") && !mParams.use_marketplace_folders)
	{
		getFilter().setFilterCategoryTypes(getFilter().getFilterCategoryTypes() & ~(1ULL << LLFolderType::FT_MARKETPLACE_LISTINGS));
    }
    
	// set the filter for the empty folder if the debug setting is on
	if (gSavedSettings.getBOOL("DebugHideEmptySystemFolders"))
	{
		getFilter().setFilterEmptySystemFolders();
	}
	
	// keep track of the clipboard state so that we avoid filtering too much
	mClipboardState = LLClipboard::instance().getGeneration();
	
	// Initialize base class params.
	LLPanel::initFromParams(mParams);
}

LLInventoryPanel::~LLInventoryPanel()
{
	U32 sort_order = getFolderViewModel()->getSorter().getSortOrder();
    if (mSortOrderSetting != INHERIT_SORT_ORDER)
    {
        gSavedSettings.setU32(mSortOrderSetting, sort_order);
    }
    
    clearFolderRoot();
}

/*virtual*/
void LLInventoryPanel::onVisibilityChange(BOOL new_visibility)
{
    if (new_visibility && mViewsInitialized == VIEWS_UNINITIALIZED)
    {
        mViewsInitialized = VIEWS_INITIALIZING;
        gIdleCallbacks.addFunction(onIdle, (void*)this);
    }
    LLPanel::onVisibilityChange(new_visibility);
}

void LLInventoryPanel::draw()
{
	// Select the desired item (in case it wasn't loaded when the selection was requested)
	updateSelection();
	
	LLPanel::draw();
}

const LLInventoryFilter& LLInventoryPanel::getFilter() const
{
	return getFolderViewModel()->getFilter();
}

LLInventoryFilter& LLInventoryPanel::getFilter()
{
	return getFolderViewModel()->getFilter();
}

void LLInventoryPanel::setFilterTypes(U64 types, LLInventoryFilter::EFilterType filter_type)
{
	if (filter_type == LLInventoryFilter::FILTERTYPE_OBJECT)
	{
		getFilter().setFilterObjectTypes(types);
	}
	if (filter_type == LLInventoryFilter::FILTERTYPE_CATEGORY)
		getFilter().setFilterCategoryTypes(types);
}

void LLInventoryPanel::setFilterWorn()
{
    getFilter().setFilterWorn();
}

U32 LLInventoryPanel::getFilterObjectTypes() const 
{ 
	return getFilter().getFilterObjectTypes();
}

U32 LLInventoryPanel::getFilterPermMask() const 
{ 
	return getFilter().getFilterPermissions();
}


void LLInventoryPanel::setFilterPermMask(PermissionMask filter_perm_mask)
{
	getFilter().setFilterPermissions(filter_perm_mask);
}

void LLInventoryPanel::setFilterWearableTypes(U64 types)
{
	getFilter().setFilterWearableTypes(types);
}

void LLInventoryPanel::setFilterSettingsTypes(U64 filter)
{
    getFilter().setFilterSettingsTypes(filter);
}

void LLInventoryPanel::setFilterSubString(const std::string& string)
{
	getFilter().setFilterSubString(string);
}

const std::string LLInventoryPanel::getFilterSubString() 
{ 
	return getFilter().getFilterSubString();
}

void LLInventoryPanel::setSortOrder(U32 order)
{
    LLInventorySort sorter(order);
	if (order != getFolderViewModel()->getSorter().getSortOrder())
	{
		getFolderViewModel()->setSorter(sorter);
		mFolderRoot.get()->arrangeAll();
		// try to keep selection onscreen, even if it wasn't to start with
		mFolderRoot.get()->scrollToShowSelection();
	}
}

U32 LLInventoryPanel::getSortOrder() const 
{ 
	return getFolderViewModel()->getSorter().getSortOrder();
}

void LLInventoryPanel::setSinceLogoff(BOOL sl)
{
	getFilter().setDateRangeLastLogoff(sl);
}

void LLInventoryPanel::setHoursAgo(U32 hours)
{
	getFilter().setHoursAgo(hours);
}

void LLInventoryPanel::setDateSearchDirection(U32 direction)
{
	getFilter().setDateSearchDirection(direction);
}

void LLInventoryPanel::setFilterLinks(U64 filter_links)
{
	getFilter().setFilterLinks(filter_links);
}

void LLInventoryPanel::setSearchType(LLInventoryFilter::ESearchType type)
{
	getFilter().setSearchType(type);
}

LLInventoryFilter::ESearchType LLInventoryPanel::getSearchType()
{
	return getFilter().getSearchType();
}

void LLInventoryPanel::setShowFolderState(LLInventoryFilter::EFolderShow show)
{
	getFilter().setShowFolderState(show);
}

LLInventoryFilter::EFolderShow LLInventoryPanel::getShowFolderState()
{
	return getFilter().getShowFolderState();
}

void LLInventoryPanel::itemChanged(const LLUUID& item_id, U32 mask, const LLInventoryObject* model_item)
{
	LLFolderViewItem* view_item = getItemByID(item_id);
	LLFolderViewModelItemInventory* viewmodel_item = 
		static_cast<LLFolderViewModelItemInventory*>(view_item ? view_item->getViewModelItem() : NULL);

	// LLFolderViewFolder is derived from LLFolderViewItem so dynamic_cast from item
	// to folder is the fast way to get a folder without searching through folders tree.
	LLFolderViewFolder* view_folder = NULL;

	// Check requires as this item might have already been deleted
	// as a child of its deleted parent.
	if (model_item && view_item)
	{
		view_folder = dynamic_cast<LLFolderViewFolder*>(view_item);
	}

    // if folder is not fully initialized (likely due to delayed load on idle)
    // and we are not rebuilding, try updating children
    if (view_folder
        && !view_folder->areChildrenInited()
        && ( (mask & LLInventoryObserver::REBUILD) == 0))
    {
        LLInventoryObject const* objectp = mInventory->getObject(item_id);
        if (objectp)
        {
            view_item = buildNewViews(item_id, objectp, view_item, BUILD_ONE_FOLDER);
        }
    }

	//////////////////////////////
	// LABEL Operation
	// Empty out the display name for relabel.
	if (mask & LLInventoryObserver::LABEL)
	{
		if (view_item)
		{
			// Request refresh on this item (also flags for filtering)
			LLInvFVBridge* bridge = (LLInvFVBridge*)view_item->getViewModelItem();
			if(bridge)
			{
				// Clear the display name first, so it gets properly re-built during refresh()
				bridge->clearDisplayName();

				view_item->refresh();
			}
			LLFolderViewFolder* parent = view_item->getParentFolder();
			if(parent)
			{
				parent->getViewModelItem()->dirtyDescendantsFilter();
			}
		}
	}

	//////////////////////////////
	// REBUILD Operation
	// Destroy and regenerate the UI.
	if (mask & LLInventoryObserver::REBUILD)
	{
		if (model_item && view_item && viewmodel_item)
		{
			const LLUUID& idp = viewmodel_item->getUUID();
			view_item->destroyView();
			removeItemID(idp);
		}

        LLInventoryObject const* objectp = mInventory->getObject(item_id);
        if (objectp)
        {
            // providing NULL directly avoids unnessesary getItemByID calls
            view_item = buildNewViews(item_id, objectp, NULL, BUILD_ONE_FOLDER);
        }
        else
        {
            view_item = NULL;
        }

		viewmodel_item = 
			static_cast<LLFolderViewModelItemInventory*>(view_item ? view_item->getViewModelItem() : NULL);
		view_folder = dynamic_cast<LLFolderViewFolder *>(view_item);
	}

	//////////////////////////////
	// INTERNAL Operation
	// This could be anything.  For now, just refresh the item.
	if (mask & LLInventoryObserver::INTERNAL)
	{
		if (view_item)
		{
			view_item->refresh();
		}
	}

	//////////////////////////////
	// SORT Operation
	// Sort the folder.
	if (mask & LLInventoryObserver::SORT)
	{
		if (view_folder)
		{
			view_folder->getViewModelItem()->requestSort();
		}
	}

	// We don't typically care which of these masks the item is actually flagged with, since the masks
	// may not be accurate (e.g. in the main inventory panel, I move an item from My Inventory into
	// Landmarks; this is a STRUCTURE change for that panel but is an ADD change for the Landmarks
	// panel).  What's relevant is that the item and UI are probably out of sync and thus need to be
	// resynchronized.
	if (mask & (LLInventoryObserver::STRUCTURE |
				LLInventoryObserver::ADD |
				LLInventoryObserver::REMOVE))
	{
		//////////////////////////////
		// ADD Operation
		// Item exists in memory but a UI element hasn't been created for it.
		if (model_item && !view_item)
		{
			// Add the UI element for this item.
            LLInventoryObject const* objectp = mInventory->getObject(item_id);
            if (objectp)
            {
                // providing NULL directly avoids unnessesary getItemByID calls
                buildNewViews(item_id, objectp, NULL, BUILD_ONE_FOLDER);
            }

			// Select any newly created object that has the auto rename at top of folder root set.
			if(mFolderRoot.get()->getRoot()->needsAutoRename())
			{
				setSelection(item_id, FALSE);
			}
			updateFolderLabel(model_item->getParentUUID());
		}

		//////////////////////////////
		// STRUCTURE Operation
		// This item already exists in both memory and UI.  It was probably reparented.
		else if (model_item && view_item)
		{
			LLFolderViewFolder* old_parent = view_item->getParentFolder();
			// Don't process the item if it is the root
			if (old_parent)
			{
				LLFolderViewModelItemInventory* viewmodel_folder = static_cast<LLFolderViewModelItemInventory*>(old_parent->getViewModelItem());
				LLFolderViewFolder* new_parent =   (LLFolderViewFolder*)getItemByID(model_item->getParentUUID());
				// Item has been moved.
				if (old_parent != new_parent)
				{
					if (new_parent != NULL)
					{
						// Item is to be moved and we found its new parent in the panel's directory, so move the item's UI.
						view_item->addToFolder(new_parent);
						addItemID(viewmodel_item->getUUID(), view_item);
						if (mInventory)
						{
							const LLUUID trash_id = mInventory->findCategoryUUIDForType(LLFolderType::FT_TRASH);
							if (trash_id != model_item->getParentUUID() && (mask & LLInventoryObserver::INTERNAL) && new_parent->isOpen())
							{
								setSelection(item_id, FALSE);
							}
						}
						updateFolderLabel(model_item->getParentUUID());
					}
					else 
					{
						// Remove the item ID before destroying the view because the view-model-item gets
						// destroyed when the view is destroyed
						removeItemID(viewmodel_item->getUUID());

						// Item is to be moved outside the panel's directory (e.g. moved to trash for a panel that 
						// doesn't include trash).  Just remove the item's UI.
						view_item->destroyView();
					}
					if(viewmodel_folder)
					{
						updateFolderLabel(viewmodel_folder->getUUID());
					}
					old_parent->getViewModelItem()->dirtyDescendantsFilter();
				}
			}
		}

		//////////////////////////////
		// REMOVE Operation
		// This item has been removed from memory, but its associated UI element still exists.
		else if (!model_item && view_item && viewmodel_item)
		{
			// Remove the item's UI.
			LLFolderViewFolder* parent = view_item->getParentFolder();
			removeItemID(viewmodel_item->getUUID());
			view_item->destroyView();
			if(parent)
			{
				parent->getViewModelItem()->dirtyDescendantsFilter();
				LLFolderViewModelItemInventory* viewmodel_folder = static_cast<LLFolderViewModelItemInventory*>(parent->getViewModelItem());
				if(viewmodel_folder)
				{
					updateFolderLabel(viewmodel_folder->getUUID());
				}
			}
		}
	}
}

// Called when something changed in the global model (new item, item coming through the wire, rename, move, etc...) (CHUI-849)
void LLInventoryPanel::modelChanged(U32 mask)
{
    LL_PROFILE_ZONE_SCOPED;

	if (mViewsInitialized != VIEWS_INITIALIZED) return;
	
	const LLInventoryModel* model = getModel();
	if (!model) return;

	const LLInventoryModel::changed_items_t& changed_items = model->getChangedIDs();
	if (changed_items.empty()) return;

	for (LLInventoryModel::changed_items_t::const_iterator items_iter = changed_items.begin();
		 items_iter != changed_items.end();
		 ++items_iter)
	{
		const LLUUID& item_id = (*items_iter);
		const LLInventoryObject* model_item = model->getObject(item_id);
		itemChanged(item_id, mask, model_item);
	}
}

LLUUID LLInventoryPanel::getRootFolderID()
{
    LLUUID root_id;
	if (mFolderRoot.get() && mFolderRoot.get()->getViewModelItem())
	{
		root_id = static_cast<LLFolderViewModelItemInventory*>(mFolderRoot.get()->getViewModelItem())->getUUID();
	}
	else
	{
		if (mParams.start_folder.id.isChosen())
		{
			root_id = mParams.start_folder.id;
		}
		else
		{
			const LLFolderType::EType preferred_type = mParams.start_folder.type.isChosen() 
				? mParams.start_folder.type
				: LLViewerFolderType::lookupTypeFromNewCategoryName(mParams.start_folder.name);

			if ("LIBRARY" == mParams.start_folder.name())
			{
				root_id = gInventory.getLibraryRootFolderID();
			}
			else if (preferred_type != LLFolderType::FT_NONE)
			{
                LLStringExplicit label(mParams.start_folder.name());
                setLabel(label);
                
				root_id = gInventory.findCategoryUUIDForType(preferred_type, false);
				if (root_id.isNull())
				{
					LL_WARNS() << "Could not find folder of type " << preferred_type << LL_ENDL;
					root_id.generateNewID();
				}
			}
		}
	}
    return root_id;
}

// static
void LLInventoryPanel::onIdle(void *userdata)
{
	if (!gInventory.isInventoryUsable())
		return;

	LLInventoryPanel *self = (LLInventoryPanel*)userdata;
	if (self->mViewsInitialized <= VIEWS_INITIALIZING)
	{
		const F64 max_time = 0.001f; // 1 ms, in this case we need only root folders
		self->initializeViews(max_time); // Shedules LLInventoryPanel::idle()
	}
	if (self->mViewsInitialized >= VIEWS_BUILDING)
	{
		gIdleCallbacks.deleteFunction(onIdle, (void*)self);
	}
}

struct DirtyFilterFunctor : public LLFolderViewFunctor
{
	/*virtual*/ void doFolder(LLFolderViewFolder* folder)
	{
		folder->getViewModelItem()->dirtyFilter();
	}
	/*virtual*/ void doItem(LLFolderViewItem* item)
	{
		item->getViewModelItem()->dirtyFilter();
	}
};

void LLInventoryPanel::idle(void* user_data)
{
	LLInventoryPanel* panel = (LLInventoryPanel*)user_data;
	// Nudge the filter if the clipboard state changed
	if (panel->mClipboardState != LLClipboard::instance().getGeneration())
	{
		panel->mClipboardState = LLClipboard::instance().getGeneration();
		const LLUUID trash_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TRASH);
		LLFolderViewFolder* trash_folder = panel->getFolderByID(trash_id);
		if (trash_folder)
		{
            DirtyFilterFunctor dirtyFilterFunctor;
			trash_folder->applyFunctorToChildren(dirtyFilterFunctor);
		}

	}

    bool in_visible_chain = panel->isInVisibleChain();

    if (!panel->mBuildViewsQueue.empty())
    {
        const F64 max_time = in_visible_chain ? 0.006f : 0.001f; // 6 ms
        F64 curent_time = LLTimer::getTotalSeconds();
        panel->mBuildViewsEndTime = curent_time + max_time;

        // things added last are closer to root thus of higher priority
        std::deque<LLUUID> priority_list;
        priority_list.swap(panel->mBuildViewsQueue);

        while (curent_time < panel->mBuildViewsEndTime
            && !priority_list.empty())
        {
            LLUUID item_id = priority_list.back();
            priority_list.pop_back();

            LLInventoryObject const* objectp = panel->mInventory->getObject(item_id);
            if (objectp && panel->typedViewsFilter(item_id, objectp))
            {
                LLFolderViewItem* folder_view_item = panel->getItemByID(item_id);
                if (!folder_view_item || !folder_view_item->areChildrenInited())
                {
                    const LLUUID &parent_id = objectp->getParentUUID();
                    LLFolderViewFolder* parent_folder = (LLFolderViewFolder*)panel->getItemByID(parent_id);
                    panel->buildViewsTree(item_id, parent_id, objectp, folder_view_item, parent_folder, BUILD_TIMELIMIT);
                }
            }
            curent_time = LLTimer::getTotalSeconds();
        }
        while (!priority_list.empty())
        {
            // items in priority_list are of higher priority
            panel->mBuildViewsQueue.push_back(priority_list.front());
            priority_list.pop_front();
        }
        if (panel->mBuildViewsQueue.empty())
        {
            panel->mViewsInitialized = VIEWS_INITIALIZED;
        }
    }

    // Take into account the fact that the root folder might be invalidated
    if (panel->mFolderRoot.get())
    {
        panel->mFolderRoot.get()->update();
        // while dragging, update selection rendering to reflect single/multi drag status
        if (LLToolDragAndDrop::getInstance()->hasMouseCapture())
        {
            EAcceptance last_accept = LLToolDragAndDrop::getInstance()->getLastAccept();
            if (last_accept == ACCEPT_YES_SINGLE || last_accept == ACCEPT_YES_COPY_SINGLE)
            {
                panel->mFolderRoot.get()->setShowSingleSelection(TRUE);
            }
            else
            {
                panel->mFolderRoot.get()->setShowSingleSelection(FALSE);
            }
        }
        else
        {
            panel->mFolderRoot.get()->setShowSingleSelection(FALSE);
        }
    }
    else
    {
        LL_WARNS() << "Inventory : Deleted folder root detected on panel" << LL_ENDL;
        panel->clearFolderRoot();
    }
}


void LLInventoryPanel::initializeViews(F64 max_time)
{
	if (!gInventory.isInventoryUsable()) return;

    mViewsInitialized = VIEWS_BUILDING;

    F64 curent_time = LLTimer::getTotalSeconds();
    mBuildViewsEndTime = curent_time + max_time;

	// init everything
	LLUUID root_id = getRootFolderID();
	if (root_id.notNull())
	{
		buildNewViews(getRootFolderID());
	}
	else
	{
		// Default case: always add "My Inventory" root first, "Library" root second
		// If we run out of time, this still should create root folders
		buildNewViews(gInventory.getRootFolderID());		// My Inventory
		buildNewViews(gInventory.getLibraryRootFolderID());	// Library
	}

    if (mBuildViewsQueue.empty())
    {
        mViewsInitialized = VIEWS_INITIALIZED;
    }

	gIdleCallbacks.addFunction(idle, this);
	
	openStartFolderOrMyInventory();
	
	// Special case for new user login
	if (gAgent.isFirstLogin())
	{
		// Auto open the user's library
		LLFolderViewFolder* lib_folder =   getFolderByID(gInventory.getLibraryRootFolderID());
		if (lib_folder)
		{
			lib_folder->setOpen(TRUE);
		}
		
		// Auto close the user's my inventory folder
		LLFolderViewFolder* my_inv_folder =   getFolderByID(gInventory.getRootFolderID());
		if (my_inv_folder)
		{
			my_inv_folder->setOpenArrangeRecursively(FALSE, LLFolderViewFolder::RECURSE_DOWN);
		}
	}
}


LLFolderViewFolder * LLInventoryPanel::createFolderViewFolder(LLInvFVBridge * bridge, bool allow_drop)
{
	LLFolderViewFolder::Params params(mParams.folder);

	params.name = bridge->getDisplayName();
	params.root = mFolderRoot.get();
	params.listener = bridge;
	params.tool_tip = params.name;
    params.allow_drop = allow_drop;

	params.font_color = (bridge->isLibraryItem() ? sLibraryColor : (bridge->isLink() ? sLinkColor : sDefaultColor));
	params.font_highlight_color = (bridge->isLibraryItem() ? sLibraryColor : (bridge->isLink() ? sLinkColor : sDefaultHighlightColor));
	
	return LLUICtrlFactory::create<LLFolderViewFolder>(params);
}

LLFolderViewItem * LLInventoryPanel::createFolderViewItem(LLInvFVBridge * bridge)
{
	LLFolderViewItem::Params params(mParams.item);
	
	params.name = bridge->getDisplayName();
	params.creation_date = bridge->getCreationDate();
	params.root = mFolderRoot.get();
	params.listener = bridge;
	params.rect = LLRect (0, 0, 0, 0);
	params.tool_tip = params.name;

	params.font_color = (bridge->isLibraryItem() ? sLibraryColor : (bridge->isLink() ? sLinkColor : sDefaultColor));
	params.font_highlight_color = (bridge->isLibraryItem() ? sLibraryColor : (bridge->isLink() ? sLinkColor : sDefaultHighlightColor));
	
	return LLUICtrlFactory::create<LLFolderViewItem>(params);
}

LLFolderViewItem* LLInventoryPanel::buildNewViews(const LLUUID& id)
{
    LLInventoryObject const* objectp = mInventory->getObject(id);
    return buildNewViews(id, objectp);
}

LLFolderViewItem* LLInventoryPanel::buildNewViews(const LLUUID& id, LLInventoryObject const* objectp)
{
    if (!objectp)
    {
        return NULL;
    }
    if (!typedViewsFilter(id, objectp))
    {
        // if certain types are not allowed permanently, no reason to create views
        return NULL;
    }

    const LLUUID &parent_id = objectp->getParentUUID();
    LLFolderViewItem* folder_view_item = getItemByID(id);
    LLFolderViewFolder* parent_folder = (LLFolderViewFolder*)getItemByID(parent_id);

    return buildViewsTree(id, parent_id, objectp, folder_view_item, parent_folder, BUILD_TIMELIMIT);
}

LLFolderViewItem* LLInventoryPanel::buildNewViews(const LLUUID& id,
                                                  LLInventoryObject const* objectp,
                                                  LLFolderViewItem *folder_view_item,
                                                  const EBuildModes &mode)
{
    if (!objectp)
    {
        return NULL;
    }
    if (!typedViewsFilter(id, objectp))
    {
        // if certain types are not allowed permanently, no reason to create views
        return NULL;
    }

    const LLUUID &parent_id = objectp->getParentUUID();
    LLFolderViewFolder* parent_folder = (LLFolderViewFolder*)getItemByID(parent_id);

    return buildViewsTree(id, parent_id, objectp, folder_view_item, parent_folder, mode);
}

LLFolderViewItem* LLInventoryPanel::buildViewsTree(const LLUUID& id,
                                                  const LLUUID& parent_id,
                                                  LLInventoryObject const* objectp,
                                                  LLFolderViewItem *folder_view_item,
                                                  LLFolderViewFolder *parent_folder,
                                                  const EBuildModes &mode)
{
    // Force the creation of an extra root level folder item if required by the inventory panel (default is "false")
    bool allow_drop = true;
    bool create_root = false;
    if (mParams.show_root_folder)
    {
        LLUUID root_id = getRootFolderID();
        if (root_id == id)
        {
            // We insert an extra level that's seen by the UI but has no influence on the model
            parent_folder = dynamic_cast<LLFolderViewFolder*>(folder_view_item);
            folder_view_item = NULL;
            allow_drop = mParams.allow_drop_on_root;
            create_root = true;
        }
    }

 	if (!folder_view_item && parent_folder)
  		{
			if (objectp->getType() <= LLAssetType::AT_NONE)
			{
				LL_WARNS() << "LLInventoryPanel::buildViewsTree called with invalid objectp->mType : "
					<< ((S32)objectp->getType()) << " name " << objectp->getName() << " UUID " << objectp->getUUID()
					<< LL_ENDL;
				return NULL;
			}
			
			if (objectp->getType() >= LLAssetType::AT_COUNT)
  			{
				// Example: Happens when we add assets of new, not yet supported type to library
				LL_DEBUGS() << "LLInventoryPanel::buildViewsTree called with unknown objectp->mType : "
				<< ((S32) objectp->getType()) << " name " << objectp->getName() << " UUID " << objectp->getUUID()
				<< LL_ENDL;

				LLInventoryItem* item = (LLInventoryItem*)objectp;
				if (item)
				{
					LLInvFVBridge* new_listener = mInvFVBridgeBuilder->createBridge(LLAssetType::AT_UNKNOWN,
						LLAssetType::AT_UNKNOWN,
						LLInventoryType::IT_UNKNOWN,
						this,
						&mInventoryViewModel,
						mFolderRoot.get(),
						item->getUUID(),
						item->getFlags());

					if (new_listener)
					{
						folder_view_item = createFolderViewItem(new_listener);
					}
				}
  			}
  		
  			if ((objectp->getType() == LLAssetType::AT_CATEGORY) &&
  				(objectp->getActualType() != LLAssetType::AT_LINK_FOLDER))
  			{
  				LLInvFVBridge* new_listener = mInvFVBridgeBuilder->createBridge(LLAssetType::AT_CATEGORY,
                                            (mParams.use_marketplace_folders ? LLAssetType::AT_MARKETPLACE_FOLDER : LLAssetType::AT_CATEGORY),
  																				LLInventoryType::IT_CATEGORY,
  																				this,
                                                                                &mInventoryViewModel,
  																				mFolderRoot.get(),
  																				objectp->getUUID());
  				if (new_listener)
  				{
                    folder_view_item = createFolderViewFolder(new_listener,allow_drop);
  				}
  			}
  			else
  			{
  				// Build new view for item.
  				LLInventoryItem* item = (LLInventoryItem*)objectp;
  				LLInvFVBridge* new_listener = mInvFVBridgeBuilder->createBridge(item->getType(),
  																				item->getActualType(),
  																				item->getInventoryType(),
  																				this,
																			&mInventoryViewModel,
  																				mFolderRoot.get(),
  																				item->getUUID(),
  																				item->getFlags());
 
  				if (new_listener)
  				{
				folder_view_item = createFolderViewItem(new_listener);
  				}
  			}
 
  	    if (folder_view_item)
        {
            llassert(parent_folder != NULL);
            folder_view_item->addToFolder(parent_folder);
			addItemID(id, folder_view_item);
            // In the case of the root folder been shown, open that folder by default once the widget is created
            if (create_root)
            {
                folder_view_item->setOpen(TRUE);
            }
        }
	}

    bool create_children = folder_view_item && objectp->getType() == LLAssetType::AT_CATEGORY;

    if (create_children)
    {
        switch (mode)
        {
            case BUILD_TIMELIMIT:
            {
                F64 curent_time = LLTimer::getTotalSeconds();
                // If function is out of time, we want to shedule it into mBuildViewsQueue
                // If we have time, no matter how little, create views for all children
                //
                // This creates children in 'bulk' to make sure folder has either
                // 'empty and incomplete' or 'complete' states with nothing in between.
                // Folders are marked as mIsFolderComplete == false by default,
                // later arrange() will update mIsFolderComplete by child count
                if (mBuildViewsEndTime < curent_time)
                {
                    create_children = false;
                    // run it again for the sake of creating children
                    mBuildViewsQueue.push_back(id);
                }
                else
                {
                    create_children = true;
                    folder_view_item->setChildrenInited(true);
                }
                break;
            }
            case BUILD_NO_CHILDREN:
            {
                create_children = false;
                // run it to create children, current caller is only interested in current view
                mBuildViewsQueue.push_back(id);
                break;
            }
            case BUILD_ONE_FOLDER:
            {
                // This view loads chindren, following ones don't
                // Note: Might be better idea to do 'depth' instead,
                // It also will help to prioritize root folder's content
                create_children = true;
                folder_view_item->setChildrenInited(true);
                break;
            }
            case BUILD_NO_LIMIT:
            default:
            {
                // keep working till everything exists
                create_children = true;
                folder_view_item->setChildrenInited(true);
            }
        }
    }

	// If this is a folder, add the children of the folder and recursively add any 
	// child folders.
	if (create_children)
	{
		LLViewerInventoryCategory::cat_array_t* categories;
		LLViewerInventoryItem::item_array_t* items;
		mInventory->lockDirectDescendentArrays(id, categories, items);

        LLFolderViewFolder *parentp = dynamic_cast<LLFolderViewFolder*>(folder_view_item);

		if(categories)
        {
            bool has_folders = parentp->getFoldersCount() > 0;
			for (LLViewerInventoryCategory::cat_array_t::const_iterator cat_iter = categories->begin();
				 cat_iter != categories->end();
				 ++cat_iter)
			{
				const LLViewerInventoryCategory* cat = (*cat_iter);
                if (typedViewsFilter(cat->getUUID(), cat)) 
                {
                    if (has_folders)
                    {
                        // This can be optimized: we don't need to call getItemByID()
                        // each time, especially since content is growing, we can just
                        // iter over copy of mItemMap in some way
                        LLFolderViewItem* view_itemp = getItemByID(cat->getUUID());
                        buildViewsTree(cat->getUUID(), id, cat, view_itemp, parentp, (mode == BUILD_ONE_FOLDER ? BUILD_NO_CHILDREN : mode));
                    }
                    else
                    {
                        buildViewsTree(cat->getUUID(), id, cat, NULL, parentp, (mode == BUILD_ONE_FOLDER ? BUILD_NO_CHILDREN : mode));
                    }
                }
			}
		}
		
		if(items)
        {
			for (LLViewerInventoryItem::item_array_t::const_iterator item_iter = items->begin();
				 item_iter != items->end();
				 ++item_iter)
			{
                // At the moment we have to build folder's items in bulk and ignore mBuildViewsEndTime
				const LLViewerInventoryItem* item = (*item_iter);
                if (typedViewsFilter(item->getUUID(), item))
                {
                    // This can be optimized: we don't need to call getItemByID()
                    // each time, especially since content is growing, we can just
                    // iter over copy of mItemMap in some way
                    LLFolderViewItem* view_itemp = getItemByID(item->getUUID());
                    buildViewsTree(item->getUUID(), id, item, view_itemp, parentp, mode);
                }
			}
		}
		mInventory->unlockDirectDescendentArrays(id);
	}
	
	return folder_view_item;
}

// bit of a hack to make sure the inventory is open.
void LLInventoryPanel::openStartFolderOrMyInventory()
{
	// Find My Inventory folder and open it up by name
	for (LLView *child = mFolderRoot.get()->getFirstChild(); child; child = mFolderRoot.get()->findNextSibling(child))
	{
		LLFolderViewFolder *fchild = dynamic_cast<LLFolderViewFolder*>(child);
		if (fchild
			&& fchild->getViewModelItem()
			&& fchild->getViewModelItem()->getName() == "My Inventory")
		{
			fchild->setOpen(TRUE);
			break;
		}
	}
}

void LLInventoryPanel::onItemsCompletion()
{
	if (mFolderRoot.get()) mFolderRoot.get()->updateMenu();
}

void LLInventoryPanel::openSelected()
{
	LLFolderViewItem* folder_item = mFolderRoot.get()->getCurSelectedItem();
	if(!folder_item) return;
	LLInvFVBridge* bridge = (LLInvFVBridge*)folder_item->getViewModelItem();
	if(!bridge) return;
	bridge->openItem();
}

void LLInventoryPanel::unSelectAll()	
{ 
	mFolderRoot.get()->setSelection(NULL, FALSE, FALSE);
}


BOOL LLInventoryPanel::handleHover(S32 x, S32 y, MASK mask)
{
	BOOL handled = LLView::handleHover(x, y, mask);
	if(handled)
	{
		ECursorType cursor = getWindow()->getCursor();
		if (LLInventoryModelBackgroundFetch::instance().folderFetchActive() && cursor == UI_CURSOR_ARROW)
		{
			// replace arrow cursor with arrow and hourglass cursor
			getWindow()->setCursor(UI_CURSOR_WORKING);
		}
	}
	else
	{
		getWindow()->setCursor(UI_CURSOR_ARROW);
	}
	return TRUE;
}

BOOL LLInventoryPanel::handleToolTip(S32 x, S32 y, MASK mask)
{
	if (const LLFolderViewItem* hover_item_p = (!mFolderRoot.isDead()) ? mFolderRoot.get()->getHoveredItem() : nullptr)
	{
		if (const LLFolderViewModelItemInventory* vm_item_p = static_cast<const LLFolderViewModelItemInventory*>(hover_item_p->getViewModelItem()))
		{
            LLSD params;
            params["inv_type"] = vm_item_p->getInventoryType();
            params["thumbnail_id"] = vm_item_p->getThumbnailUUID();
            params["item_id"] = vm_item_p->getUUID();
            
			LLToolTipMgr::instance().show(LLToolTip::Params()
					.message(hover_item_p->getToolTip())
					.sticky_rect(hover_item_p->calcScreenRect())
					.delay_time(LLView::getTooltipTimeout())
					.create_callback(boost::bind(&LLInspectTextureUtil::createInventoryToolTip, _1))
					.create_params(params));
			return TRUE;
		}
	}
	return LLPanel::handleToolTip(x, y, mask);
}

BOOL LLInventoryPanel::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
								   EDragAndDropType cargo_type,
								   void* cargo_data,
								   EAcceptance* accept,
								   std::string& tooltip_msg)
{
	BOOL handled = FALSE;

	if (mAcceptsDragAndDrop)
	{
		handled = LLPanel::handleDragAndDrop(x, y, mask, drop, cargo_type, cargo_data, accept, tooltip_msg);

		// If folder view is empty the (x, y) point won't be in its rect
		// so the handler must be called explicitly.
		// but only if was not handled before. See EXT-6746.
		if (!handled && mParams.allow_drop_on_root && !mFolderRoot.get()->hasVisibleChildren())
		{
			handled = mFolderRoot.get()->handleDragAndDrop(x, y, mask, drop, cargo_type, cargo_data, accept, tooltip_msg);
		}

		if (handled)
		{
			mFolderRoot.get()->setDragAndDropThisFrame();
		}
	}

	return handled;
}

void LLInventoryPanel::onFocusLost()
{
	// inventory no longer handles cut/copy/paste/delete
	if (LLEditMenuHandler::gEditMenuHandler == mFolderRoot.get())
	{
		LLEditMenuHandler::gEditMenuHandler = NULL;
	}

	LLPanel::onFocusLost();
}

void LLInventoryPanel::onFocusReceived()
{
	// inventory now handles cut/copy/paste/delete
	LLEditMenuHandler::gEditMenuHandler = mFolderRoot.get();

	LLPanel::onFocusReceived();
}

void LLInventoryPanel::onFolderOpening(const LLUUID &id)
{
    LLFolderViewItem* folder = getItemByID(id);
    if (folder && !folder->areChildrenInited())
    {
        // Last item in list will be processed first.
        // This might result in dupplicates in list, but it
        // isn't critical, views won't be created twice
        mBuildViewsQueue.push_back(id);
    }
}

bool LLInventoryPanel::addBadge(LLBadge * badge)
{
	bool badge_added = false;

	if (acceptsBadge())
	{
		badge_added = badge->addToView(mFolderRoot.get());
	}

	return badge_added;
}

void LLInventoryPanel::openAllFolders()
{
	mFolderRoot.get()->setOpenArrangeRecursively(TRUE, LLFolderViewFolder::RECURSE_DOWN);
	mFolderRoot.get()->arrangeAll();
}

void LLInventoryPanel::setSelection(const LLUUID& obj_id, BOOL take_keyboard_focus)
{
	// Don't select objects in COF (e.g. to prevent refocus when items are worn).
	const LLInventoryObject *obj = mInventory->getObject(obj_id);
	if (obj && obj->getParentUUID() == LLAppearanceMgr::instance().getCOF())
	{
		return;
	}
	setSelectionByID(obj_id, take_keyboard_focus);
}

void LLInventoryPanel::setSelectCallback(const boost::function<void (const std::deque<LLFolderViewItem*>& items, BOOL user_action)>& cb) 
{ 
	if (mFolderRoot.get())
	{
		mFolderRoot.get()->setSelectCallback(cb);
	}
}

void LLInventoryPanel::clearSelection()
{
	mSelectThisID.setNull();
	mFocusSelection = false;
}

LLInventoryPanel::selected_items_t LLInventoryPanel::getSelectedItems() const
{
    return mFolderRoot.get()->getSelectionList();
}

void LLInventoryPanel::onSelectionChange(const std::deque<LLFolderViewItem*>& items, BOOL user_action)
{
	// Schedule updating the folder view context menu when all selected items become complete (STORM-373).
	mCompletionObserver->reset();
	for (std::deque<LLFolderViewItem*>::const_iterator it = items.begin(); it != items.end(); ++it)
	{
		LLFolderViewModelItemInventory* view_model = static_cast<LLFolderViewModelItemInventory*>((*it)->getViewModelItem());
		if (view_model)
		{
			LLUUID id = view_model->getUUID();
            if (!(*it)->areChildrenInited())
            {
                const F64 max_time = 0.0001f;
                mBuildViewsEndTime = LLTimer::getTotalSeconds() + max_time;
                buildNewViews(id);
            }
			LLViewerInventoryItem* inv_item = mInventory->getItem(id);

			if (inv_item && !inv_item->isFinished())
			{
				mCompletionObserver->watchItem(id);
			}
		}
	}

	LLFolderView* fv = mFolderRoot.get();
	if (fv->needsAutoRename()) // auto-selecting a new user-created asset and preparing to rename
	{
		fv->setNeedsAutoRename(FALSE);
		if (items.size()) // new asset is visible and selected
		{
			fv->startRenamingSelectedItem();
		}
	}

	std::set<LLFolderViewItem*> selected_items = mFolderRoot.get()->getSelectionList();
	LLFolderViewItem* prev_folder_item = getItemByID(mPreviousSelectedFolder);

	if (selected_items.size() == 1)
	{
		std::set<LLFolderViewItem*>::const_iterator iter = selected_items.begin();
		LLFolderViewItem* folder_item = (*iter);
		if(folder_item && (folder_item != prev_folder_item))
		{
			LLFolderViewModelItemInventory* fve_listener = static_cast<LLFolderViewModelItemInventory*>(folder_item->getViewModelItem());
			if (fve_listener && (fve_listener->getInventoryType() == LLInventoryType::IT_CATEGORY))
			{
				if (fve_listener->getInventoryObject() && fve_listener->getInventoryObject()->getIsLinkType())
				{
					return;
				}

				if(prev_folder_item)
				{
					LLFolderBridge* prev_bridge = (LLFolderBridge*)prev_folder_item->getViewModelItem();
					if(prev_bridge)
					{
						prev_bridge->clearDisplayName();
						prev_bridge->setShowDescendantsCount(false);
						prev_folder_item->refresh();
					}
				}

				LLFolderBridge* bridge = (LLFolderBridge*)folder_item->getViewModelItem();
				if(bridge)
				{
					bridge->clearDisplayName();
					bridge->setShowDescendantsCount(true);
					folder_item->refresh();
					mPreviousSelectedFolder = bridge->getUUID();
				}
			}
		}
	}
	else
	{
		if(prev_folder_item)
		{
			LLFolderBridge* prev_bridge = (LLFolderBridge*)prev_folder_item->getViewModelItem();
			if(prev_bridge)
			{
				prev_bridge->clearDisplayName();
				prev_bridge->setShowDescendantsCount(false);
				prev_folder_item->refresh();
			}
		}
		mPreviousSelectedFolder = LLUUID();
	}

}

void LLInventoryPanel::updateFolderLabel(const LLUUID& folder_id)
{
	if(folder_id != mPreviousSelectedFolder) return;

	LLFolderViewItem* folder_item = getItemByID(mPreviousSelectedFolder);
	if(folder_item)
	{
		LLFolderBridge* bridge = (LLFolderBridge*)folder_item->getViewModelItem();
		if(bridge)
		{
			bridge->clearDisplayName();
			bridge->setShowDescendantsCount(true);
			folder_item->refresh();
		}
	}
}

void LLInventoryPanel::doCreate(const LLSD& userdata)
{
	reset_inventory_filter();
	menu_create_inventory_item(this, LLFolderBridge::sSelf.get(), userdata);
}

bool LLInventoryPanel::beginIMSession()
{
	std::set<LLFolderViewItem*> selected_items =   mFolderRoot.get()->getSelectionList();

	std::string name;

	std::vector<LLUUID> members;
	EInstantMessage type = IM_SESSION_CONFERENCE_START;

	std::set<LLFolderViewItem*>::const_iterator iter;
	for (iter = selected_items.begin(); iter != selected_items.end(); iter++)
	{

		LLFolderViewItem* folder_item = (*iter);
			
		if(folder_item) 
		{
			LLFolderViewModelItemInventory* fve_listener = static_cast<LLFolderViewModelItemInventory*>(folder_item->getViewModelItem());
			if (fve_listener && (fve_listener->getInventoryType() == LLInventoryType::IT_CATEGORY))
			{

				LLFolderBridge* bridge = (LLFolderBridge*)folder_item->getViewModelItem();
				if(!bridge) return true;
				LLViewerInventoryCategory* cat = bridge->getCategory();
				if(!cat) return true;
				name = cat->getName();
				LLUniqueBuddyCollector is_buddy;
				LLInventoryModel::cat_array_t cat_array;
				LLInventoryModel::item_array_t item_array;
				gInventory.collectDescendentsIf(bridge->getUUID(),
												cat_array,
												item_array,
												LLInventoryModel::EXCLUDE_TRASH,
												is_buddy);
				S32 count = item_array.size();
				if(count > 0)
				{
					//*TODO by what to replace that?
					//LLFloaterReg::showInstance("communicate");

					// create the session
					LLAvatarTracker& at = LLAvatarTracker::instance();
					LLUUID id;
					for(S32 i = 0; i < count; ++i)
					{
						id = item_array.at(i)->getCreatorUUID();
						if(at.isBuddyOnline(id))
						{
							members.push_back(id);
						}
					}
				}
			}
			else
			{
				LLInvFVBridge* listenerp = (LLInvFVBridge*)folder_item->getViewModelItem();

				if (listenerp->getInventoryType() == LLInventoryType::IT_CALLINGCARD)
				{
					LLInventoryItem* inv_item = gInventory.getItem(listenerp->getUUID());

					if (inv_item)
					{
						LLAvatarTracker& at = LLAvatarTracker::instance();
						LLUUID id = inv_item->getCreatorUUID();

						if(at.isBuddyOnline(id))
						{
							members.push_back(id);
						}
					}
				} //if IT_CALLINGCARD
			} //if !IT_CATEGORY
		}
	} //for selected_items	

	// the session_id is randomly generated UUID which will be replaced later
	// with a server side generated number

	if (name.empty())
	{
		name = LLTrans::getString("conference-title");
	}

	LLUUID session_id = gIMMgr->addSession(name, type, members[0], members);
	if (session_id != LLUUID::null)
	{
		LLFloaterIMContainer::getInstance()->showConversation(session_id);
	}
		
	return true;
}

void LLInventoryPanel::fileUploadLocation(const LLSD& userdata)
{
    const std::string param = userdata.asString();
    if (param == "model")
    {
        gSavedPerAccountSettings.setString("ModelUploadFolder", LLFolderBridge::sSelf.get()->getUUID().asString());
    }
    else if (param == "texture")
    {
        gSavedPerAccountSettings.setString("TextureUploadFolder", LLFolderBridge::sSelf.get()->getUUID().asString());
    }
    else if (param == "sound")
    {
        gSavedPerAccountSettings.setString("SoundUploadFolder", LLFolderBridge::sSelf.get()->getUUID().asString());
    }
    else if (param == "animation")
    {
        gSavedPerAccountSettings.setString("AnimationUploadFolder", LLFolderBridge::sSelf.get()->getUUID().asString());
    }
}

void LLInventoryPanel::openSingleViewInventory(LLUUID folder_id)
{
    LLPanelMainInventory::newFolderWindow(folder_id.isNull() ? LLFolderBridge::sSelf.get()->getUUID() : folder_id);
}

void LLInventoryPanel::purgeSelectedItems()
{
    if (!mFolderRoot.get()) return;

    const std::set<LLFolderViewItem*> inventory_selected = mFolderRoot.get()->getSelectionList();
    if (inventory_selected.empty()) return;
    LLSD args;
    S32 count = inventory_selected.size();
    for (std::set<LLFolderViewItem*>::const_iterator it = inventory_selected.begin(), end_it = inventory_selected.end();
        it != end_it;
        ++it)
    {
        LLUUID item_id = static_cast<LLFolderViewModelItemInventory*>((*it)->getViewModelItem())->getUUID();
        LLInventoryModel::cat_array_t cats;
        LLInventoryModel::item_array_t items;
        gInventory.collectDescendents(item_id, cats, items, LLInventoryModel::INCLUDE_TRASH);
        count += items.size() + cats.size();
    }
    args["COUNT"] = count;
    LLNotificationsUtil::add("PurgeSelectedItems", args, LLSD(), boost::bind(&LLInventoryPanel::callbackPurgeSelectedItems, this, _1, _2));
}

void LLInventoryPanel::callbackPurgeSelectedItems(const LLSD& notification, const LLSD& response)
{
    if (!mFolderRoot.get()) return;

    S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
    if (option == 0)
    {
        const std::set<LLFolderViewItem*> inventory_selected = mFolderRoot.get()->getSelectionList();
        if (inventory_selected.empty()) return;

        std::set<LLFolderViewItem*>::const_iterator it = inventory_selected.begin();
        const std::set<LLFolderViewItem*>::const_iterator it_end = inventory_selected.end();
        for (; it != it_end; ++it)
        {
            LLUUID item_id = static_cast<LLFolderViewModelItemInventory*>((*it)->getViewModelItem())->getUUID();
            remove_inventory_object(item_id, NULL);
        }
    }
}

bool LLInventoryPanel::attachObject(const LLSD& userdata)
{
	// Copy selected item UUIDs to a vector.
	std::set<LLFolderViewItem*> selected_items = mFolderRoot.get()->getSelectionList();
	uuid_vec_t items;
	for (std::set<LLFolderViewItem*>::const_iterator set_iter = selected_items.begin();
		 set_iter != selected_items.end(); 
		 ++set_iter)
	{
		items.push_back(static_cast<LLFolderViewModelItemInventory*>((*set_iter)->getViewModelItem())->getUUID());
	}

	// Attach selected items.
	LLViewerAttachMenu::attachObjects(items, userdata.asString());

	gFocusMgr.setKeyboardFocus(NULL);

	return true;
}

BOOL LLInventoryPanel::getSinceLogoff()
{
	return getFilter().isSinceLogoff();
}

// DEBUG ONLY
// static 
void LLInventoryPanel::dumpSelectionInformation(void* user_data)
{
	LLInventoryPanel* iv = (LLInventoryPanel*)user_data;
	iv->mFolderRoot.get()->dumpSelectionInformation();
}

BOOL is_inventorysp_active()
{
	LLSidepanelInventory *sidepanel_inventory =	LLFloaterSidePanelContainer::getPanel<LLSidepanelInventory>("inventory");
	if (!sidepanel_inventory || !sidepanel_inventory->isInVisibleChain()) return FALSE;
	return sidepanel_inventory->isMainInventoryPanelActive();
}

// static
LLInventoryPanel* LLInventoryPanel::getActiveInventoryPanel(BOOL auto_open)
{
	S32 z_min = S32_MAX;
	LLInventoryPanel* res = NULL;
	LLFloater* active_inv_floaterp = NULL;

	LLFloater* floater_inventory = LLFloaterReg::getInstance("inventory");
	if (!floater_inventory)
	{
		LL_WARNS() << "Could not find My Inventory floater" << LL_ENDL;
		return FALSE;
	}

	LLSidepanelInventory *inventory_panel =	LLFloaterSidePanelContainer::getPanel<LLSidepanelInventory>("inventory");

	// Iterate through the inventory floaters and return whichever is on top.
	LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("inventory");
	for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin(); iter != inst_list.end(); ++iter)
	{
		LLFloaterSidePanelContainer* inventory_floater = dynamic_cast<LLFloaterSidePanelContainer*>(*iter);
		inventory_panel = inventory_floater->findChild<LLSidepanelInventory>("main_panel");

		if (inventory_floater && inventory_panel && inventory_floater->getVisible())
		{
			S32 z_order = gFloaterView->getZOrder(inventory_floater);
			if (z_order < z_min)
			{
				res = inventory_panel->getActivePanel();
				z_min = z_order;
				active_inv_floaterp = inventory_floater;
			}
		}
	}

	if (res)
	{
		// Make sure the floater is not minimized (STORM-438).
		if (active_inv_floaterp && active_inv_floaterp->isMinimized())
		{
			active_inv_floaterp->setMinimized(FALSE);
		}
	}	
	else if (auto_open)
	{
		floater_inventory->openFloater();

		res = inventory_panel->getActivePanel();
	}

	return res;
}

//static
void LLInventoryPanel::openInventoryPanelAndSetSelection(BOOL auto_open, const LLUUID& obj_id, BOOL main_panel, BOOL take_keyboard_focus, BOOL reset_filter)
{
	LLSidepanelInventory* sidepanel_inventory = LLFloaterSidePanelContainer::getPanel<LLSidepanelInventory>("inventory");
	sidepanel_inventory->showInventoryPanel();

	bool in_inbox = (gInventory.isObjectDescendentOf(obj_id, gInventory.findCategoryUUIDForType(LLFolderType::FT_INBOX)));

	if (!in_inbox && (main_panel || !sidepanel_inventory->getMainInventoryPanel()->isRecentItemsPanelSelected()))
	{
		sidepanel_inventory->selectAllItemsPanel();
	}
	LLInventoryPanel *active_panel = LLInventoryPanel::getActiveInventoryPanel(auto_open);

	if (active_panel)
	{
		LL_DEBUGS("Messaging") << "Highlighting" << obj_id  << LL_ENDL;

		if (reset_filter)
		{
			reset_inventory_filter();
		}

		if (in_inbox)
		{
			
			LLInventoryPanel * inventory_panel = NULL;
			sidepanel_inventory->openInbox();
			inventory_panel = sidepanel_inventory->getInboxPanel();

			if (inventory_panel)
			{
				inventory_panel->setSelection(obj_id, take_keyboard_focus);
			}
		}
		else
		{
			LLFloater* floater_inventory = LLFloaterReg::getInstance("inventory");
			if (floater_inventory)
			{
				floater_inventory->setFocus(TRUE);
			}
			active_panel->setSelection(obj_id, take_keyboard_focus);
		}
	}
}

void LLInventoryPanel::setSFViewAndOpenFolder(const LLInventoryPanel* panel, const LLUUID& folder_id)
{

    LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("inventory");
    for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin(); iter != inst_list.end(); ++iter)
    {
        LLFloaterSidePanelContainer* inventory_floater = dynamic_cast<LLFloaterSidePanelContainer*>(*iter);
        LLSidepanelInventory* sidepanel_inventory = inventory_floater->findChild<LLSidepanelInventory>("main_panel");

        LLPanelMainInventory* main_inventory = sidepanel_inventory->getMainInventoryPanel();
        if (main_inventory && panel->hasAncestor(main_inventory) && !main_inventory->isSingleFolderMode())
        {
            main_inventory->onViewModeClick();
            main_inventory->setSingleFolderViewRoot(folder_id, false);
        }
    }
}

void LLInventoryPanel::addHideFolderType(LLFolderType::EType folder_type)
{
	getFilter().setFilterCategoryTypes(getFilter().getFilterCategoryTypes() & ~(1ULL << folder_type));
}

BOOL LLInventoryPanel::getIsHiddenFolderType(LLFolderType::EType folder_type) const
{
	return !(getFilter().getFilterCategoryTypes() & (1ULL << folder_type));
}

void LLInventoryPanel::addItemID( const LLUUID& id, LLFolderViewItem*   itemp )
{
	mItemMap[id] = itemp;
}

void LLInventoryPanel::removeItemID(const LLUUID& id)
{
	LLInventoryModel::cat_array_t categories;
	LLInventoryModel::item_array_t items;
	gInventory.collectDescendents(id, categories, items, TRUE);

	mItemMap.erase(id);

	for (LLInventoryModel::cat_array_t::iterator it = categories.begin(),    end_it = categories.end();
		it != end_it;
		++it)
	{
		mItemMap.erase((*it)->getUUID());
}

	for (LLInventoryModel::item_array_t::iterator it = items.begin(),   end_it  = items.end();
		it != end_it;
		++it)
	{
		mItemMap.erase((*it)->getUUID());
	}
}

LLFolderViewItem* LLInventoryPanel::getItemByID(const LLUUID& id)
{
    LL_PROFILE_ZONE_SCOPED;

	std::map<LLUUID, LLFolderViewItem*>::iterator map_it;
	map_it = mItemMap.find(id);
	if (map_it != mItemMap.end())
	{
		return map_it->second;
	}

	return NULL;
}

LLFolderViewFolder* LLInventoryPanel::getFolderByID(const LLUUID& id)
{
	LLFolderViewItem* item = getItemByID(id);
	return dynamic_cast<LLFolderViewFolder*>(item);
}


void LLInventoryPanel::setSelectionByID( const LLUUID& obj_id, BOOL    take_keyboard_focus )
{
	LLFolderViewItem* itemp = getItemByID(obj_id);

    if (itemp && !itemp->areChildrenInited())
    {
        LLInventoryObject const* objectp = mInventory->getObject(obj_id);
        if (objectp)
        {
            buildNewViews(obj_id, objectp, itemp, BUILD_ONE_FOLDER);
        }
    }

	if(itemp && itemp->getViewModelItem())
	{
		itemp->arrangeAndSet(TRUE, take_keyboard_focus);
		mSelectThisID.setNull();
		mFocusSelection = false;
		return;
	}
	else
	{
		// save the desired item to be selected later (if/when ready)
		mFocusSelection = take_keyboard_focus;
		mSelectThisID = obj_id;
	}
}

void LLInventoryPanel::updateSelection()
{
	if (mSelectThisID.notNull())
	{
		setSelectionByID(mSelectThisID, mFocusSelection);
	}
}

void LLInventoryPanel::doToSelected(const LLSD& userdata)
{
	if (("purge" == userdata.asString()))
	{
		purgeSelectedItems();
		return;
	}
	LLInventoryAction::doToSelected(mInventory, mFolderRoot.get(), userdata.asString());

	return;
}

BOOL LLInventoryPanel::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)
		{
			if (mSuppressOpenItemAction)
			{
				LLFolderViewItem* folder_item = mFolderRoot.get()->getCurSelectedItem();
				if(folder_item)
				{
					LLInvFVBridge* bridge = (LLInvFVBridge*)folder_item->getViewModelItem();
					if(bridge && (bridge->getInventoryType() != LLInventoryType::IT_CATEGORY))
					{
						return handled;
					}
				}
			}
			LLInventoryAction::doToSelected(mInventory, mFolderRoot.get(), "open");
			handled = TRUE;
		}
		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 (isSelectionRemovable() && (mask == MASK_NONE))
		{
			LLInventoryAction::doToSelected(mInventory, mFolderRoot.get(), "delete");
			handled = TRUE;
		}
		break;
	}
	return handled;
}

bool LLInventoryPanel::isSelectionRemovable()
{
	bool can_delete = false;
	if (mFolderRoot.get())
	{
		std::set<LLFolderViewItem*> selection_set = mFolderRoot.get()->getSelectionList();
		if (!selection_set.empty()) 
		{
			can_delete = true;
			for (std::set<LLFolderViewItem*>::iterator iter = selection_set.begin();
				 iter != selection_set.end();
				 ++iter)
			{
				LLFolderViewItem *item = *iter;
				const LLFolderViewModelItemInventory *listener = static_cast<const LLFolderViewModelItemInventory*>(item->getViewModelItem());
				if (!listener)
				{
					can_delete = false;
				}
				else
				{
					can_delete &= listener->isItemRemovable() && !listener->isItemInTrash();
				}
			}
		}
	}
	return can_delete;
}

/************************************************************************/
/* Recent Inventory Panel related class                                 */
/************************************************************************/
static const LLRecentInventoryBridgeBuilder RECENT_ITEMS_BUILDER;
class LLInventoryRecentItemsPanel : public LLInventoryPanel
{
public:
	struct Params :	public LLInitParam::Block<Params, LLInventoryPanel::Params>
	{};

	void initFromParams(const Params& p)
	{
		LLInventoryPanel::initFromParams(p);
		// turn on inbox for recent items
		getFilter().setFilterCategoryTypes(getFilter().getFilterCategoryTypes() | (1ULL << LLFolderType::FT_INBOX));
        // turn off marketplace for recent items
        getFilter().setFilterNoMarketplaceFolder();
	}

protected:
	LLInventoryRecentItemsPanel (const Params&);
	friend class LLUICtrlFactory;
};

LLInventoryRecentItemsPanel::LLInventoryRecentItemsPanel( const Params& params)
: LLInventoryPanel(params)
{
	// replace bridge builder to have necessary View bridges.
	mInvFVBridgeBuilder = &RECENT_ITEMS_BUILDER;
}

static LLDefaultChildRegistry::Register<LLInventorySingleFolderPanel> t_single_folder_inventory_panel("single_folder_inventory_panel");

LLInventorySingleFolderPanel::LLInventorySingleFolderPanel(const Params& params)
    : LLInventoryPanel(params)
{
    getFilter().setSingleFolderMode(true);
    getFilter().setEmptyLookupMessage("InventorySingleFolderNoMatches");
    getFilter().setDefaultEmptyLookupMessage("InventorySingleFolderEmpty");

    mCommitCallbackRegistrar.add("Inventory.OpenSelectedFolder", boost::bind(&LLInventorySingleFolderPanel::openInCurrentWindow, this, _2));
}

LLInventorySingleFolderPanel::~LLInventorySingleFolderPanel()
{
}

void LLInventorySingleFolderPanel::setSelectCallback(const boost::function<void(const std::deque<LLFolderViewItem*>& items, BOOL user_action)>& cb)
{
    if (mFolderRoot.get())
    {
        mFolderRoot.get()->setSelectCallback(cb);
        mSelectionCallback = cb;
    }
}

void LLInventorySingleFolderPanel::initFromParams(const Params& p)
{
    Params fav_params(p);
    fav_params.start_folder.id = gInventory.getRootFolderID();
    LLInventoryPanel::initFromParams(p);
    changeFolderRoot(gInventory.getRootFolderID());
}

void LLInventorySingleFolderPanel::openInCurrentWindow(const LLSD& userdata)
{
    changeFolderRoot(LLFolderBridge::sSelf.get()->getUUID());
}

void LLInventorySingleFolderPanel::changeFolderRoot(const LLUUID& new_id)
{
    if(mFolderID.notNull())
    {
        mBackwardFolders.push_back(mFolderID);
    }
    mFolderID = new_id;
    updateSingleFolderRoot();
}

void LLInventorySingleFolderPanel::onForwardFolder()
{
    if(!mForwardFolders.empty() && (mFolderID != mForwardFolders.back()))
    {
        mBackwardFolders.push_back(mFolderID);
        mFolderID = mForwardFolders.back();
        mForwardFolders.pop_back();
        updateSingleFolderRoot();
    }
}

void LLInventorySingleFolderPanel::onBackwardFolder()
{
    if(!mBackwardFolders.empty() && (mFolderID != mBackwardFolders.back()))
    {
        mForwardFolders.push_back(mFolderID);
        mFolderID = mBackwardFolders.back();
        mBackwardFolders.pop_back();
        updateSingleFolderRoot();
    }
}

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

boost::signals2::connection LLInventorySingleFolderPanel::setRootChangedCallback(root_changed_callback_t cb)
{
    return mRootChangedSignal.connect(cb);
}

void LLInventorySingleFolderPanel::updateSingleFolderRoot()
{
    if (mFolderID != getRootFolderID())
    {
        mRootChangedSignal();

        LLUUID root_id = mFolderID;
        if (mFolderRoot.get())
        {
            removeItemID(getRootFolderID());
            mFolderRoot.get()->destroyView();
        }

        mCommitCallbackRegistrar.pushScope();
        {
            LLFolderView* folder_view = createFolderRoot(root_id);
            folder_view->setChildrenInited(false);
            mFolderRoot = folder_view->getHandle();

            addItemID(root_id, mFolderRoot.get());

            LLRect scroller_view_rect = getRect();
            scroller_view_rect.translate(-scroller_view_rect.mLeft, -scroller_view_rect.mBottom);
            LLScrollContainer::Params scroller_params(mParams.scroll());
            scroller_params.rect(scroller_view_rect);

            if (mScroller)
            {
                removeChild(mScroller);
                delete mScroller;
                mScroller = NULL;
            }
            mScroller = LLUICtrlFactory::create<LLFolderViewScrollContainer>(scroller_params);
            addChild(mScroller);
            mScroller->addChild(mFolderRoot.get());
            mFolderRoot.get()->setScrollContainer(mScroller);
            mFolderRoot.get()->setFollowsAll();
            mFolderRoot.get()->addChild(mFolderRoot.get()->mStatusTextBox);

            if (!mSelectionCallback.empty())
            {
                mFolderRoot.get()->setSelectCallback(mSelectionCallback);
            }
        }
        mCommitCallbackRegistrar.popScope();
        mFolderRoot.get()->setCallbackRegistrar(&mCommitCallbackRegistrar);

        buildNewViews(mFolderID);
    }
}

/************************************************************************/
/* Asset Pre-Filtered Inventory Panel related class                     */
/************************************************************************/

void LLAssetFilteredInventoryPanel::initFromParams(const Params& p)
{
    mAssetType = LLAssetType::lookup(p.filter_asset_type.getValue());
    LLInventoryPanel::initFromParams(p);
    U64 filter_cats = getFilter().getFilterCategoryTypes();
    filter_cats &= ~(1ULL << LLFolderType::FT_MARKETPLACE_LISTINGS);
    getFilter().setFilterCategoryTypes(filter_cats);
    getFilter().setFilterNoMarketplaceFolder();
}

BOOL LLAssetFilteredInventoryPanel::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
    EDragAndDropType cargo_type,
    void* cargo_data,
    EAcceptance* accept,
    std::string& tooltip_msg)
{
    BOOL result = FALSE;

    if (mAcceptsDragAndDrop)
    {
        EDragAndDropType allow_type = LLViewerAssetType::lookupDragAndDropType(mAssetType);
        // Don't allow DAD_CATEGORY here since it can contain other items besides required assets
        // We should see everything we drop!
        if (allow_type == cargo_type)
        {
            result = LLInventoryPanel::handleDragAndDrop(x, y, mask, drop, cargo_type, cargo_data, accept, tooltip_msg);
        }
    }

    return result;
}

/*virtual*/
bool LLAssetFilteredInventoryPanel::typedViewsFilter(const LLUUID& id, LLInventoryObject const* objectp)
{
    if (!objectp)
    {
        return false;
    }

    if (objectp->getType() != mAssetType && objectp->getType() != LLAssetType::AT_CATEGORY)
    {
        return false;
    }

    return true;
}

void LLAssetFilteredInventoryPanel::itemChanged(const LLUUID& id, U32 mask, const LLInventoryObject* model_item)
{
    if (!model_item && !getItemByID(id))
    {
        // remove operation, but item is not in panel already
        return;
    }

    if (model_item
        && model_item->getType() != mAssetType
        && model_item->getType() != LLAssetType::AT_CATEGORY)
    {
        return;
    }

    LLInventoryPanel::itemChanged(id, mask, model_item);
}

namespace LLInitParam
{
	void TypeValues<LLFolderType::EType>::declareValues()
	{
		declare(LLFolderType::lookup(LLFolderType::FT_TEXTURE)          , LLFolderType::FT_TEXTURE);
		declare(LLFolderType::lookup(LLFolderType::FT_SOUND)            , LLFolderType::FT_SOUND);
		declare(LLFolderType::lookup(LLFolderType::FT_CALLINGCARD)      , LLFolderType::FT_CALLINGCARD);
		declare(LLFolderType::lookup(LLFolderType::FT_LANDMARK)         , LLFolderType::FT_LANDMARK);
		declare(LLFolderType::lookup(LLFolderType::FT_CLOTHING)         , LLFolderType::FT_CLOTHING);
		declare(LLFolderType::lookup(LLFolderType::FT_OBJECT)           , LLFolderType::FT_OBJECT);
		declare(LLFolderType::lookup(LLFolderType::FT_NOTECARD)         , LLFolderType::FT_NOTECARD);
		declare(LLFolderType::lookup(LLFolderType::FT_ROOT_INVENTORY)   , LLFolderType::FT_ROOT_INVENTORY);
		declare(LLFolderType::lookup(LLFolderType::FT_LSL_TEXT)         , LLFolderType::FT_LSL_TEXT);
		declare(LLFolderType::lookup(LLFolderType::FT_BODYPART)         , LLFolderType::FT_BODYPART);
		declare(LLFolderType::lookup(LLFolderType::FT_TRASH)            , LLFolderType::FT_TRASH);
		declare(LLFolderType::lookup(LLFolderType::FT_SNAPSHOT_CATEGORY), LLFolderType::FT_SNAPSHOT_CATEGORY);
		declare(LLFolderType::lookup(LLFolderType::FT_LOST_AND_FOUND)   , LLFolderType::FT_LOST_AND_FOUND);
		declare(LLFolderType::lookup(LLFolderType::FT_ANIMATION)        , LLFolderType::FT_ANIMATION);
		declare(LLFolderType::lookup(LLFolderType::FT_GESTURE)          , LLFolderType::FT_GESTURE);
		declare(LLFolderType::lookup(LLFolderType::FT_FAVORITE)         , LLFolderType::FT_FAVORITE);
		declare(LLFolderType::lookup(LLFolderType::FT_ENSEMBLE_START)   , LLFolderType::FT_ENSEMBLE_START);
		declare(LLFolderType::lookup(LLFolderType::FT_ENSEMBLE_END)     , LLFolderType::FT_ENSEMBLE_END);
		declare(LLFolderType::lookup(LLFolderType::FT_CURRENT_OUTFIT)   , LLFolderType::FT_CURRENT_OUTFIT);
		declare(LLFolderType::lookup(LLFolderType::FT_OUTFIT)           , LLFolderType::FT_OUTFIT);
		declare(LLFolderType::lookup(LLFolderType::FT_MY_OUTFITS)       , LLFolderType::FT_MY_OUTFITS);
		declare(LLFolderType::lookup(LLFolderType::FT_MESH )            , LLFolderType::FT_MESH );
		declare(LLFolderType::lookup(LLFolderType::FT_INBOX)            , LLFolderType::FT_INBOX);
		declare(LLFolderType::lookup(LLFolderType::FT_OUTBOX)           , LLFolderType::FT_OUTBOX);
		declare(LLFolderType::lookup(LLFolderType::FT_BASIC_ROOT)       , LLFolderType::FT_BASIC_ROOT);
        declare(LLFolderType::lookup(LLFolderType::FT_SETTINGS)         , LLFolderType::FT_SETTINGS);
		declare(LLFolderType::lookup(LLFolderType::FT_MARKETPLACE_LISTINGS)   , LLFolderType::FT_MARKETPLACE_LISTINGS);
		declare(LLFolderType::lookup(LLFolderType::FT_MARKETPLACE_STOCK), LLFolderType::FT_MARKETPLACE_STOCK);
		declare(LLFolderType::lookup(LLFolderType::FT_MARKETPLACE_VERSION), LLFolderType::FT_MARKETPLACE_VERSION);
	}
}