summaryrefslogtreecommitdiffstats
path: root/layout/xul/tree/nsTreeContentView.cpp
blob: 75652918a73e08a1b7e9df29f8d01bccf2c0bb10 (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsNameSpaceManager.h"
#include "nsGkAtoms.h"
#include "nsTreeUtils.h"
#include "nsTreeContentView.h"
#include "ChildIterator.h"
#include "nsError.h"
#include "nsXULSortService.h"
#include "nsTreeBodyFrame.h"
#include "nsTreeColumns.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/TreeContentViewBinding.h"
#include "mozilla/dom/XULTreeElement.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/dom/Document.h"

using namespace mozilla;
using namespace mozilla::dom;

// A content model view implementation for the tree.

#define ROW_FLAG_CONTAINER 0x01
#define ROW_FLAG_OPEN 0x02
#define ROW_FLAG_EMPTY 0x04
#define ROW_FLAG_SEPARATOR 0x08

class Row {
 public:
  Row(Element* aContent, int32_t aParentIndex)
      : mContent(aContent),
        mParentIndex(aParentIndex),
        mSubtreeSize(0),
        mFlags(0) {}

  ~Row() = default;

  void SetContainer(bool aContainer) {
    aContainer ? mFlags |= ROW_FLAG_CONTAINER : mFlags &= ~ROW_FLAG_CONTAINER;
  }
  bool IsContainer() { return mFlags & ROW_FLAG_CONTAINER; }

  void SetOpen(bool aOpen) {
    aOpen ? mFlags |= ROW_FLAG_OPEN : mFlags &= ~ROW_FLAG_OPEN;
  }
  bool IsOpen() { return !!(mFlags & ROW_FLAG_OPEN); }

  void SetEmpty(bool aEmpty) {
    aEmpty ? mFlags |= ROW_FLAG_EMPTY : mFlags &= ~ROW_FLAG_EMPTY;
  }
  bool IsEmpty() { return !!(mFlags & ROW_FLAG_EMPTY); }

  void SetSeparator(bool aSeparator) {
    aSeparator ? mFlags |= ROW_FLAG_SEPARATOR : mFlags &= ~ROW_FLAG_SEPARATOR;
  }
  bool IsSeparator() { return !!(mFlags & ROW_FLAG_SEPARATOR); }

  // Weak reference to a content item.
  Element* mContent;

  // The parent index of the item, set to -1 for the top level items.
  int32_t mParentIndex;

  // Subtree size for this item.
  int32_t mSubtreeSize;

 private:
  // State flags
  int8_t mFlags;
};

// We don't reference count the reference to the document
// If the document goes away first, we'll be informed and we
// can drop our reference.
// If we go away first, we'll get rid of ourselves from the
// document's observer list.

nsTreeContentView::nsTreeContentView(void)
    : mTree(nullptr), mSelection(nullptr), mDocument(nullptr) {}

nsTreeContentView::~nsTreeContentView(void) {
  // Remove ourselves from mDocument's observers.
  if (mDocument) mDocument->RemoveObserver(this);
}

nsresult NS_NewTreeContentView(nsITreeView** aResult) {
  *aResult = new nsTreeContentView;
  if (!*aResult) return NS_ERROR_OUT_OF_MEMORY;
  NS_ADDREF(*aResult);
  return NS_OK;
}

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(nsTreeContentView, mTree, mSelection,
                                      mBody)

NS_IMPL_CYCLE_COLLECTING_ADDREF(nsTreeContentView)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsTreeContentView)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsTreeContentView)
  NS_INTERFACE_MAP_ENTRY(nsITreeView)
  NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver)
  NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsITreeView)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_END

JSObject* nsTreeContentView::WrapObject(JSContext* aCx,
                                        JS::Handle<JSObject*> aGivenProto) {
  return TreeContentView_Binding::Wrap(aCx, this, aGivenProto);
}

nsISupports* nsTreeContentView::GetParentObject() { return mTree; }

NS_IMETHODIMP
nsTreeContentView::GetRowCount(int32_t* aRowCount) {
  *aRowCount = mRows.Length();

  return NS_OK;
}

NS_IMETHODIMP
nsTreeContentView::GetSelection(nsITreeSelection** aSelection) {
  NS_IF_ADDREF(*aSelection = GetSelection());

  return NS_OK;
}

bool nsTreeContentView::CanTrustTreeSelection(nsISupports* aValue) {
  // Untrusted content is only allowed to specify known-good views
  if (nsContentUtils::LegacyIsCallerChromeOrNativeCode()) return true;
  nsCOMPtr<nsINativeTreeSelection> nativeTreeSel = do_QueryInterface(aValue);
  return nativeTreeSel && NS_SUCCEEDED(nativeTreeSel->EnsureNative());
}

