DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (2a29ee0adb31)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "msgCore.h"
#include "nsMsgThreadedDBView.h"
#include "nsIMsgHdr.h"
#include "nsIMsgThread.h"
#include "nsIDBFolderInfo.h"
#include "nsIMsgSearchSession.h"
#include "nsMsgMessageFlags.h"

// Allocate this more to avoid reallocation on new mail.
#define MSGHDR_CACHE_LOOK_AHEAD_SIZE  25
// Max msghdr cache entries.
#define MSGHDR_CACHE_MAX_SIZE         8192
#define MSGHDR_CACHE_DEFAULT_SIZE     100

nsMsgThreadedDBView::nsMsgThreadedDBView()
{
  /* member initializers and constructor code */
  m_havePrevView = false;
}

nsMsgThreadedDBView::~nsMsgThreadedDBView()
{
  /* destructor code */
}

NS_IMETHODIMP
nsMsgThreadedDBView::Open(nsIMsgFolder *folder,
                          nsMsgViewSortTypeValue sortType,
                          nsMsgViewSortOrderValue sortOrder,
                          nsMsgViewFlagsTypeValue viewFlags,
                          int32_t *pCount)
{
  nsresult rv = nsMsgDBView::Open(folder, sortType, sortOrder, viewFlags, pCount);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!m_db)
    return NS_ERROR_NULL_POINTER;

  // Preset msg hdr cache size for performance reason.
  int32_t totalMessages, unreadMessages;
  nsCOMPtr <nsIDBFolderInfo> dbFolderInfo;
  PersistFolderInfo(getter_AddRefs(dbFolderInfo));
  NS_ENSURE_SUCCESS(rv, rv);

  // Save off sort type and order, view type and flags.
  dbFolderInfo->GetNumUnreadMessages(&unreadMessages);
  dbFolderInfo->GetNumMessages(&totalMessages);
  if (m_viewFlags & nsMsgViewFlagsType::kUnreadOnly)
  {
    // Set unread msg size + extra entries to avoid reallocation on new mail.
    totalMessages = (uint32_t)unreadMessages+MSGHDR_CACHE_LOOK_AHEAD_SIZE;
  }
  else
  {
    if (totalMessages > MSGHDR_CACHE_MAX_SIZE)
      // Use max default.
      totalMessages = MSGHDR_CACHE_MAX_SIZE;
    else if (totalMessages > 0)
      // Allocate extra entries to avoid reallocation on new mail.
      totalMessages += MSGHDR_CACHE_LOOK_AHEAD_SIZE;
  }

  // If total messages is 0, then we probably don't have any idea how many
  // headers are in the db so we have no business setting the cache size.
  if (totalMessages > 0)
    m_db->SetMsgHdrCacheSize((uint32_t)totalMessages);

  if (pCount)
    *pCount = 0;

  rv = InitThreadedView(pCount);

  // This is a hack, but we're trying to find a way to correct
  // incorrect total and unread msg counts w/o paying a big
  // performance penalty. So, if we're not threaded, just add
  // up the total and unread messages in the view and see if that
  // matches what the db totals say. Except ignored threads are
  // going to throw us off...hmm. Unless we just look at the
  // unread counts which is what mostly tweaks people anyway...
  int32_t unreadMsgsInView = 0;
  if (!(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay))
  {
    for (uint32_t i = m_flags.Length(); i > 0; )
    {
      if (!(m_flags[--i] & nsMsgMessageFlags::Read))
        ++unreadMsgsInView;
    }

    if (unreadMessages != unreadMsgsInView)
      m_db->SyncCounts();
  }

  m_db->SetMsgHdrCacheSize(MSGHDR_CACHE_DEFAULT_SIZE);

  return rv;
}

NS_IMETHODIMP
nsMsgThreadedDBView::Close()
{
  return nsMsgDBView::Close();
}

nsresult
nsMsgThreadedDBView::InitThreadedView(int32_t *pCount)
{
  nsresult rv;

  m_keys.Clear();
  m_flags.Clear();
  m_levels.Clear();
  m_prevKeys.Clear();
  m_prevFlags.Clear();
  m_prevLevels.Clear();
  m_havePrevView = false;
  nsresult getSortrv = NS_OK;
  // XXX TODO m_db->GetSortInfo(&sortType, &sortOrder);

  // List all the ids into m_keys.
  nsMsgKey startMsg = 0;
  do
  {
    const int32_t kIdChunkSize = 400;
    int32_t  numListed = 0;
    nsMsgKey idArray[kIdChunkSize];
    int32_t  flagArray[kIdChunkSize];
    char     levelArray[kIdChunkSize];

    rv = ListThreadIds(&startMsg,
                       (m_viewFlags & nsMsgViewFlagsType::kUnreadOnly) != 0,
                       idArray,
                       flagArray,
                       levelArray,
                       kIdChunkSize,
                       &numListed,
                       nullptr);

    if (NS_SUCCEEDED(rv))
    {
      int32_t numAdded = AddKeys(idArray, flagArray, levelArray, m_sortType, numListed);
      if (pCount)
        *pCount += numAdded;
    }

  } while (NS_SUCCEEDED(rv) && startMsg != nsMsgKey_None);

  if (NS_SUCCEEDED(getSortrv))
  {
    rv = InitSort(m_sortType, m_sortOrder);
    SaveSortInfo(m_sortType, m_sortOrder);

  }

  return rv;
}

