forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsNavHistoryResult.cpp
4794 lines (4138 loc) · 159 KB
/
nsNavHistoryResult.cpp
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
/* -*- 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 <stdio.h>
#include "nsNavHistory.h"
#include "nsNavBookmarks.h"
#include "nsFaviconService.h"
#include "nsITaggingService.h"
#include "nsAnnotationService.h"
#include "Helpers.h"
#include "mozilla/DebugOnly.h"
#include "nsDebug.h"
#include "nsNetUtil.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "nsUnicharUtils.h"
#include "prtime.h"
#include "nsQueryObject.h"
#include "nsCycleCollectionParticipant.h"
// Thanks, Windows.h :(
#undef CompareString
#define TO_ICONTAINER(_node) \
static_cast<nsINavHistoryContainerResultNode*>(_node)
#define TO_CONTAINER(_node) \
static_cast<nsNavHistoryContainerResultNode*>(_node)
#define NOTIFY_RESULT_OBSERVERS_RET(_result, _method, _ret) \
PR_BEGIN_MACRO \
NS_ENSURE_TRUE(_result, _ret); \
if (!_result->mSuppressNotifications) { \
ENUMERATE_WEAKARRAY(_result->mObservers, nsINavHistoryResultObserver, \
_method) \
} \
PR_END_MACRO
#define NOTIFY_RESULT_OBSERVERS(_result, _method) \
NOTIFY_RESULT_OBSERVERS_RET(_result, _method, NS_ERROR_UNEXPECTED)
// What we want is: NS_INTERFACE_MAP_ENTRY(self) for static IID accessors,
// but some of our classes (like nsNavHistoryResult) have an ambiguous base
// class of nsISupports which prevents this from working (the default macro
// converts it to nsISupports, then addrefs it, then returns it). Therefore, we
// expand the macro here and change it so that it works. Yuck.
#define NS_INTERFACE_MAP_STATIC_AMBIGUOUS(_class) \
if (aIID.Equals(NS_GET_IID(_class))) { \
NS_ADDREF(this); \
*aInstancePtr = this; \
return NS_OK; \
} else
// Number of changes to handle separately in a batch. If more changes are
// requested the node will switch to full refresh mode.
#define MAX_BATCH_CHANGES_BEFORE_REFRESH 5
// Emulate string comparison (used for sorting) for PRTime and int.
inline int32_t ComparePRTime(PRTime a, PRTime b)
{
if (a < b)
return -1;
else if (a > b)
return 1;
return 0;
}
inline int32_t CompareIntegers(uint32_t a, uint32_t b)
{
return a - b;
}
using namespace mozilla;
using namespace mozilla::places;
NS_IMPL_CYCLE_COLLECTION(nsNavHistoryResultNode, mParent)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNavHistoryResultNode)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsINavHistoryResultNode)
NS_INTERFACE_MAP_ENTRY(nsINavHistoryResultNode)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNavHistoryResultNode)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNavHistoryResultNode)
nsNavHistoryResultNode::nsNavHistoryResultNode(
const nsACString& aURI, const nsACString& aTitle, uint32_t aAccessCount,
PRTime aTime) :
mParent(nullptr),
mURI(aURI),
mTitle(aTitle),
mAreTagsSorted(false),
mAccessCount(aAccessCount),
mTime(aTime),
mBookmarkIndex(-1),
mItemId(-1),
mFolderId(-1),
mVisitId(-1),
mFromVisitId(-1),
mDateAdded(0),
mLastModified(0),
mIndentLevel(-1),
mFrecency(0),
mHidden(false),
mTransitionType(0)
{
mTags.SetIsVoid(true);
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetIcon(nsACString& aIcon)
{
if (this->IsContainer() || mURI.IsEmpty()) {
return NS_OK;
}
aIcon.AppendLiteral("page-icon:");
aIcon.Append(mURI);
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetParent(nsINavHistoryContainerResultNode** aParent)
{
NS_IF_ADDREF(*aParent = mParent);
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetParentResult(nsINavHistoryResult** aResult)
{
*aResult = nullptr;
if (IsContainer())
NS_IF_ADDREF(*aResult = GetAsContainer()->mResult);
else if (mParent)
NS_IF_ADDREF(*aResult = mParent->mResult);
NS_ENSURE_STATE(*aResult);
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetTags(nsAString& aTags) {
// Only URI-nodes may be associated with tags
if (!IsURI()) {
aTags.Truncate();
return NS_OK;
}
// Initially, the tags string is set to a void string (see constructor). We
// then build it the first time this method called is called (and by that,
// implicitly unset the void flag). Result observers may re-set the void flag
// in order to force rebuilding of the tags string.
if (!mTags.IsVoid()) {
// If mTags is assigned by a history query it is unsorted for performance
// reasons, it must be sorted by name on first read access.
if (!mAreTagsSorted) {
nsTArray<nsCString> tags;
ParseString(NS_ConvertUTF16toUTF8(mTags), ',', tags);
tags.Sort();
mTags.SetIsVoid(true);
for (nsTArray<nsCString>::index_type i = 0; i < tags.Length(); ++i) {
AppendUTF8toUTF16(tags[i], mTags);
if (i < tags.Length() - 1 )
mTags.AppendLiteral(", ");
}
mAreTagsSorted = true;
}
aTags.Assign(mTags);
return NS_OK;
}
// Fetch the tags
RefPtr<Database> DB = Database::GetDatabase();
NS_ENSURE_STATE(DB);
nsCOMPtr<mozIStorageStatement> stmt = DB->GetStatement(
"/* do not warn (bug 487594) */ "
"SELECT GROUP_CONCAT(tag_title, ', ') "
"FROM ( "
"SELECT t.title AS tag_title "
"FROM moz_bookmarks b "
"JOIN moz_bookmarks t ON t.id = +b.parent "
"WHERE b.fk = (SELECT id FROM moz_places WHERE url_hash = hash(:page_url) AND url = :page_url) "
"AND t.parent = :tags_folder "
"ORDER BY t.title COLLATE NOCASE ASC "
") "
);
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsNavHistory* history = nsNavHistory::GetHistoryService();
NS_ENSURE_STATE(history);
nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("tags_folder"),
history->GetTagsFolder());
NS_ENSURE_SUCCESS(rv, rv);
rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), mURI);
NS_ENSURE_SUCCESS(rv, rv);
bool hasTags = false;
if (NS_SUCCEEDED(stmt->ExecuteStep(&hasTags)) && hasTags) {
rv = stmt->GetString(0, mTags);
NS_ENSURE_SUCCESS(rv, rv);
aTags.Assign(mTags);
mAreTagsSorted = true;
}
// If this node is a child of a history query, we need to make sure changes
// to tags are properly live-updated.
if (mParent && mParent->IsQuery() &&
mParent->mOptions->QueryType() == nsINavHistoryQueryOptions::QUERY_TYPE_HISTORY) {
nsNavHistoryQueryResultNode* query = mParent->GetAsQuery();
nsNavHistoryResult* result = query->GetResult();
NS_ENSURE_STATE(result);
result->AddAllBookmarksObserver(query);
}
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetPageGuid(nsACString& aPageGuid) {
aPageGuid = mPageGuid;
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetBookmarkGuid(nsACString& aBookmarkGuid) {
aBookmarkGuid = mBookmarkGuid;
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetVisitId(int64_t* aVisitId) {
*aVisitId = mVisitId;
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetFromVisitId(int64_t* aFromVisitId) {
*aFromVisitId = mFromVisitId;
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryResultNode::GetVisitType(uint32_t* aVisitType) {
*aVisitType = mTransitionType;
return NS_OK;
}
void
nsNavHistoryResultNode::OnRemoving()
{
mParent = nullptr;
}
/**
* This will find the result for this node. We can ask the nearest container
* for this value (either ourselves or our parents should be a container,
* and all containers have result pointers).
*
* @note The result may be null, if the container is detached from the result
* who owns it.
*/
nsNavHistoryResult*
nsNavHistoryResultNode::GetResult()
{
nsNavHistoryResultNode* node = this;
do {
if (node->IsContainer()) {
nsNavHistoryContainerResultNode* container = TO_CONTAINER(node);
return container->mResult;
}
node = node->mParent;
} while (node);
MOZ_ASSERT(false, "No container node found in hierarchy!");
return nullptr;
}
/**
* Searches up the tree for the closest ancestor node that has an options
* structure. This will tell us the options that were used to generate this
* node.
*
* Be careful, this function walks up the tree, so it can not be used when
* result nodes are created because they have no parent. Only call this
* function after the tree has been built.
*/
nsNavHistoryQueryOptions*
nsNavHistoryResultNode::GetGeneratingOptions()
{
if (!mParent) {
// When we have no parent, it either means we haven't built the tree yet,
// in which case calling this function is a bug, or this node is the root
// of the tree. When we are the root of the tree, our own options are the
// generating options.
if (IsContainer())
return GetAsContainer()->mOptions;
NS_NOTREACHED("Can't find a generating node for this container, perhaps FillStats has not been called on this tree yet?");
return nullptr;
}
// Look up the tree. We want the options that were used to create this node,
// and since it has a parent, it's the options of an ancestor, not of the node
// itself. So start at the parent.
nsNavHistoryContainerResultNode* cur = mParent;
while (cur) {
if (cur->IsContainer())
return cur->GetAsContainer()->mOptions;
cur = cur->mParent;
}
// We should always find a container node as an ancestor.
NS_NOTREACHED("Can't find a generating node for this container, the tree seemes corrupted.");
return nullptr;
}
NS_IMPL_CYCLE_COLLECTION_INHERITED(nsNavHistoryContainerResultNode, nsNavHistoryResultNode,
mResult,
mChildren)
NS_IMPL_ADDREF_INHERITED(nsNavHistoryContainerResultNode, nsNavHistoryResultNode)
NS_IMPL_RELEASE_INHERITED(nsNavHistoryContainerResultNode, nsNavHistoryResultNode)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNavHistoryContainerResultNode)
NS_INTERFACE_MAP_STATIC_AMBIGUOUS(nsNavHistoryContainerResultNode)
NS_INTERFACE_MAP_ENTRY(nsINavHistoryContainerResultNode)
NS_INTERFACE_MAP_END_INHERITING(nsNavHistoryResultNode)
nsNavHistoryContainerResultNode::nsNavHistoryContainerResultNode(
const nsACString& aURI, const nsACString& aTitle, uint32_t aContainerType,
nsNavHistoryQueryOptions* aOptions) :
nsNavHistoryResultNode(aURI, aTitle, 0, 0),
mResult(nullptr),
mContainerType(aContainerType),
mExpanded(false),
mOptions(aOptions),
mAsyncCanceledState(NOT_CANCELED)
{
}
nsNavHistoryContainerResultNode::nsNavHistoryContainerResultNode(
const nsACString& aURI, const nsACString& aTitle,
PRTime aTime, uint32_t aContainerType,
nsNavHistoryQueryOptions* aOptions) :
nsNavHistoryResultNode(aURI, aTitle, 0, aTime),
mResult(nullptr),
mContainerType(aContainerType),
mExpanded(false),
mOptions(aOptions),
mAsyncCanceledState(NOT_CANCELED)
{
}
nsNavHistoryContainerResultNode::~nsNavHistoryContainerResultNode()
{
// Explicitly clean up array of children of this container. We must ensure
// all references are gone and all of their destructors are called.
mChildren.Clear();
}
/**
* Containers should notify their children that they are being removed when the
* container is being removed.
*/
void
nsNavHistoryContainerResultNode::OnRemoving()
{
nsNavHistoryResultNode::OnRemoving();
for (int32_t i = 0; i < mChildren.Count(); ++i)
mChildren[i]->OnRemoving();
mChildren.Clear();
mResult = nullptr;
}
bool
nsNavHistoryContainerResultNode::AreChildrenVisible()
{
nsNavHistoryResult* result = GetResult();
if (!result) {
NS_NOTREACHED("Invalid result");
return false;
}
if (!mExpanded)
return false;
// Now check if any ancestor is closed.
nsNavHistoryContainerResultNode* ancestor = mParent;
while (ancestor) {
if (!ancestor->mExpanded)
return false;
ancestor = ancestor->mParent;
}
return true;
}
NS_IMETHODIMP
nsNavHistoryContainerResultNode::GetContainerOpen(bool *aContainerOpen)
{
*aContainerOpen = mExpanded;
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryContainerResultNode::SetContainerOpen(bool aContainerOpen)
{
if (aContainerOpen) {
if (!mExpanded) {
nsNavHistoryQueryOptions* options = GetGeneratingOptions();
if (options && options->AsyncEnabled())
OpenContainerAsync();
else
OpenContainer();
}
}
else {
if (mExpanded)
CloseContainer();
else if (mAsyncPendingStmt)
CancelAsyncOpen(false);
}
return NS_OK;
}
/**
* Notifies the result's observers of a change in the container's state. The
* notification includes both the old and new states: The old is aOldState, and
* the new is the container's current state.
*
* @param aOldState
* The state being transitioned out of.
*/
nsresult
nsNavHistoryContainerResultNode::NotifyOnStateChange(uint16_t aOldState)
{
nsNavHistoryResult* result = GetResult();
NS_ENSURE_STATE(result);
nsresult rv;
uint16_t currState;
rv = GetState(&currState);
NS_ENSURE_SUCCESS(rv, rv);
// Notify via the new ContainerStateChanged observer method.
NOTIFY_RESULT_OBSERVERS(result,
ContainerStateChanged(this, aOldState, currState));
return NS_OK;
}
NS_IMETHODIMP
nsNavHistoryContainerResultNode::GetState(uint16_t* _state)
{
NS_ENSURE_ARG_POINTER(_state);
*_state = mExpanded ? (uint16_t)STATE_OPENED
: mAsyncPendingStmt ? (uint16_t)STATE_LOADING
: (uint16_t)STATE_CLOSED;
return NS_OK;
}
/**
* This handles the generic container case. Other container types should
* override this to do their own handling.
*/
nsresult
nsNavHistoryContainerResultNode::OpenContainer()
{
NS_ASSERTION(!mExpanded, "Container must not be expanded to open it");
mExpanded = true;
nsresult rv = NotifyOnStateChange(STATE_CLOSED);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
/**
* Unset aSuppressNotifications to notify observers on this change. That is
* the normal operation. This is set to false for the recursive calls since the
* root container that is being closed will handle recomputation of the visible
* elements for its entire subtree.
*/
nsresult
nsNavHistoryContainerResultNode::CloseContainer(bool aSuppressNotifications)
{
NS_ASSERTION((mExpanded && !mAsyncPendingStmt) ||
(!mExpanded && mAsyncPendingStmt),
"Container must be expanded or loading to close it");
nsresult rv;
uint16_t oldState;
rv = GetState(&oldState);
NS_ENSURE_SUCCESS(rv, rv);
if (mExpanded) {
// Recursively close all child containers.
for (int32_t i = 0; i < mChildren.Count(); ++i) {
if (mChildren[i]->IsContainer() &&
mChildren[i]->GetAsContainer()->mExpanded)
mChildren[i]->GetAsContainer()->CloseContainer(true);
}
mExpanded = false;
}
// Be sure to set this to null before notifying observers. It signifies that
// the container is no longer loading (if it was in the first place).
mAsyncPendingStmt = nullptr;
if (!aSuppressNotifications) {
rv = NotifyOnStateChange(oldState);
NS_ENSURE_SUCCESS(rv, rv);
}
// If this is the root container of a result, we can tell the result to stop
// observing changes, otherwise the result will stay in memory and updates
// itself till it is cycle collected.
nsNavHistoryResult* result = GetResult();
NS_ENSURE_STATE(result);
if (result->mRootNode == this) {
result->StopObserving();
// When reopening this node its result will be out of sync.
// We must clear our children to ensure we will call FillChildren
// again in such a case.
if (this->IsQuery())
this->GetAsQuery()->ClearChildren(true);
else if (this->IsFolder())
this->GetAsFolder()->ClearChildren(true);
}
return NS_OK;
}
/**
* The async version of OpenContainer.
*/
nsresult
nsNavHistoryContainerResultNode::OpenContainerAsync()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/**
* Cancels the pending asynchronous Storage execution triggered by
* FillChildrenAsync, if it exists. This method doesn't do much, because after
* cancelation Storage will call this node's HandleCompletion callback, where
* the real work is done.
*
* @param aRestart
* If true, async execution will be restarted by HandleCompletion.
*/
void
nsNavHistoryContainerResultNode::CancelAsyncOpen(bool aRestart)
{
NS_ASSERTION(mAsyncPendingStmt, "Async execution canceled but not pending");
mAsyncCanceledState = aRestart ? CANCELED_RESTART_NEEDED : CANCELED;
// Cancel will fail if the pending statement has already been canceled.
// That's OK since this method may be called multiple times, and multiple
// cancels don't harm anything.
(void)mAsyncPendingStmt->Cancel();
}
/**
* This builds up tree statistics from the bottom up. Call with a container
* and the indent level of that container. To init the full tree, call with
* the root container. The default indent level is -1, which is appropriate
* for the root level.
*
* CALL THIS AFTER FILLING ANY CONTAINER to update the parent and result node
* pointers, even if you don't care about visit counts and last visit dates.
*/
void
nsNavHistoryContainerResultNode::FillStats()
{
uint32_t accessCount = 0;
PRTime newTime = 0;
for (int32_t i = 0; i < mChildren.Count(); ++i) {
nsNavHistoryResultNode* node = mChildren[i];
node->mParent = this;
node->mIndentLevel = mIndentLevel + 1;
if (node->IsContainer()) {
nsNavHistoryContainerResultNode* container = node->GetAsContainer();
container->mResult = mResult;
container->FillStats();
}
accessCount += node->mAccessCount;
// this is how container nodes get sorted by date
// The container gets the most recent time of the child nodes.
if (node->mTime > newTime)
newTime = node->mTime;
}
if (mExpanded) {
mAccessCount = accessCount;
if (!IsQuery() || newTime > mTime)
mTime = newTime;
}
}
/**
* This is used when one container changes to do a minimal update of the tree
* structure. When something changes, you want to call FillStats if necessary
* and update this container completely. Then call this function which will
* walk up the tree and fill in the previous containers.
*
* Note that you have to tell us by how much our access count changed. Our
* access count should already be set to the new value; this is used tochange
* the parents without having to re-count all their children.
*
* This does NOT update the last visit date downward. Therefore, if you are
* deleting a node that has the most recent last visit date, the parents will
* not get their last visit dates downshifted accordingly. This is a rather
* unusual case: we don't often delete things, and we usually don't even show
* the last visit date for folders. Updating would be slower because we would
* have to recompute it from scratch.
*/
nsresult
nsNavHistoryContainerResultNode::ReverseUpdateStats(int32_t aAccessCountChange)
{
if (mParent) {
nsNavHistoryResult* result = GetResult();
bool shouldNotify = result && mParent->mParent &&
mParent->mParent->AreChildrenVisible();
uint32_t oldAccessCount = mParent->mAccessCount;
PRTime oldTime = mParent->mTime;
mParent->mAccessCount += aAccessCountChange;
bool timeChanged = false;
if (mTime > mParent->mTime) {
timeChanged = true;
mParent->mTime = mTime;
}
if (shouldNotify) {
NOTIFY_RESULT_OBSERVERS(result,
NodeHistoryDetailsChanged(TO_ICONTAINER(mParent),
oldTime,
oldAccessCount));
}
// check sorting, the stats may have caused this node to move if the
// sorting depended on something we are changing.
uint16_t sortMode = mParent->GetSortType();
bool sortingByVisitCount =
sortMode == nsINavHistoryQueryOptions::SORT_BY_VISITCOUNT_ASCENDING ||
sortMode == nsINavHistoryQueryOptions::SORT_BY_VISITCOUNT_DESCENDING;
bool sortingByTime =
sortMode == nsINavHistoryQueryOptions::SORT_BY_DATE_ASCENDING ||
sortMode == nsINavHistoryQueryOptions::SORT_BY_DATE_DESCENDING;
if ((sortingByVisitCount && aAccessCountChange != 0) ||
(sortingByTime && timeChanged)) {
int32_t ourIndex = mParent->FindChild(this);
NS_ASSERTION(ourIndex >= 0, "Could not find self in parent");
if (ourIndex >= 0)
EnsureItemPosition(static_cast<uint32_t>(ourIndex));
}
nsresult rv = mParent->ReverseUpdateStats(aAccessCountChange);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
/**
* This walks up the tree until we find a query result node or the root to get
* the sorting type.
*/
uint16_t
nsNavHistoryContainerResultNode::GetSortType()
{
if (mParent)
return mParent->GetSortType();
if (mResult)
return mResult->mSortingMode;
// This is a detached container, just use natural order.
return nsINavHistoryQueryOptions::SORT_BY_NONE;
}
nsresult nsNavHistoryContainerResultNode::Refresh() {
NS_WARNING("Refresh() is supported by queries or folders, not generic containers.");
return NS_OK;
}
void
nsNavHistoryContainerResultNode::GetSortingAnnotation(nsACString& aAnnotation)
{
if (mParent)
mParent->GetSortingAnnotation(aAnnotation);
else if (mResult)
aAnnotation.Assign(mResult->mSortingAnnotation);
}
/**
* @return the sorting comparator function for the give sort type, or null if
* there is no comparator.
*/
nsNavHistoryContainerResultNode::SortComparator
nsNavHistoryContainerResultNode::GetSortingComparator(uint16_t aSortType)
{
switch (aSortType)
{
case nsINavHistoryQueryOptions::SORT_BY_NONE:
return &SortComparison_Bookmark;
case nsINavHistoryQueryOptions::SORT_BY_TITLE_ASCENDING:
return &SortComparison_TitleLess;
case nsINavHistoryQueryOptions::SORT_BY_TITLE_DESCENDING:
return &SortComparison_TitleGreater;
case nsINavHistoryQueryOptions::SORT_BY_DATE_ASCENDING:
return &SortComparison_DateLess;
case nsINavHistoryQueryOptions::SORT_BY_DATE_DESCENDING:
return &SortComparison_DateGreater;
case nsINavHistoryQueryOptions::SORT_BY_URI_ASCENDING:
return &SortComparison_URILess;
case nsINavHistoryQueryOptions::SORT_BY_URI_DESCENDING:
return &SortComparison_URIGreater;
case nsINavHistoryQueryOptions::SORT_BY_VISITCOUNT_ASCENDING:
return &SortComparison_VisitCountLess;
case nsINavHistoryQueryOptions::SORT_BY_VISITCOUNT_DESCENDING:
return &SortComparison_VisitCountGreater;
case nsINavHistoryQueryOptions::SORT_BY_KEYWORD_ASCENDING:
return &SortComparison_KeywordLess;
case nsINavHistoryQueryOptions::SORT_BY_KEYWORD_DESCENDING:
return &SortComparison_KeywordGreater;
case nsINavHistoryQueryOptions::SORT_BY_ANNOTATION_ASCENDING:
return &SortComparison_AnnotationLess;
case nsINavHistoryQueryOptions::SORT_BY_ANNOTATION_DESCENDING:
return &SortComparison_AnnotationGreater;
case nsINavHistoryQueryOptions::SORT_BY_DATEADDED_ASCENDING:
return &SortComparison_DateAddedLess;
case nsINavHistoryQueryOptions::SORT_BY_DATEADDED_DESCENDING:
return &SortComparison_DateAddedGreater;
case nsINavHistoryQueryOptions::SORT_BY_LASTMODIFIED_ASCENDING:
return &SortComparison_LastModifiedLess;
case nsINavHistoryQueryOptions::SORT_BY_LASTMODIFIED_DESCENDING:
return &SortComparison_LastModifiedGreater;
case nsINavHistoryQueryOptions::SORT_BY_TAGS_ASCENDING:
return &SortComparison_TagsLess;
case nsINavHistoryQueryOptions::SORT_BY_TAGS_DESCENDING:
return &SortComparison_TagsGreater;
case nsINavHistoryQueryOptions::SORT_BY_FRECENCY_ASCENDING:
return &SortComparison_FrecencyLess;
case nsINavHistoryQueryOptions::SORT_BY_FRECENCY_DESCENDING:
return &SortComparison_FrecencyGreater;
default:
NS_NOTREACHED("Bad sorting type");
return nullptr;
}
}
/**
* This is used by Result::SetSortingMode and QueryResultNode::FillChildren to
* sort the child list.
*
* This does NOT update any visibility or tree information. The caller will
* have to completely rebuild the visible list after this.
*/
void
nsNavHistoryContainerResultNode::RecursiveSort(
const char* aData, SortComparator aComparator)
{
void* data = const_cast<void*>(static_cast<const void*>(aData));
mChildren.Sort(aComparator, data);
for (int32_t i = 0; i < mChildren.Count(); ++i) {
if (mChildren[i]->IsContainer())
mChildren[i]->GetAsContainer()->RecursiveSort(aData, aComparator);
}
}
/**
* @return the index that the given item would fall on if it were to be
* inserted using the given sorting.
*/
uint32_t
nsNavHistoryContainerResultNode::FindInsertionPoint(
nsNavHistoryResultNode* aNode, SortComparator aComparator,
const char* aData, bool* aItemExists)
{
if (aItemExists)
(*aItemExists) = false;
if (mChildren.Count() == 0)
return 0;
void* data = const_cast<void*>(static_cast<const void*>(aData));
// The common case is the beginning or the end because this is used to insert
// new items that are added to history, which is usually sorted by date.
int32_t res;
res = aComparator(aNode, mChildren[0], data);
if (res <= 0) {
if (aItemExists && res == 0)
(*aItemExists) = true;
return 0;
}
res = aComparator(aNode, mChildren[mChildren.Count() - 1], data);
if (res >= 0) {
if (aItemExists && res == 0)
(*aItemExists) = true;
return mChildren.Count();
}
uint32_t beginRange = 0; // inclusive
uint32_t endRange = mChildren.Count(); // exclusive
while (1) {
if (beginRange == endRange)
return endRange;
uint32_t center = beginRange + (endRange - beginRange) / 2;
int32_t res = aComparator(aNode, mChildren[center], data);
if (res <= 0) {
endRange = center; // left side
if (aItemExists && res == 0)
(*aItemExists) = true;
}
else {
beginRange = center + 1; // right site
}
}
}
/**
* This checks the child node at the given index to see if its sorting is
* correct. This is called when nodes are updated and we need to see whether
* we need to move it.
*
* @returns true if not and it should be resorted.
*/
bool
nsNavHistoryContainerResultNode::DoesChildNeedResorting(uint32_t aIndex,
SortComparator aComparator, const char* aData)
{
NS_ASSERTION(aIndex < uint32_t(mChildren.Count()),
"Input index out of range");
if (mChildren.Count() == 1)
return false;
void* data = const_cast<void*>(static_cast<const void*>(aData));
if (aIndex > 0) {
// compare to previous item
if (aComparator(mChildren[aIndex - 1], mChildren[aIndex], data) > 0)
return true;
}
if (aIndex < uint32_t(mChildren.Count()) - 1) {
// compare to next item
if (aComparator(mChildren[aIndex], mChildren[aIndex + 1], data) > 0)
return true;
}
return false;
}
/* static */
int32_t nsNavHistoryContainerResultNode::SortComparison_StringLess(
const nsAString& a, const nsAString& b) {
nsNavHistory* history = nsNavHistory::GetHistoryService();
NS_ENSURE_TRUE(history, 0);
nsICollation* collation = history->GetCollation();
NS_ENSURE_TRUE(collation, 0);
int32_t res = 0;
collation->CompareString(nsICollation::kCollationCaseInSensitive, a, b, &res);
return res;
}
/**
* When there are bookmark indices, we should never have ties, so we don't
* need to worry about tiebreaking. When there are no bookmark indices,
* everything will be -1 and we don't worry about sorting.
*/
int32_t nsNavHistoryContainerResultNode::SortComparison_Bookmark(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
return a->mBookmarkIndex - b->mBookmarkIndex;
}
/**
* These are a little more complicated because they do a localization
* conversion. If this is too slow, we can compute the sort keys once in
* advance, sort that array, and then reorder the real array accordingly.
* This would save some key generations.
*
* The collation object must be allocated before sorting on title!
*/
int32_t nsNavHistoryContainerResultNode::SortComparison_TitleLess(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
uint32_t aType;
a->GetType(&aType);
int32_t value = SortComparison_StringLess(NS_ConvertUTF8toUTF16(a->mTitle),
NS_ConvertUTF8toUTF16(b->mTitle));
if (value == 0) {
// resolve by URI
if (a->IsURI()) {
value = a->mURI.Compare(b->mURI.get());
}
if (value == 0) {
// resolve by date
value = ComparePRTime(a->mTime, b->mTime);
if (value == 0)
value = nsNavHistoryContainerResultNode::SortComparison_Bookmark(a, b, closure);
}
}
return value;
}
int32_t nsNavHistoryContainerResultNode::SortComparison_TitleGreater(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
return -SortComparison_TitleLess(a, b, closure);
}
/**
* Equal times will be very unusual, but it is important that there is some
* deterministic ordering of the results so they don't move around.
*/
int32_t nsNavHistoryContainerResultNode::SortComparison_DateLess(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
int32_t value = ComparePRTime(a->mTime, b->mTime);
if (value == 0) {
value = SortComparison_StringLess(NS_ConvertUTF8toUTF16(a->mTitle),
NS_ConvertUTF8toUTF16(b->mTitle));
if (value == 0)
value = nsNavHistoryContainerResultNode::SortComparison_Bookmark(a, b, closure);
}
return value;
}
int32_t nsNavHistoryContainerResultNode::SortComparison_DateGreater(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
return -nsNavHistoryContainerResultNode::SortComparison_DateLess(a, b, closure);
}
int32_t nsNavHistoryContainerResultNode::SortComparison_DateAddedLess(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
int32_t value = ComparePRTime(a->mDateAdded, b->mDateAdded);
if (value == 0) {
value = SortComparison_StringLess(NS_ConvertUTF8toUTF16(a->mTitle),
NS_ConvertUTF8toUTF16(b->mTitle));
if (value == 0)
value = nsNavHistoryContainerResultNode::SortComparison_Bookmark(a, b, closure);
}
return value;
}
int32_t nsNavHistoryContainerResultNode::SortComparison_DateAddedGreater(
nsNavHistoryResultNode* a, nsNavHistoryResultNode* b, void* closure)
{
return -nsNavHistoryContainerResultNode::SortComparison_DateAddedLess(a, b, closure);
}