NS_IMETHODIMP
nsTreeContentView::SetSelection(nsITreeSelection* aSelection) {
  ErrorResult rv;
  SetSelection(aSelection, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::SetSelection(nsITreeSelection* aSelection,
                                     ErrorResult& aError) {
  if (aSelection && !CanTrustTreeSelection(aSelection)) {
    aError.ThrowSecurityError("Not allowed to set tree selection");
    return;
  }

  mSelection = aSelection;
}

void nsTreeContentView::GetRowProperties(int32_t aRow, nsAString& aProperties,
                                         ErrorResult& aError) {
  aProperties.Truncate();
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();
  nsIContent* realRow;
  if (row->IsSeparator())
    realRow = row->mContent;
  else
    realRow = nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);

  if (realRow && realRow->IsElement()) {
    realRow->AsElement()->GetAttr(nsGkAtoms::properties, aProperties);
  }
}

NS_IMETHODIMP
nsTreeContentView::GetRowProperties(int32_t aIndex, nsAString& aProps) {
  ErrorResult rv;
  GetRowProperties(aIndex, aProps, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::GetCellProperties(int32_t aRow, nsTreeColumn& aColumn,
                                          nsAString& aProperties,
                                          ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();
  nsIContent* realRow =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
  if (realRow) {
    Element* cell = GetCell(realRow, aColumn);
    if (cell) {
      cell->GetAttr(nsGkAtoms::properties, aProperties);
    }
  }
}

NS_IMETHODIMP
nsTreeContentView::GetCellProperties(int32_t aRow, nsTreeColumn* aCol,
                                     nsAString& aProps) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  GetCellProperties(aRow, *aCol, aProps, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::GetColumnProperties(nsTreeColumn& aColumn,
                                            nsAString& aProperties) {
  RefPtr<Element> element = aColumn.Element();

  if (element) {
    element->GetAttr(nsGkAtoms::properties, aProperties);
  }
}

NS_IMETHODIMP
nsTreeContentView::GetColumnProperties(nsTreeColumn* aCol, nsAString& aProps) {
  NS_ENSURE_ARG(aCol);

  GetColumnProperties(*aCol, aProps);
  return NS_OK;
}

bool nsTreeContentView::IsContainer(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return false;
  }

  return mRows[aRow]->IsContainer();
}

NS_IMETHODIMP
nsTreeContentView::IsContainer(int32_t aIndex, bool* _retval) {
  ErrorResult rv;
  *_retval = IsContainer(aIndex, rv);
  return rv.StealNSResult();
}

bool nsTreeContentView::IsContainerOpen(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return false;
  }

  return mRows[aRow]->IsOpen();
}

NS_IMETHODIMP
nsTreeContentView::IsContainerOpen(int32_t aIndex, bool* _retval) {
  ErrorResult rv;
  *_retval = IsContainerOpen(aIndex, rv);
  return rv.StealNSResult();
}

bool nsTreeContentView::IsContainerEmpty(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return false;
  }

  return mRows[aRow]->IsEmpty();
}

NS_IMETHODIMP
nsTreeContentView::IsContainerEmpty(int32_t aIndex, bool* _retval) {
  ErrorResult rv;
  *_retval = IsContainerEmpty(aIndex, rv);
  return rv.StealNSResult();
}

bool nsTreeContentView::IsSeparator(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return false;
  }

  return mRows[aRow]->IsSeparator();
}

NS_IMETHODIMP
nsTreeContentView::IsSeparator(int32_t aIndex, bool* _retval) {
  ErrorResult rv;
  *_retval = IsSeparator(aIndex, rv);
  return rv.StealNSResult();
}

NS_IMETHODIMP
nsTreeContentView::IsSorted(bool* _retval) {
  *_retval = IsSorted();

  return NS_OK;
}

bool nsTreeContentView::CanDrop(int32_t aRow, int32_t aOrientation,
                                ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
  }
  return false;
}

bool nsTreeContentView::CanDrop(int32_t aRow, int32_t aOrientation,
                                DataTransfer* aDataTransfer,
                                ErrorResult& aError) {
  return CanDrop(aRow, aOrientation, aError);
}

NS_IMETHODIMP
nsTreeContentView::CanDrop(int32_t aIndex, int32_t aOrientation,
                           DataTransfer* aDataTransfer, bool* _retval) {
  ErrorResult rv;
  *_retval = CanDrop(aIndex, aOrientation, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::Drop(int32_t aRow, int32_t aOrientation,
                             ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
  }
}

void nsTreeContentView::Drop(int32_t aRow, int32_t aOrientation,
                             DataTransfer* aDataTransfer, ErrorResult& aError) {
  Drop(aRow, aOrientation, aError);
}

NS_IMETHODIMP
nsTreeContentView::Drop(int32_t aRow, int32_t aOrientation,
                        DataTransfer* aDataTransfer) {
  ErrorResult rv;
  Drop(aRow, aOrientation, rv);
  return rv.StealNSResult();
}

int32_t nsTreeContentView::GetParentIndex(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return 0;
  }

  return mRows[aRow]->mParentIndex;
}

NS_IMETHODIMP
nsTreeContentView::GetParentIndex(int32_t aRowIndex, int32_t* _retval) {
  ErrorResult rv;
  *_retval = GetParentIndex(aRowIndex, rv);
  return rv.StealNSResult();
}