nsresult
nsMsgThreadedDBView::SortThreads(nsMsgViewSortTypeValue sortType,
                                 nsMsgViewSortOrderValue sortOrder)
{
  NS_ASSERTION(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay,
               "trying to sort unthreaded threads");

  uint32_t numThreads = 0;
  // The idea here is that copy the current view, then build up an m_keys and
  // m_flags array of just the top level messages in the view, and then call
  // nsMsgDBView::Sort(sortType, sortOrder).
  // Then, we expand the threads in the result array that were expanded in the
  // original view (perhaps by copying from the original view, but more likely
  // just be calling expand).
  for (uint32_t i = 0; i < m_keys.Length(); i++)
  {
    if (m_flags[i] & MSG_VIEW_FLAG_ISTHREAD)
    {
      if (numThreads < i)
      {
        m_keys[numThreads] = m_keys[i];
        m_flags[numThreads] = m_flags[i];
      }

      m_levels[numThreads] = 0;
      numThreads++;
    }
  }

  m_keys.SetLength(numThreads);
  m_flags.SetLength(numThreads);
  m_levels.SetLength(numThreads);
  //m_viewFlags &= ~nsMsgViewFlagsType::kThreadedDisplay;
  m_sortType = nsMsgViewSortType::byNone; // sort from scratch
  nsMsgDBView::Sort(sortType, sortOrder);
  m_viewFlags |= nsMsgViewFlagsType::kThreadedDisplay;
  SetSuppressChangeNotifications(true);

  // Loop through the original array, for each thread that's expanded,
  // find it in the new array and expand the thread. We have to update
  // MSG_VIEW_FLAG_HAS_CHILDREN because we may be going from a flat sort,
  // which doesn't maintain that flag, to a threaded sort, which requires
  // that flag.
  for (uint32_t j = 0; j < m_keys.Length(); j++)
  {
    uint32_t flags = m_flags[j];
    if ((flags & (MSG_VIEW_FLAG_HASCHILDREN |
                  nsMsgMessageFlags::Elided)) == MSG_VIEW_FLAG_HASCHILDREN)
    {
      uint32_t numExpanded;
      m_flags[j] = flags | nsMsgMessageFlags::Elided;
      ExpandByIndex(j, &numExpanded);
      j += numExpanded;
      if (numExpanded > 0)
        m_flags[j - numExpanded] = flags | MSG_VIEW_FLAG_HASCHILDREN;
    }
    else if (flags & MSG_VIEW_FLAG_ISTHREAD &&
             !(flags & MSG_VIEW_FLAG_HASCHILDREN))
    {
      nsCOMPtr <nsIMsgDBHdr> msgHdr;
      nsCOMPtr <nsIMsgThread> pThread;
      m_db->GetMsgHdrForKey(m_keys[j], getter_AddRefs(msgHdr));
      if (msgHdr)
      {
        m_db->GetThreadContainingMsgHdr(msgHdr, getter_AddRefs(pThread));
        if (pThread)
        {
          uint32_t numChildren;
          pThread->GetNumChildren(&numChildren);
          if (numChildren > 1)
            m_flags[j] = flags | MSG_VIEW_FLAG_HASCHILDREN | nsMsgMessageFlags::Elided;
        }
      }
    }
  }

  SetSuppressChangeNotifications(false);

  return NS_OK;
}

int32_t
nsMsgThreadedDBView::AddKeys(nsMsgKey *pKeys,
                             int32_t *pFlags,
                             const char *pLevels,
                             nsMsgViewSortTypeValue sortType,
                             int32_t numKeysToAdd)
{
  int32_t numAdded = 0;
  // Allocate enough space first to avoid memory allocation/deallocation.
  m_keys.SetCapacity(m_keys.Length() + numKeysToAdd);
  m_flags.SetCapacity(m_flags.Length() + numKeysToAdd);
  m_levels.SetCapacity(m_levels.Length() + numKeysToAdd);
  for (int32_t i = 0; i < numKeysToAdd; i++)
  {
    int32_t threadFlag = pFlags[i];
    int32_t flag = threadFlag;

    // Skip ignored threads.
    if ((threadFlag & nsMsgMessageFlags::Ignored) && !(m_viewFlags & nsMsgViewFlagsType::kShowIgnored))
      continue;

    // Skip ignored subthreads
    nsCOMPtr <nsIMsgDBHdr> msgHdr;
    m_db->GetMsgHdrForKey(pKeys[i], getter_AddRefs(msgHdr));
    if (!(m_viewFlags & nsMsgViewFlagsType::kShowIgnored))
    {
      bool killed;
      msgHdr->GetIsKilled(&killed);
      if (killed)
        continue;
    }

    // By default, make threads collapsed unless we're only viewing new msgs.

    if (flag & MSG_VIEW_FLAG_HASCHILDREN)
      flag |= nsMsgMessageFlags::Elided;

    // Should this be persistent? Doesn't seem to need to be.
    flag |= MSG_VIEW_FLAG_ISTHREAD;
    m_keys.AppendElement(pKeys[i]);
    m_flags.AppendElement(flag);
    m_levels.AppendElement(pLevels[i]);
    numAdded++;

    // We expand as we build the view, which allows us to insert at the end
    // of the key array, instead of the middle, and is much faster.
    if ((!(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay) ||
         m_viewFlags & nsMsgViewFlagsType::kExpandAll) &&
        flag & nsMsgMessageFlags::Elided)
    {
       ExpandByIndex(m_keys.Length() - 1, NULL);
    }
  }

  return numAdded;
}