bool nsTreeContentView::HasNextSibling(int32_t aRow, int32_t aAfterIndex,
                                       ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return false;
  }

  // We have a next sibling if the row is not the last in the subtree.
  int32_t parentIndex = mRows[aRow]->mParentIndex;
  if (parentIndex < 0) {
    return uint32_t(aRow) < mRows.Length() - 1;
  }

  // Compute the last index in this subtree.
  int32_t lastIndex = parentIndex + (mRows[parentIndex])->mSubtreeSize;
  Row* row = mRows[lastIndex].get();
  while (row->mParentIndex != parentIndex) {
    lastIndex = row->mParentIndex;
    row = mRows[lastIndex].get();
  }

  return aRow < lastIndex;
}

NS_IMETHODIMP
nsTreeContentView::HasNextSibling(int32_t aRowIndex, int32_t aAfterIndex,
                                  bool* _retval) {
  ErrorResult rv;
  *_retval = HasNextSibling(aRowIndex, aAfterIndex, rv);
  return rv.StealNSResult();
}

int32_t nsTreeContentView::GetLevel(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return 0;
  }

  int32_t level = 0;
  Row* row = mRows[aRow].get();
  while (row->mParentIndex >= 0) {
    level++;
    row = mRows[row->mParentIndex].get();
  }
  return level;
}

NS_IMETHODIMP
nsTreeContentView::GetLevel(int32_t aIndex, int32_t* _retval) {
  ErrorResult rv;
  *_retval = GetLevel(aIndex, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::GetImageSrc(int32_t aRow, nsTreeColumn& aColumn,
                                    nsAString& aSrc, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();

  nsIContent* realRow =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
  if (realRow) {
    Element* cell = GetCell(realRow, aColumn);
    if (cell) cell->GetAttr(nsGkAtoms::src, aSrc);
  }
}

NS_IMETHODIMP
nsTreeContentView::GetImageSrc(int32_t aRow, nsTreeColumn* aCol,
                               nsAString& _retval) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  GetImageSrc(aRow, *aCol, _retval, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::GetCellValue(int32_t aRow, nsTreeColumn& aColumn,
                                     nsAString& aValue, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();

  nsIContent* realRow =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
  if (realRow) {
    Element* cell = GetCell(realRow, aColumn);
    if (cell) cell->GetAttr(nsGkAtoms::value, aValue);
  }
}

NS_IMETHODIMP
nsTreeContentView::GetCellValue(int32_t aRow, nsTreeColumn* aCol,
                                nsAString& _retval) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  GetCellValue(aRow, *aCol, _retval, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::GetCellText(int32_t aRow, nsTreeColumn& aColumn,
                                    nsAString& aText, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();

  // Check for a "label" attribute - this is valid on an <treeitem>
  // with a single implied column.
  if (row->mContent->GetAttr(nsGkAtoms::label, aText) && !aText.IsEmpty()) {
    return;
  }

  if (row->mContent->IsXULElement(nsGkAtoms::treeitem)) {
    nsIContent* realRow =
        nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
    if (realRow) {
      Element* cell = GetCell(realRow, aColumn);
      if (cell) cell->GetAttr(nsGkAtoms::label, aText);
    }
  }
}

NS_IMETHODIMP
nsTreeContentView::GetCellText(int32_t aRow, nsTreeColumn* aCol,
                               nsAString& _retval) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  GetCellText(aRow, *aCol, _retval, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::SetTree(XULTreeElement* aTree, ErrorResult& aError) {
  aError = SetTree(aTree);
}

NS_IMETHODIMP
nsTreeContentView::SetTree(XULTreeElement* aTree) {
  ClearRows();

  mTree = aTree;

  if (aTree) {
    // Add ourselves to document's observers.
    Document* document = mTree->GetComposedDoc();
    if (document) {
      document->AddObserver(this);
      mDocument = document;
    }

    RefPtr<dom::Element> bodyElement = mTree->GetTreeBody();
    if (bodyElement) {
      mBody = std::move(bodyElement);
      int32_t index = 0;
      Serialize(mBody, -1, &index, mRows);
    }
  }

  return NS_OK;
}

void nsTreeContentView::ToggleOpenState(int32_t aRow, ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  // We don't serialize content right here, since content might be generated
  // lazily.
  Row* row = mRows[aRow].get();

  if (row->IsOpen())
    row->mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"false"_ns,
                           true);
  else
    row->mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"true"_ns,
                           true);
}

NS_IMETHODIMP
nsTreeContentView::ToggleOpenState(int32_t aIndex) {
  ErrorResult rv;
  ToggleOpenState(aIndex, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::CycleHeader(nsTreeColumn& aColumn,
                                    ErrorResult& aError) {
  if (!mTree) return;

  RefPtr<Element> column = aColumn.Element();
  nsAutoString sort;
  column->GetAttr(nsGkAtoms::sort, sort);
  if (!sort.IsEmpty()) {
    nsAutoString sortdirection;
    static Element::AttrValuesArray strings[] = {
        nsGkAtoms::ascending, nsGkAtoms::descending, nullptr};
    switch (column->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::sortDirection,
                                    strings, eCaseMatters)) {
      case 0:
        sortdirection.AssignLiteral("descending");
        break;
      case 1:
        sortdirection.AssignLiteral("natural");
        break;
      default:
        sortdirection.AssignLiteral("ascending");
        break;
    }

    nsAutoString hints;
    column->GetAttr(nsGkAtoms::sorthints, hints);
    sortdirection.Append(' ');
    sortdirection += hints;

    XULWidgetSort(mTree, sort, sortdirection);
  }
}

NS_IMETHODIMP
nsTreeContentView::CycleHeader(nsTreeColumn* aCol) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  CycleHeader(*aCol, rv);
  return rv.StealNSResult();
}

NS_IMETHODIMP
nsTreeContentView::SelectionChangedXPCOM() { return NS_OK; }

NS_IMETHODIMP
nsTreeContentView::CycleCell(int32_t aRow, nsTreeColumn* aCol) { return NS_OK; }

bool nsTreeContentView::IsEditable(int32_t aRow, nsTreeColumn& aColumn,
                                   ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return false;
  }

  Row* row = mRows[aRow].get();

  nsIContent* realRow =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
  if (realRow) {
    Element* cell = GetCell(realRow, aColumn);
    if (cell && cell->AttrValueIs(kNameSpaceID_None, nsGkAtoms::editable,
                                  nsGkAtoms::_false, eCaseMatters)) {
      return false;
    }
  }

  return true;
}

NS_IMETHODIMP
nsTreeContentView::IsEditable(int32_t aRow, nsTreeColumn* aCol, bool* _retval) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  *_retval = IsEditable(aRow, *aCol, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::SetCellValue(int32_t aRow, nsTreeColumn& aColumn,
                                     const nsAString& aValue,
                                     ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();

  nsIContent* realRow =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
  if (realRow) {
    Element* cell = GetCell(realRow, aColumn);
    if (cell) cell->SetAttr(kNameSpaceID_None, nsGkAtoms::value, aValue, true);
  }
}

NS_IMETHODIMP
nsTreeContentView::SetCellValue(int32_t aRow, nsTreeColumn* aCol,
                                const nsAString& aValue) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  SetCellValue(aRow, *aCol, aValue, rv);
  return rv.StealNSResult();
}

void nsTreeContentView::SetCellText(int32_t aRow, nsTreeColumn& aColumn,
                                    const nsAString& aValue,
                                    ErrorResult& aError) {
  if (!IsValidRowIndex(aRow)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return;
  }

  Row* row = mRows[aRow].get();

  nsIContent* realRow =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treerow);
  if (realRow) {
    Element* cell = GetCell(realRow, aColumn);
    if (cell) cell->SetAttr(kNameSpaceID_None, nsGkAtoms::label, aValue, true);
  }
}

NS_IMETHODIMP
nsTreeContentView::SetCellText(int32_t aRow, nsTreeColumn* aCol,
                               const nsAString& aValue) {
  NS_ENSURE_ARG(aCol);

  ErrorResult rv;
  SetCellText(aRow, *aCol, aValue, rv);
  return rv.StealNSResult();
}

Element* nsTreeContentView::GetItemAtIndex(int32_t aIndex,
                                           ErrorResult& aError) {
  if (!IsValidRowIndex(aIndex)) {
    aError.Throw(NS_ERROR_INVALID_ARG);
    return nullptr;
  }

  return mRows[aIndex]->mContent;
}

int32_t nsTreeContentView::GetIndexOfItem(Element* aItem) {
  return FindContent(aItem);
}

void nsTreeContentView::AttributeChanged(dom::Element* aElement,
                                         int32_t aNameSpaceID,
                                         nsAtom* aAttribute, int32_t aModType,
                                         const nsAttrValue* aOldValue) {
  // Lots of codepaths under here that do all sorts of stuff, so be safe.
  nsCOMPtr<nsIMutationObserver> kungFuDeathGrip(this);

  // Make sure this notification concerns us.
  // First check the tag to see if it's one that we care about.
  if (aElement == mTree || aElement == mBody) {
    mTree->ClearStyleAndImageCaches();
    mTree->Invalidate();
  }

  // We don't consider non-XUL nodes.
  nsIContent* parent = nullptr;
  if (!aElement->IsXULElement() ||
      ((parent = aElement->GetParent()) && !parent->IsXULElement())) {
    return;
  }
  if (!aElement->IsAnyOfXULElements(nsGkAtoms::treecol, nsGkAtoms::treeitem,
                                    nsGkAtoms::treeseparator,
                                    nsGkAtoms::treerow, nsGkAtoms::treecell)) {
    return;
  }

  // If we have a legal tag, go up to the tree/select and make sure
  // that it's ours.

  for (nsIContent* element = aElement; element != mBody;
       element = element->GetParent()) {
    if (!element) return;                                // this is not for us
    if (element->IsXULElement(nsGkAtoms::tree)) return;  // this is not for us
  }

  // Handle changes of the hidden attribute.
  if (aAttribute == nsGkAtoms::hidden &&
      aElement->IsAnyOfXULElements(nsGkAtoms::treeitem,
                                   nsGkAtoms::treeseparator)) {
    bool hidden = aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden,
                                        nsGkAtoms::_true, eCaseMatters);

    int32_t index = FindContent(aElement);
    if (hidden && index >= 0) {
      // Hide this row along with its children.
      int32_t count = RemoveRow(index);
      if (mTree) mTree->RowCountChanged(index, -count);
    } else if (!hidden && index < 0) {
      // Show this row along with its children.
      nsCOMPtr<nsIContent> parent = aElement->GetParent();
      if (parent) {
        InsertRowFor(parent, aElement);
      }
    }

    return;
  }

  if (aElement->IsXULElement(nsGkAtoms::treecol)) {
    if (aAttribute == nsGkAtoms::properties) {
      if (mTree) {
        RefPtr<nsTreeColumns> cols = mTree->GetColumns();
        if (cols) {
          RefPtr<nsTreeColumn> col = cols->GetColumnFor(aElement);
          mTree->InvalidateColumn(col);
        }
      }
    }
  } else if (aElement->IsXULElement(nsGkAtoms::treeitem)) {
    int32_t index = FindContent(aElement);
    if (index >= 0) {
      Row* row = mRows[index].get();
      if (aAttribute == nsGkAtoms::container) {
        bool isContainer =
            aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::container,
                                  nsGkAtoms::_true, eCaseMatters);
        row->SetContainer(isContainer);
        if (mTree) mTree->InvalidateRow(index);
      } else if (aAttribute == nsGkAtoms::open) {
        bool isOpen = aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::open,
                                            nsGkAtoms::_true, eCaseMatters);
        bool wasOpen = row->IsOpen();
        if (!isOpen && wasOpen)
          CloseContainer(index);
        else if (isOpen && !wasOpen)
          OpenContainer(index);
      } else if (aAttribute == nsGkAtoms::empty) {
        bool isEmpty =
            aElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::empty,
                                  nsGkAtoms::_true, eCaseMatters);
        row->SetEmpty(isEmpty);
        if (mTree) mTree->InvalidateRow(index);
      }
    }
  } else if (aElement->IsXULElement(nsGkAtoms::treeseparator)) {
    int32_t index = FindContent(aElement);
    if (index >= 0) {
      if (aAttribute == nsGkAtoms::properties && mTree) {
        mTree->InvalidateRow(index);
      }
    }
  } else if (aElement->IsXULElement(nsGkAtoms::treerow)) {
    if (aAttribute == nsGkAtoms::properties) {
      nsCOMPtr<nsIContent> parent = aElement->GetParent();
      if (parent) {
        int32_t index = FindContent(parent);
        if (index >= 0 && mTree) {
          mTree->InvalidateRow(index);
        }
      }
    }
  } else if (aElement->IsXULElement(nsGkAtoms::treecell)) {
    if (aAttribute == nsGkAtoms::properties || aAttribute == nsGkAtoms::mode ||
        aAttribute == nsGkAtoms::src || aAttribute == nsGkAtoms::value ||
        aAttribute == nsGkAtoms::label) {
      nsIContent* parent = aElement->GetParent();
      if (parent) {
        nsCOMPtr<nsIContent> grandParent = parent->GetParent();
        if (grandParent && grandParent->IsXULElement()) {
          int32_t index = FindContent(grandParent);
          if (index >= 0 && mTree) {
            // XXX Should we make an effort to invalidate only cell ?
            mTree->InvalidateRow(index);
          }
        }
      }
    }
  }
}