NS_IMETHODIMP
nsMsgThreadedDBView::Sort(nsMsgViewSortTypeValue sortType,
                          nsMsgViewSortOrderValue sortOrder)
{
  nsresult rv;

  int32_t rowCountBeforeSort = GetSize();

  if (!rowCountBeforeSort)
  {
    // Still need to setup our flags even when no articles - bug 98183.
    m_sortType = sortType;
    if (sortType == nsMsgViewSortType::byThread &&
        !(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay))
    {
      SetViewFlags(m_viewFlags | nsMsgViewFlagsType::kThreadedDisplay);
    }

    SaveSortInfo(sortType, sortOrder);
    return NS_OK;
  }

  if (!m_checkedCustomColumns && CustomColumnsInSortAndNotRegistered())
    return NS_OK;

  // Sort threads by sort order.
  bool sortThreads = m_viewFlags & (nsMsgViewFlagsType::kThreadedDisplay |
                                    nsMsgViewFlagsType::kGroupBySort);

  // If sort type is by thread, and we're already threaded, change sort type
  // to byId.
  if (sortType == nsMsgViewSortType::byThread &&
      (m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay) != 0)
  {
    sortType = nsMsgViewSortType::byId;
  }

  nsMsgKey preservedKey;
  AutoTArray<nsMsgKey, 1> preservedSelection;
  SaveAndClearSelection(&preservedKey, preservedSelection);
  // If the client wants us to forget our cached id arrays, they
  // should build a new view. If this isn't good enough, we
  // need a method to do that.
  if (sortType != m_sortType || !m_sortValid || sortThreads)
  {
    SaveSortInfo(sortType, sortOrder);
    if (sortType == nsMsgViewSortType::byThread)
    {
      m_sortType = sortType;
      m_viewFlags |= nsMsgViewFlagsType::kThreadedDisplay;
      m_viewFlags &= ~nsMsgViewFlagsType::kGroupBySort;
      if ( m_havePrevView)
      {
        // Restore saved id array and flags array.
        m_keys = m_prevKeys;
        m_flags = m_prevFlags;
        m_levels = m_prevLevels;
        m_sortValid = true;

        // The sort may have changed the number of rows
        // before we restore the selection, tell the tree
        // do this before we call restore selection
        // this is safe when there is no selection.
        rv = AdjustRowCount(rowCountBeforeSort, GetSize());

        RestoreSelection(preservedKey, preservedSelection);
        if (mTree)
          mTree->Invalidate();

        return NS_OK;
      }
      else
      {
        // Set sort info in anticipation of what Init will do.
        // Build up thread list.
        InitThreadedView(nullptr);
        if (sortOrder != nsMsgViewSortOrder::ascending)
          Sort(sortType, sortOrder);

        // The sort may have changed the number of rows
        // before we update the selection, tell the tree
        // do this before we call restore selection
        // this is safe when there is no selection.
        rv = AdjustRowCount(rowCountBeforeSort, GetSize());

        RestoreSelection(preservedKey, preservedSelection);
        if (mTree)
          mTree->Invalidate();

        return NS_OK;
      }
    }
    else if (sortType  != nsMsgViewSortType::byThread &&
             (m_sortType == nsMsgViewSortType::byThread  || sortThreads)
             /* && !m_havePrevView*/)
    {
      if (sortThreads)
      {
        SortThreads(sortType, sortOrder);
        // Hack so base class won't do anything.
        sortType = nsMsgViewSortType::byThread;
      }
      else
      {
        // Going from SortByThread to non-thread sort - must build new key,
        // level, and flags arrays.
        m_prevKeys = m_keys;
        m_prevFlags = m_flags;
        m_prevLevels = m_levels;
        // Do this before we sort, so that we'll use the cheap method
        // of expanding.
        m_viewFlags &= ~(nsMsgViewFlagsType::kThreadedDisplay | nsMsgViewFlagsType::kGroupBySort);
        ExpandAll();
        // m_idArray.RemoveAll();
        // m_flags.Clear();
        m_havePrevView = true;
      }
    }
  }
  else if (m_sortOrder != sortOrder)
  {
    // Check for toggling the sort.
    nsMsgDBView::Sort(sortType, sortOrder);
  }

  if (!sortThreads)
  {
    // Call the base class in case we're not sorting by thread.
    rv = nsMsgDBView::Sort(sortType, sortOrder);
    SaveSortInfo(sortType, sortOrder);
  }

  // The sort may have changed the number of rows
  // before we restore the selection, tell the tree
  // do this before we call restore selection
  // this is safe when there is no selection.
  rv = AdjustRowCount(rowCountBeforeSort, GetSize());

  RestoreSelection(preservedKey, preservedSelection);
  if (mTree)
    mTree->Invalidate();

  NS_ENSURE_SUCCESS(rv,rv);
  return NS_OK;
}