void nsTreeContentView::ContentAppended(nsIContent* aFirstNewContent) {
  for (nsIContent* cur = aFirstNewContent; cur; cur = cur->GetNextSibling()) {
    // Our contentinserted doesn't use the index
    ContentInserted(cur);
  }
}

void nsTreeContentView::ContentInserted(nsIContent* aChild) {
  NS_ASSERTION(aChild, "null ptr");
  nsIContent* container = aChild->GetParent();

  // Make sure this notification concerns us.
  // First check the tag to see if it's one that we care about.

  // Don't allow non-XUL nodes.
  if (!aChild->IsXULElement() || !container->IsXULElement()) return;

  if (!aChild->IsAnyOfXULElements(nsGkAtoms::treeitem, nsGkAtoms::treeseparator,
                                  nsGkAtoms::treechildren, nsGkAtoms::treerow,
                                  nsGkAtoms::treecell)) {
    return;
  }

  // If we have a legal tag, go up to the tree/select and make sure
  // that it's ours.

  for (nsIContent* element = container; element != mBody;
       element = element->GetParent()) {
    if (!element) return;                                // this is not for us
    if (element->IsXULElement(nsGkAtoms::tree)) return;  // this is not for us
  }

  // Lots of codepaths under here that do all sorts of stuff, so be safe.
  nsCOMPtr<nsIMutationObserver> kungFuDeathGrip(this);

  if (aChild->IsXULElement(nsGkAtoms::treechildren)) {
    int32_t index = FindContent(container);
    if (index >= 0) {
      Row* row = mRows[index].get();
      row->SetEmpty(false);
      if (mTree) mTree->InvalidateRow(index);
      if (row->IsContainer() && row->IsOpen()) {
        int32_t count = EnsureSubtree(index);
        if (mTree) mTree->RowCountChanged(index + 1, count);
      }
    }
  } else if (aChild->IsAnyOfXULElements(nsGkAtoms::treeitem,
                                        nsGkAtoms::treeseparator)) {
    InsertRowFor(container, aChild);
  } else if (aChild->IsXULElement(nsGkAtoms::treerow)) {
    int32_t index = FindContent(container);
    if (index >= 0 && mTree) mTree->InvalidateRow(index);
  } else if (aChild->IsXULElement(nsGkAtoms::treecell)) {
    nsCOMPtr<nsIContent> parent = container->GetParent();
    if (parent) {
      int32_t index = FindContent(parent);
      if (index >= 0 && mTree) mTree->InvalidateRow(index);
    }
  }
}

void nsTreeContentView::ContentRemoved(nsIContent* aChild,
                                       nsIContent* aPreviousSibling) {
  NS_ASSERTION(aChild, "null ptr");

  nsIContent* container = aChild->GetParent();
  // Make sure this notification concerns us.
  // First check the tag to see if it's one that we care about.

  // We don't consider non-XUL nodes.
  if (!aChild->IsXULElement() || !container->IsXULElement()) return;

  if (!aChild->IsAnyOfXULElements(nsGkAtoms::treeitem, nsGkAtoms::treeseparator,
                                  nsGkAtoms::treechildren, nsGkAtoms::treerow,
                                  nsGkAtoms::treecell)) {
    return;
  }

  // If we have a legal tag, go up to the tree/select and make sure
  // that it's ours.

  for (nsIContent* element = container; element != mBody;
       element = element->GetParent()) {
    if (!element) return;                                // this is not for us
    if (element->IsXULElement(nsGkAtoms::tree)) return;  // this is not for us
  }

  // Lots of codepaths under here that do all sorts of stuff, so be safe.
  nsCOMPtr<nsIMutationObserver> kungFuDeathGrip(this);

  if (aChild->IsXULElement(nsGkAtoms::treechildren)) {
    int32_t index = FindContent(container);
    if (index >= 0) {
      Row* row = mRows[index].get();
      row->SetEmpty(true);
      int32_t count = RemoveSubtree(index);
      // Invalidate also the row to update twisty.
      if (mTree) {
        mTree->InvalidateRow(index);
        mTree->RowCountChanged(index + 1, -count);
      }
    }
  } else if (aChild->IsAnyOfXULElements(nsGkAtoms::treeitem,
                                        nsGkAtoms::treeseparator)) {
    int32_t index = FindContent(aChild);
    if (index >= 0) {
      int32_t count = RemoveRow(index);
      if (mTree) mTree->RowCountChanged(index, -count);
    }
  } else if (aChild->IsXULElement(nsGkAtoms::treerow)) {
    int32_t index = FindContent(container);
    if (index >= 0 && mTree) mTree->InvalidateRow(index);
  } else if (aChild->IsXULElement(nsGkAtoms::treecell)) {
    nsCOMPtr<nsIContent> parent = container->GetParent();
    if (parent) {
      int32_t index = FindContent(parent);
      if (index >= 0 && mTree) mTree->InvalidateRow(index);
    }
  }
}

void nsTreeContentView::NodeWillBeDestroyed(nsINode* aNode) {
  // XXXbz do we need this strong ref?  Do we drop refs to self in ClearRows?
  nsCOMPtr<nsIMutationObserver> kungFuDeathGrip(this);
  ClearRows();
}

// Recursively serialize content, starting with aContent.
void nsTreeContentView::Serialize(nsIContent* aContent, int32_t aParentIndex,
                                  int32_t* aIndex,
                                  nsTArray<UniquePtr<Row>>& aRows) {
  // Don't allow non-XUL nodes.
  if (!aContent->IsXULElement()) return;

  dom::FlattenedChildIterator iter(aContent);
  for (nsIContent* content = iter.GetNextChild(); content;
       content = iter.GetNextChild()) {
    int32_t count = aRows.Length();

    if (content->IsXULElement(nsGkAtoms::treeitem)) {
      SerializeItem(content->AsElement(), aParentIndex, aIndex, aRows);
    } else if (content->IsXULElement(nsGkAtoms::treeseparator)) {
      SerializeSeparator(content->AsElement(), aParentIndex, aIndex, aRows);
    }

    *aIndex += aRows.Length() - count;
  }
}