// List the ids of the top-level thread ids starting at id == startMsg.
// This actually returns the ids of the first message in each thread.
nsresult
nsMsgThreadedDBView::ListThreadIds(nsMsgKey *startMsg,
                                   bool unreadOnly,
                                   nsMsgKey *pOutput,
                                   int32_t *pFlags,
                                   char *pLevels,
                                   int32_t numToList,
                                   int32_t *pNumListed,
                                   int32_t *pTotalHeaders)
{
  nsresult rv = NS_OK;
  // N.B..don't ret before assigning numListed to *pNumListed.
  int32_t numListed = 0;

  if (*startMsg > 0)
  {
    // For now, we'll just have to rely on the caller leaving
    // the iterator in the right place.
    NS_ASSERTION(m_threadEnumerator != nullptr, "where's our iterator?");
  }
  else
  {
    NS_ASSERTION(m_db, "no db");
    if (!m_db)
      return NS_ERROR_UNEXPECTED;

    rv = m_db->EnumerateThreads(getter_AddRefs(m_threadEnumerator));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  bool hasMore = false;

  nsCOMPtr <nsIMsgThread> threadHdr ;
  int32_t threadsRemoved = 0;
  while (numListed < numToList &&
         NS_SUCCEEDED(rv = m_threadEnumerator->HasMoreElements(&hasMore)) &&
         hasMore)
  {
    nsCOMPtr <nsISupports> supports;
    rv = m_threadEnumerator->GetNext(getter_AddRefs(supports));
    if (NS_FAILED(rv))
    {
      threadHdr = nullptr;
      break;
    }

    threadHdr = do_QueryInterface(supports);
    if (!threadHdr)
      break;

    nsCOMPtr <nsIMsgDBHdr> msgHdr;
    uint32_t numChildren;
    if (unreadOnly)
      threadHdr->GetNumUnreadChildren(&numChildren);
    else
      threadHdr->GetNumChildren(&numChildren);

    uint32_t threadFlags;
    threadHdr->GetFlags(&threadFlags);
    if (numChildren != 0)
    {
      // Not an empty thread.
      int32_t unusedRootIndex;
      if (pTotalHeaders)
        *pTotalHeaders += numChildren;

      if (unreadOnly)
        rv = threadHdr->GetFirstUnreadChild(getter_AddRefs(msgHdr));
      else
        rv = threadHdr->GetRootHdr(&unusedRootIndex, getter_AddRefs(msgHdr));

      if (NS_SUCCEEDED(rv) && msgHdr != nullptr && WantsThisThread(threadHdr))
      {
        uint32_t msgFlags;
        uint32_t newMsgFlags;
        nsMsgKey msgKey;
        msgHdr->GetMessageKey(&msgKey);
        msgHdr->GetFlags(&msgFlags);
        // Turn off high byte of msg flags - used for view flags.
        msgFlags &= ~MSG_VIEW_FLAGS;
        pOutput[numListed] = msgKey;
        pLevels[numListed] = 0;
        // Turn off these flags on msg hdr - they belong in thread.
        msgHdr->AndFlags(~(nsMsgMessageFlags::Watched), &newMsgFlags);
        AdjustReadFlag(msgHdr, &msgFlags);
        // Try adding in MSG_VIEW_FLAG_ISTHREAD flag for unreadonly view.
        pFlags[numListed] = msgFlags | MSG_VIEW_FLAG_ISTHREAD | threadFlags;
        if (numChildren > 1)
          pFlags[numListed] |= MSG_VIEW_FLAG_HASCHILDREN;

        numListed++;
      }
      else
      {
        NS_ASSERTION(NS_SUCCEEDED(rv) && msgHdr,
                     "couldn't get header for some reason");
      }
    }
    else if (threadsRemoved < 10 &&
             !(threadFlags & (nsMsgMessageFlags::Watched |
                              nsMsgMessageFlags::Ignored)))
    {
      // ### remove thread.
      // Don't want to remove all empty threads first time around as it will
      // choke performance for upgrade.
      threadsRemoved++;
#ifdef DEBUG_bienvenu
      printf("removing empty non-ignored non-watched thread\n");
#endif
    }
  }

  if (hasMore && threadHdr)
  {
    threadHdr->GetThreadKey(startMsg);
  }
  else
  {
    *startMsg = nsMsgKey_None;
    nsCOMPtr <nsIDBChangeListener> dbListener = do_QueryInterface(m_threadEnumerator);
    // This is needed to make the thread enumerator release its reference
    // to the db.
    if (dbListener)
      dbListener->OnAnnouncerGoingAway(nullptr);

    m_threadEnumerator = nullptr;
  }

  *pNumListed = numListed;
  return rv;
}

void
nsMsgThreadedDBView::OnExtraFlagChanged(nsMsgViewIndex index,
                                        uint32_t extraFlag)
{
  if (IsValidIndex(index))
  {
    if (m_havePrevView)
    {
      nsMsgKey keyChanged = m_keys[index];
      nsMsgViewIndex prevViewIndex = m_prevKeys.IndexOf(keyChanged);
      if (prevViewIndex != nsMsgViewIndex_None)
      {
        uint32_t prevFlag = m_prevFlags[prevViewIndex];
        // Don't want to change the elided bit, or has children or is thread.
        if (prevFlag & nsMsgMessageFlags::Elided)
          extraFlag |= nsMsgMessageFlags::Elided;
        else
          extraFlag &= ~nsMsgMessageFlags::Elided;

        if (prevFlag & MSG_VIEW_FLAG_ISTHREAD)
          extraFlag |= MSG_VIEW_FLAG_ISTHREAD;
        else
          extraFlag &= ~MSG_VIEW_FLAG_ISTHREAD;

        if (prevFlag & MSG_VIEW_FLAG_HASCHILDREN)
          extraFlag |= MSG_VIEW_FLAG_HASCHILDREN;
        else
          extraFlag &= ~MSG_VIEW_FLAG_HASCHILDREN;

        // Will this be right?
        m_prevFlags[prevViewIndex] = extraFlag;
      }
    }
  }

  // We don't really know what's changed, but to be on the safe side, set the
  // sort invalid so that reverse sort will pick it up.
  if (m_sortType == nsMsgViewSortType::byStatus ||
      m_sortType == nsMsgViewSortType::byFlagged ||
      m_sortType == nsMsgViewSortType::byUnread ||
      m_sortType == nsMsgViewSortType::byPriority)
  {
    m_sortValid = false;
  }
}

void
nsMsgThreadedDBView::OnHeaderAddedOrDeleted()
{
  ClearPrevIdArray();
}

void
nsMsgThreadedDBView::ClearPrevIdArray()
{
  m_prevKeys.Clear();
  m_prevLevels.Clear();
  m_prevFlags.Clear();
  m_havePrevView = false;
}

nsresult
nsMsgThreadedDBView::InitSort(nsMsgViewSortTypeValue sortType,
                              nsMsgViewSortOrderValue sortOrder)
{
  // Nothing to do.
  if (m_viewFlags & nsMsgViewFlagsType::kGroupBySort)
    return NS_OK;

  if (sortType == nsMsgViewSortType::byThread)
  {
    // Sort top level threads by id.
    nsMsgDBView::Sort(nsMsgViewSortType::byId, sortOrder);
    m_sortType = nsMsgViewSortType::byThread;
    m_viewFlags |= nsMsgViewFlagsType::kThreadedDisplay;
    m_viewFlags &= ~nsMsgViewFlagsType::kGroupBySort;
    // Persist the view flags.
    SetViewFlags(m_viewFlags);
    // m_db->SetSortInfo(m_sortType, sortOrder);
  }
//  else
//    m_viewFlags &= ~nsMsgViewFlagsType::kThreadedDisplay;


  // By default, the unread only view should have all threads expanded.
  if ((m_viewFlags & (nsMsgViewFlagsType::kUnreadOnly |
                      nsMsgViewFlagsType::kExpandAll)) &&
      (m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay))
  {
    ExpandAll();
  }

  if (!(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay))
  {
    // For now, expand all and do a flat sort.
    ExpandAll();
  }

  Sort(sortType, sortOrder);
  if (sortType != nsMsgViewSortType::byThread)
  {
    // Forget prev view, since it has everything expanded.
    ClearPrevIdArray();
  }

  return NS_OK;
}

nsresult
nsMsgThreadedDBView::OnNewHeader(nsIMsgDBHdr *newHdr,
                                 nsMsgKey aParentKey,
                                 bool ensureListed)
{
  if (m_viewFlags & nsMsgViewFlagsType::kGroupBySort)
    return nsMsgGroupView::OnNewHeader(newHdr, aParentKey, ensureListed);

  NS_ENSURE_TRUE(newHdr, NS_MSG_MESSAGE_NOT_FOUND);

  nsMsgKey newKey;
  newHdr->GetMessageKey(&newKey);

  // Views can override this behaviour, which is to append to view.
  // This is the mail behaviour, but threaded views want
  // to insert in order...
  uint32_t msgFlags;
  newHdr->GetFlags(&msgFlags);
  if (m_viewFlags & nsMsgViewFlagsType::kUnreadOnly &&
      !ensureListed &&
      msgFlags & nsMsgMessageFlags::Read)
  {
    return NS_OK;
  }

  // Currently, we only add the header in a threaded view if it's a thread.
  // We used to check if this was the first header in the thread, but that's
  // a bit harder in the unreadOnly view. But we'll catch it below.

  // If not threaded display just add it to the view.
  if (!(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay))
    return AddHdr(newHdr);

  // Need to find the thread we added this to so we can change the hasnew flag
  // added message to existing thread, but not to view.
  // Fix flags on thread header.
  int32_t threadCount;
  uint32_t threadFlags;
  bool moveThread = false;
  nsMsgViewIndex threadIndex = ThreadIndexOfMsg(newKey, nsMsgViewIndex_None,
                                                &threadCount, &threadFlags);
  bool threadRootIsDisplayed = false;

  nsCOMPtr <nsIMsgThread> threadHdr;
  m_db->GetThreadContainingMsgHdr(newHdr, getter_AddRefs(threadHdr));
  if (threadHdr && m_sortType == nsMsgViewSortType::byDate)
  {
    uint32_t newestMsgInThread = 0, msgDate = 0;
    threadHdr->GetNewestMsgDate(&newestMsgInThread);
    newHdr->GetDateInSeconds(&msgDate);
    moveThread = (msgDate == newestMsgInThread);
  }

  if (threadIndex != nsMsgViewIndex_None)
  {
    threadRootIsDisplayed = (m_currentlyDisplayedViewIndex == threadIndex);
    uint32_t flags = m_flags[threadIndex];
    if (!(flags & MSG_VIEW_FLAG_HASCHILDREN))
    {
      flags |= MSG_VIEW_FLAG_HASCHILDREN | MSG_VIEW_FLAG_ISTHREAD;
      if (!(m_viewFlags & nsMsgViewFlagsType::kUnreadOnly))
        flags |= nsMsgMessageFlags::Elided;

      m_flags[threadIndex] = flags;
    }

    if (!(flags & nsMsgMessageFlags::Elided))
    {
      // Thread is expanded.
      // Insert child into thread.
      // Levels of other hdrs may have changed!
      uint32_t newFlags = msgFlags;
      int32_t level = 0;
      nsMsgViewIndex insertIndex = threadIndex;
      if (aParentKey == nsMsgKey_None)
      {
        newFlags |= MSG_VIEW_FLAG_ISTHREAD | MSG_VIEW_FLAG_HASCHILDREN;
      }
      else
      {
        nsMsgViewIndex parentIndex = FindParentInThread(aParentKey, threadIndex);
        level = m_levels[parentIndex] + 1;
        insertIndex = GetInsertInfoForNewHdr(newHdr, parentIndex, level);
      }

      InsertMsgHdrAt(insertIndex, newHdr, newKey, newFlags, level);
      // The call to NoteChange() has to happen after we add the key as
      // NoteChange() will call RowCountChanged() which will call our
      // GetRowCount().
      NoteChange(insertIndex, 1, nsMsgViewNotificationCode::insertOrDelete);

      if (aParentKey == nsMsgKey_None)
      {
        // this header is the new king! try collapsing the existing thread,
        // removing it, installing this header as king, and expanding it.
        CollapseByIndex(threadIndex, nullptr);
        // call base class, so child won't get promoted.
        // nsMsgDBView::RemoveByIndex(threadIndex);
        ExpandByIndex(threadIndex, nullptr);
      }
    }
    else if (aParentKey == nsMsgKey_None)
    {
      // if we have a collapsed thread which just got a new
      // top of thread, change the keys array.
      m_keys[threadIndex] = newKey;
    }

    // If this message is new, the thread is collapsed, it is the
    // root and it was displayed, expand it so that the user does
    // not find that their message has magically turned into a summary.
    if (msgFlags & nsMsgMessageFlags::New &&
        m_flags[threadIndex] & nsMsgMessageFlags::Elided &&
        threadRootIsDisplayed)
      ExpandByIndex(threadIndex, nullptr);

    if (moveThread)
      MoveThreadAt(threadIndex);
    else
      // note change, to update the parent thread's unread and total counts
      NoteChange(threadIndex, 1, nsMsgViewNotificationCode::changed);
  }
  else if (threadHdr)
  {
    // Adding msg to thread that's not in view.
    AddMsgToThreadNotInView(threadHdr, newHdr, ensureListed);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsMsgThreadedDBView::OnParentChanged (nsMsgKey aKeyChanged,
                                      nsMsgKey oldParent,
                                      nsMsgKey newParent,
                                      nsIDBChangeListener *aInstigator)
{
  // We need to adjust the level of the hdr whose parent changed, and
  // invalidate that row, iff we're in threaded mode.
#if 0
  // This code never runs due to the if (false) and Clang complains about it
  // so it is ifdefed out for now.
  if (false && m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay)
  {
    nsMsgViewIndex childIndex = FindViewIndex(aKeyChanged);
    if (childIndex != nsMsgViewIndex_None)
    {
      nsMsgViewIndex parentIndex = FindViewIndex(newParent);
      int32_t newParentLevel =
        (parentIndex == nsMsgViewIndex_None) ? -1 : m_levels[parentIndex];

      nsMsgViewIndex oldParentIndex = FindViewIndex(oldParent);

      int32_t oldParentLevel =
        (oldParentIndex != nsMsgViewIndex_None ||
         newParent == nsMsgKey_None) ? m_levels[oldParentIndex] : -1 ;

      int32_t levelChanged = m_levels[childIndex];
      int32_t parentDelta = oldParentLevel - newParentLevel;
      m_levels[childIndex] = (newParent == nsMsgKey_None) ? 0 : newParentLevel + 1;
      if (parentDelta > 0)
      {
        for (nsMsgViewIndex viewIndex = childIndex + 1;
             viewIndex < GetSize() && m_levels[viewIndex] > levelChanged;
             viewIndex++)
        {
          m_levels[viewIndex] = m_levels[viewIndex] - parentDelta;
          NoteChange(viewIndex, 1, nsMsgViewNotificationCode::changed);
        }
      }

      NoteChange(childIndex, 1, nsMsgViewNotificationCode::changed);
    }
  }
#endif
  return NS_OK;
}

nsMsgViewIndex
nsMsgThreadedDBView::GetInsertInfoForNewHdr(nsIMsgDBHdr *newHdr,
                                            nsMsgViewIndex parentIndex,
                                            int32_t targetLevel)
{
  uint32_t viewSize = GetSize();
  while (++parentIndex < viewSize)
  {
    // Loop until we find a message at a level less than or equal to the
    // parent level
    if (m_levels[parentIndex] < targetLevel)
      break;
  }

  return parentIndex;
}

// This method removes the thread at threadIndex from the view
// and puts it back in its new position, determined by the sort order.
// And, if the selection is affected, save and restore the selection.
void
nsMsgThreadedDBView::MoveThreadAt(nsMsgViewIndex threadIndex)
{
  // We need to check if the thread is collapsed or not...
  // We want to turn off tree notifications so that we don't
  // reload the current message.
  // We also need to invalidate the range between where the thread was
  // and where it ended up.
  bool changesDisabled = mSuppressChangeNotification;
  if (!changesDisabled)
    SetSuppressChangeNotifications(true);

  nsCOMPtr <nsIMsgDBHdr> threadHdr;

  GetMsgHdrForViewIndex(threadIndex, getter_AddRefs(threadHdr));
  int32_t childCount = 0;

  nsMsgKey preservedKey;
  AutoTArray<nsMsgKey, 1> preservedSelection;
  int32_t selectionCount;
  int32_t currentIndex;
  bool hasSelection = mTree && mTreeSelection &&
                      ((NS_SUCCEEDED(mTreeSelection->GetCurrentIndex(&currentIndex)) &&
                        currentIndex >= 0 && (uint32_t)currentIndex < GetSize()) ||
                       (NS_SUCCEEDED(mTreeSelection->GetRangeCount(&selectionCount)) &&
                        selectionCount > 0));
  if (hasSelection)
    SaveAndClearSelection(&preservedKey, preservedSelection);

  uint32_t saveFlags = m_flags[threadIndex];
  bool threadIsExpanded = !(saveFlags & nsMsgMessageFlags::Elided);

  if (threadIsExpanded)
  {
    ExpansionDelta(threadIndex, &childCount);
    childCount = -childCount;
  }

  nsTArray<nsMsgKey> threadKeys;
  nsTArray<uint32_t> threadFlags;
  nsTArray<uint8_t> threadLevels;

  if (threadIsExpanded)
  {
    threadKeys.SetCapacity(childCount);
    threadFlags.SetCapacity(childCount);
    threadLevels.SetCapacity(childCount);
    for (nsMsgViewIndex index = threadIndex + 1;
         index < GetSize() && m_levels[index];
         index++)
    {
      threadKeys.AppendElement(m_keys[index]);
      threadFlags.AppendElement(m_flags[index]);
      threadLevels.AppendElement(m_levels[index]);
    }

    uint32_t collapseCount;
    CollapseByIndex(threadIndex, &collapseCount);
  }

  nsMsgDBView::RemoveByIndex(threadIndex);
  nsMsgViewIndex newIndex = nsMsgViewIndex_None;
  AddHdr(threadHdr, &newIndex);

  // AddHdr doesn't always set newIndex, and getting it to do so
  // is going to require some refactoring.
  if (newIndex == nsMsgViewIndex_None)
    newIndex = FindHdr(threadHdr);

  if (threadIsExpanded)
  {
    m_keys.InsertElementsAt(newIndex + 1, threadKeys);
    m_flags.InsertElementsAt(newIndex + 1, threadFlags);
    m_levels.InsertElementsAt(newIndex + 1, threadLevels);
  }

  if (newIndex == nsMsgViewIndex_None)
  {
     NS_WARNING("newIndex=-1 in MoveThreadAt");
     newIndex = 0;
  }

  m_flags[newIndex] = saveFlags;
  // Unfreeze selection.
  if (hasSelection)
    RestoreSelection(preservedKey, preservedSelection);

  if (!changesDisabled)
    SetSuppressChangeNotifications(false);

  nsMsgViewIndex lowIndex = threadIndex < newIndex ? threadIndex : newIndex;
  nsMsgViewIndex highIndex = lowIndex == threadIndex ? newIndex : threadIndex;

  NoteChange(lowIndex, highIndex - lowIndex + childCount + 1,
             nsMsgViewNotificationCode::changed);
}

nsresult
nsMsgThreadedDBView::AddMsgToThreadNotInView(nsIMsgThread *threadHdr,
                                             nsIMsgDBHdr *msgHdr,
                                             bool ensureListed)
{
  nsresult rv = NS_OK;
  uint32_t threadFlags;
  threadHdr->GetFlags(&threadFlags);
  if (!(threadFlags & nsMsgMessageFlags::Ignored))
  {
    bool msgKilled;
    msgHdr->GetIsKilled(&msgKilled);
    if (!msgKilled)
      rv = nsMsgDBView::AddHdr(msgHdr);
  }

  return rv;
}

// This method just removes the specified line from the view. It does
// NOT delete it from the database.
nsresult
nsMsgThreadedDBView::RemoveByIndex(nsMsgViewIndex index)
{
  nsresult rv = NS_OK;
  int32_t flags;

  if (!IsValidIndex(index))
    return NS_MSG_INVALID_DBVIEW_INDEX;

  OnHeaderAddedOrDeleted();

  flags = m_flags[index];

  if (!(m_viewFlags & nsMsgViewFlagsType::kThreadedDisplay))
    return nsMsgDBView::RemoveByIndex(index);

  nsCOMPtr<nsIMsgThread> threadHdr;
  GetThreadContainingIndex(index, getter_AddRefs(threadHdr));
  NS_ENSURE_SUCCESS(rv, rv);
  uint32_t numThreadChildren = 0;
  // If we can't get a thread, it's already deleted and thus has 0 children.
  if (threadHdr)
    threadHdr->GetNumChildren(&numThreadChildren);

  // Check if we're the top level msg in the thread, and we're not collapsed.
  if ((flags & MSG_VIEW_FLAG_ISTHREAD) &&
      !(flags & nsMsgMessageFlags::Elided) &&
      (flags & MSG_VIEW_FLAG_HASCHILDREN))
  {
    // Fix flags on thread header - newly promoted message should have
    // flags set correctly.
    if (threadHdr)
    {
      nsMsgDBView::RemoveByIndex(index);
      nsCOMPtr<nsIMsgThread> nextThreadHdr;
      // Above RemoveByIndex may now make index out of bounds.
      if (IsValidIndex(index) && numThreadChildren > 0)
      {
        // unreadOnly
        nsCOMPtr<nsIMsgDBHdr> msgHdr;
        rv = threadHdr->GetChildHdrAt(0, getter_AddRefs(msgHdr));
        if (msgHdr != nullptr)
        {
          uint32_t flag = 0;
          msgHdr->GetFlags(&flag);
          if (numThreadChildren > 1)
            flag |= MSG_VIEW_FLAG_ISTHREAD | MSG_VIEW_FLAG_HASCHILDREN;

          m_flags[index] = flag;
          m_levels[index] = 0;
        }
      }
    }

    return rv;
  }
  else if (!(flags & MSG_VIEW_FLAG_ISTHREAD))
  {
    // We're not deleting the top level msg, but top level msg might be the
    // only msg in thread now.
    if (threadHdr && numThreadChildren == 1)
    {
      nsMsgKey msgKey;
      rv = threadHdr->GetChildKeyAt(0, &msgKey);
      if (NS_SUCCEEDED(rv))
      {
        nsMsgViewIndex threadIndex = FindViewIndex(msgKey);
        if (IsValidIndex(threadIndex))
        {
          uint32_t flags = m_flags[threadIndex];
          flags &= ~(MSG_VIEW_FLAG_ISTHREAD |
                     nsMsgMessageFlags::Elided |
                     MSG_VIEW_FLAG_HASCHILDREN);
          m_flags[threadIndex] = flags;
          NoteChange(threadIndex, 1, nsMsgViewNotificationCode::changed);
        }
      }

    }

    return nsMsgDBView::RemoveByIndex(index);
  }

  // Deleting collapsed thread header is special case. Child will be promoted,
  // so just tell FE that line changed, not that it was deleted.
  // Header has already been deleted from thread.
  if (threadHdr && numThreadChildren > 0)
  {
    // Change the id array and flags array to reflect the child header.
    // If we're not deleting the header, we want the second header,
    // Otherwise, the first one (which just got promoted).
    nsCOMPtr<nsIMsgDBHdr> msgHdr;
    rv = threadHdr->GetChildHdrAt(0, getter_AddRefs(msgHdr));
    if (msgHdr != nullptr)
    {
      msgHdr->GetMessageKey(&m_keys[index]);
      uint32_t flag = 0;
      msgHdr->GetFlags(&flag);
      flag |= MSG_VIEW_FLAG_ISTHREAD;

      // If only hdr in thread (with one about to be deleted).
      if (numThreadChildren == 1)
      {
        // Adjust flags.
        flag &=  ~MSG_VIEW_FLAG_HASCHILDREN;
        flag &= ~nsMsgMessageFlags::Elided;
        // Tell FE that thread header needs to be repainted.
        NoteChange(index, 1, nsMsgViewNotificationCode::changed);
      }
      else
      {
        flag |= MSG_VIEW_FLAG_HASCHILDREN;
        flag |= nsMsgMessageFlags::Elided;
      }

      m_flags[index] = flag;
      mIndicesToNoteChange.RemoveElement(index);
    }
    else
    {
      NS_ASSERTION(false, "couldn't find thread child");
    }

    NoteChange(index, 1, nsMsgViewNotificationCode::changed);
  }
  else
  {
    // We may have deleted a whole, collapsed thread - if so,
    // ensure that the current index will be noted as changed.
    if (!mIndicesToNoteChange.Contains(index))
      mIndicesToNoteChange.AppendElement(index);

    rv = nsMsgDBView::RemoveByIndex(index);
  }

  return rv;
}

NS_IMETHODIMP
nsMsgThreadedDBView::GetViewType(nsMsgViewTypeValue *aViewType)
{
  NS_ENSURE_ARG_POINTER(aViewType);
  *aViewType = nsMsgViewType::eShowAllThreads;
  return NS_OK;
}

NS_IMETHODIMP
nsMsgThreadedDBView::CloneDBView(nsIMessenger *aMessengerInstance,
                                 nsIMsgWindow *aMsgWindow,
                                 nsIMsgDBViewCommandUpdater *aCmdUpdater,
                                 nsIMsgDBView **_retval)
{
  nsMsgThreadedDBView* newMsgDBView = new nsMsgThreadedDBView();

  if (!newMsgDBView)
    return NS_ERROR_OUT_OF_MEMORY;

  nsresult rv = CopyDBView(newMsgDBView, aMessengerInstance, aMsgWindow, aCmdUpdater);
  NS_ENSURE_SUCCESS(rv,rv);

  NS_IF_ADDREF(*_retval = newMsgDBView);
  return NS_OK;
}