void nsTreeContentView::SerializeItem(Element* aContent, int32_t aParentIndex,
                                      int32_t* aIndex,
                                      nsTArray<UniquePtr<Row>>& aRows) {
  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden,
                            nsGkAtoms::_true, eCaseMatters))
    return;

  aRows.AppendElement(MakeUnique<Row>(aContent, aParentIndex));
  Row* row = aRows.LastElement().get();

  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::container,
                            nsGkAtoms::_true, eCaseMatters)) {
    row->SetContainer(true);
    if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::open,
                              nsGkAtoms::_true, eCaseMatters)) {
      row->SetOpen(true);
      nsIContent* child =
          nsTreeUtils::GetImmediateChild(aContent, nsGkAtoms::treechildren);
      if (child && child->IsXULElement()) {
        // Now, recursively serialize our child.
        int32_t count = aRows.Length();
        int32_t index = 0;
        Serialize(child, aParentIndex + *aIndex + 1, &index, aRows);
        row->mSubtreeSize += aRows.Length() - count;
      } else
        row->SetEmpty(true);
    } else if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::empty,
                                     nsGkAtoms::_true, eCaseMatters)) {
      row->SetEmpty(true);
    }
  }
}

void nsTreeContentView::SerializeSeparator(Element* aContent,
                                           int32_t aParentIndex,
                                           int32_t* aIndex,
                                           nsTArray<UniquePtr<Row>>& aRows) {
  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden,
                            nsGkAtoms::_true, eCaseMatters))
    return;

  auto row = MakeUnique<Row>(aContent, aParentIndex);
  row->SetSeparator(true);
  aRows.AppendElement(std::move(row));
}

void nsTreeContentView::GetIndexInSubtree(nsIContent* aContainer,
                                          nsIContent* aContent,
                                          int32_t* aIndex) {
  if (!aContainer->IsXULElement()) return;

  for (nsIContent* content = aContainer->GetFirstChild(); content;
       content = content->GetNextSibling()) {
    if (content == aContent) break;

    if (content->IsXULElement(nsGkAtoms::treeitem)) {
      if (!content->AsElement()->AttrValueIs(kNameSpaceID_None,
                                             nsGkAtoms::hidden,
                                             nsGkAtoms::_true, eCaseMatters)) {
        (*aIndex)++;
        if (content->AsElement()->AttrValueIs(kNameSpaceID_None,
                                              nsGkAtoms::container,
                                              nsGkAtoms::_true, eCaseMatters) &&
            content->AsElement()->AttrValueIs(kNameSpaceID_None,
                                              nsGkAtoms::open, nsGkAtoms::_true,
                                              eCaseMatters)) {
          nsIContent* child =
              nsTreeUtils::GetImmediateChild(content, nsGkAtoms::treechildren);
          if (child && child->IsXULElement())
            GetIndexInSubtree(child, aContent, aIndex);
        }
      }
    } else if (content->IsXULElement(nsGkAtoms::treeseparator)) {
      if (!content->AsElement()->AttrValueIs(kNameSpaceID_None,
                                             nsGkAtoms::hidden,
                                             nsGkAtoms::_true, eCaseMatters))
        (*aIndex)++;
    }
  }
}

int32_t nsTreeContentView::EnsureSubtree(int32_t aIndex) {
  Row* row = mRows[aIndex].get();

  nsIContent* child;
  child =
      nsTreeUtils::GetImmediateChild(row->mContent, nsGkAtoms::treechildren);
  if (!child || !child->IsXULElement()) {
    return 0;
  }

  AutoTArray<UniquePtr<Row>, 8> rows;
  int32_t index = 0;
  Serialize(child, aIndex, &index, rows);
  // Insert |rows| into |mRows| at position |aIndex|, by first creating empty
  // UniquePtr entries and then Move'ing |rows|'s entries into them. (Note
  // that we can't simply use InsertElementsAt with an array argument, since
  // the destination can't steal ownership from its const source argument.)
  UniquePtr<Row>* newRows = mRows.InsertElementsAt(aIndex + 1, rows.Length());
  for (nsTArray<Row>::index_type i = 0; i < rows.Length(); i++) {
    newRows[i] = std::move(rows[i]);
  }
  int32_t count = rows.Length();

  row->mSubtreeSize += count;
  UpdateSubtreeSizes(row->mParentIndex, count);

  // Update parent indexes, but skip newly added rows.
  // They already have correct values.
  UpdateParentIndexes(aIndex, count + 1, count);

  return count;
}

int32_t nsTreeContentView::RemoveSubtree(int32_t aIndex) {
  Row* row = mRows[aIndex].get();
  int32_t count = row->mSubtreeSize;

  mRows.RemoveElementsAt(aIndex + 1, count);

  row->mSubtreeSize -= count;
  UpdateSubtreeSizes(row->mParentIndex, -count);

  UpdateParentIndexes(aIndex, 0, -count);

  return count;
}

void nsTreeContentView::InsertRowFor(nsIContent* aParent, nsIContent* aChild) {
  int32_t grandParentIndex = -1;
  bool insertRow = false;

  nsCOMPtr<nsIContent> grandParent = aParent->GetParent();

  if (grandParent->IsXULElement(nsGkAtoms::tree)) {
    // Allow insertion to the outermost container.
    insertRow = true;
  } else {
    // Test insertion to an inner container.

    // First try to find this parent in our array of rows, if we find one
    // we can be sure that all other parents are open too.
    grandParentIndex = FindContent(grandParent);
    if (grandParentIndex >= 0) {
      // Got it, now test if it is open.
      if (mRows[grandParentIndex]->IsOpen()) insertRow = true;
    }
  }

  if (insertRow) {
    int32_t index = 0;
    GetIndexInSubtree(aParent, aChild, &index);

    int32_t count = InsertRow(grandParentIndex, index, aChild);
    if (mTree) mTree->RowCountChanged(grandParentIndex + index + 1, count);
  }
}

int32_t nsTreeContentView::InsertRow(int32_t aParentIndex, int32_t aIndex,
                                     nsIContent* aContent) {
  AutoTArray<UniquePtr<Row>, 8> rows;
  if (aContent->IsXULElement(nsGkAtoms::treeitem)) {
    SerializeItem(aContent->AsElement(), aParentIndex, &aIndex, rows);
  } else if (aContent->IsXULElement(nsGkAtoms::treeseparator)) {
    SerializeSeparator(aContent->AsElement(), aParentIndex, &aIndex, rows);
  }

  // We can't use InsertElementsAt since the destination can't steal
  // ownership from its const source argument.
  int32_t count = rows.Length();
  for (nsTArray<Row>::index_type i = 0; i < size_t(count); i++) {
    mRows.InsertElementAt(aParentIndex + aIndex + i + 1, std::move(rows[i]));
  }

  UpdateSubtreeSizes(aParentIndex, count);

  // Update parent indexes, but skip added rows.
  // They already have correct values.
  UpdateParentIndexes(aParentIndex + aIndex, count + 1, count);

  return count;
}

int32_t nsTreeContentView::RemoveRow(int32_t aIndex) {
  Row* row = mRows[aIndex].get();
  int32_t count = row->mSubtreeSize + 1;
  int32_t parentIndex = row->mParentIndex;

  mRows.RemoveElementsAt(aIndex, count);

  UpdateSubtreeSizes(parentIndex, -count);

  UpdateParentIndexes(aIndex, 0, -count);

  return count;
}

void nsTreeContentView::ClearRows() {
  mRows.Clear();
  mBody = nullptr;
  // Remove ourselves from mDocument's observers.
  if (mDocument) {
    mDocument->RemoveObserver(this);
    mDocument = nullptr;
  }
}

void nsTreeContentView::OpenContainer(int32_t aIndex) {
  Row* row = mRows[aIndex].get();
  row->SetOpen(true);

  int32_t count = EnsureSubtree(aIndex);
  if (mTree) {
    mTree->InvalidateRow(aIndex);
    mTree->RowCountChanged(aIndex + 1, count);
  }
}

void nsTreeContentView::CloseContainer(int32_t aIndex) {
  Row* row = mRows[aIndex].get();
  row->SetOpen(false);

  int32_t count = RemoveSubtree(aIndex);
  if (mTree) {
    mTree->InvalidateRow(aIndex);
    mTree->RowCountChanged(aIndex + 1, -count);
  }
}

int32_t nsTreeContentView::FindContent(nsIContent* aContent) {
  for (uint32_t i = 0; i < mRows.Length(); i++) {
    if (mRows[i]->mContent == aContent) {
      return i;
    }
  }

  return -1;
}

void nsTreeContentView::UpdateSubtreeSizes(int32_t aParentIndex,
                                           int32_t count) {
  while (aParentIndex >= 0) {
    Row* row = mRows[aParentIndex].get();
    row->mSubtreeSize += count;
    aParentIndex = row->mParentIndex;
  }
}

void nsTreeContentView::UpdateParentIndexes(int32_t aIndex, int32_t aSkip,
                                            int32_t aCount) {
  int32_t count = mRows.Length();
  for (int32_t i = aIndex + aSkip; i < count; i++) {
    Row* row = mRows[i].get();
    if (row->mParentIndex > aIndex) {
      row->mParentIndex += aCount;
    }
  }
}

Element* nsTreeContentView::GetCell(nsIContent* aContainer,
                                    nsTreeColumn& aCol) {
  int32_t colIndex(aCol.GetIndex());

  // Traverse through cells, try to find the cell by index in a row.
  Element* result = nullptr;
  int32_t j = 0;
  dom::FlattenedChildIterator iter(aContainer);
  for (nsIContent* cell = iter.GetNextChild(); cell;
       cell = iter.GetNextChild()) {
    if (cell->IsXULElement(nsGkAtoms::treecell)) {
      if (j == colIndex) {
        result = cell->AsElement();
        break;
      }
      j++;
    }
  }

  return result;
}

bool nsTreeContentView::IsValidRowIndex(int32_t aRowIndex) {
  return aRowIndex >= 0 && aRowIndex < int32_t(mRows.Length());
}