forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsXULTemplateBuilder.cpp
2663 lines (2218 loc) · 90 KB
/
nsXULTemplateBuilder.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: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Robert Churchill <rjc@netscape.com>
* David Hyatt <hyatt@netscape.com>
* Chris Waterson <waterson@netscape.com>
* Pierre Phaneuf <pp@ludusdesign.com>
* Joe Hewitt <hewitt@netscape.com>
* Neil Deakin <enndeakin@sympatico.ca>
* Laurent Jouanneau <laurent.jouanneau@disruptive-innovations.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
Builds content from a datasource using the XUL <template> tag.
TO DO
. Fix ContentTagTest's location in the network construction
To turn on logging for this module, set:
NSPR_LOG_MODULES nsXULTemplateBuilder:5
*/
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsFixedSizeAllocator.h"
#include "nsIContent.h"
#include "nsIDOMElement.h"
#include "nsIDOMNode.h"
#include "nsIDOMDocument.h"
#include "nsIDOMXMLDocument.h"
#include "nsIDOMXULElement.h"
#include "nsIDocument.h"
#include "nsBindingManager.h"
#include "nsIDOMNodeList.h"
#include "nsINameSpaceManager.h"
#include "nsIObserverService.h"
#include "nsIRDFCompositeDataSource.h"
#include "nsIRDFInferDataSource.h"
#include "nsIRDFContainerUtils.h"
#include "nsIXULDocument.h"
#include "nsIXULTemplateBuilder.h"
#include "nsIXULBuilderListener.h"
#include "nsIRDFRemoteDataSource.h"
#include "nsIRDFService.h"
#include "nsIScriptGlobalObject.h"
#include "nsIServiceManager.h"
#include "nsISimpleEnumerator.h"
#include "nsISupportsArray.h"
#include "nsIMutableArray.h"
#include "nsIURL.h"
#include "nsIXPConnect.h"
#include "nsContentCID.h"
#include "nsRDFCID.h"
#include "nsXULContentUtils.h"
#include "nsString.h"
#include "nsTArray.h"
#include "nsXPIDLString.h"
#include "nsWhitespaceTokenizer.h"
#include "nsGkAtoms.h"
#include "nsXULElement.h"
#include "jsapi.h"
#include "prlog.h"
#include "rdf.h"
#include "pldhash.h"
#include "plhash.h"
#include "nsDOMClassInfoID.h"
#include "nsPIDOMWindow.h"
#include "nsIConsoleService.h"
#include "nsNetUtil.h"
#include "nsXULTemplateBuilder.h"
#include "nsXULTemplateQueryProcessorRDF.h"
#include "nsXULTemplateQueryProcessorXML.h"
#include "nsXULTemplateQueryProcessorStorage.h"
#include "nsContentUtils.h"
using namespace mozilla::dom;
//----------------------------------------------------------------------
static NS_DEFINE_CID(kRDFContainerUtilsCID, NS_RDFCONTAINERUTILS_CID);
static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
//----------------------------------------------------------------------
//
// nsXULTemplateBuilder
//
nsrefcnt nsXULTemplateBuilder::gRefCnt = 0;
nsIRDFService* nsXULTemplateBuilder::gRDFService;
nsIRDFContainerUtils* nsXULTemplateBuilder::gRDFContainerUtils;
nsIScriptSecurityManager* nsXULTemplateBuilder::gScriptSecurityManager;
nsIPrincipal* nsXULTemplateBuilder::gSystemPrincipal;
nsIObserverService* nsXULTemplateBuilder::gObserverService;
#ifdef PR_LOGGING
PRLogModuleInfo* gXULTemplateLog;
#endif
#define NS_QUERY_PROCESSOR_CONTRACTID_PREFIX "@mozilla.org/xul/xul-query-processor;1?name="
//----------------------------------------------------------------------
//
// nsXULTemplateBuilder methods
//
nsXULTemplateBuilder::nsXULTemplateBuilder(void)
: mQueriesCompiled(false),
mFlags(0),
mTop(nsnull),
mObservedDocument(nsnull)
{
}
static PLDHashOperator
DestroyMatchList(nsISupports* aKey, nsTemplateMatch*& aMatch, void* aContext)
{
nsFixedSizeAllocator* pool = static_cast<nsFixedSizeAllocator *>(aContext);
// delete all the matches in the list
while (aMatch) {
nsTemplateMatch* next = aMatch->mNext;
nsTemplateMatch::Destroy(*pool, aMatch, true);
aMatch = next;
}
return PL_DHASH_REMOVE;
}
nsXULTemplateBuilder::~nsXULTemplateBuilder(void)
{
if (--gRefCnt == 0) {
NS_IF_RELEASE(gRDFService);
NS_IF_RELEASE(gRDFContainerUtils);
NS_IF_RELEASE(gSystemPrincipal);
NS_IF_RELEASE(gScriptSecurityManager);
NS_IF_RELEASE(gObserverService);
}
Uninit(true);
}
nsresult
nsXULTemplateBuilder::InitGlobals()
{
nsresult rv;
if (gRefCnt++ == 0) {
// Initialize the global shared reference to the service
// manager and get some shared resource objects.
rv = CallGetService(kRDFServiceCID, &gRDFService);
if (NS_FAILED(rv))
return rv;
rv = CallGetService(kRDFContainerUtilsCID, &gRDFContainerUtils);
if (NS_FAILED(rv))
return rv;
rv = CallGetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID,
&gScriptSecurityManager);
if (NS_FAILED(rv))
return rv;
rv = gScriptSecurityManager->GetSystemPrincipal(&gSystemPrincipal);
if (NS_FAILED(rv))
return rv;
rv = CallGetService(NS_OBSERVERSERVICE_CONTRACTID, &gObserverService);
if (NS_FAILED(rv))
return rv;
}
#ifdef PR_LOGGING
if (! gXULTemplateLog)
gXULTemplateLog = PR_NewLogModule("nsXULTemplateBuilder");
#endif
if (!mMatchMap.IsInitialized() && !mMatchMap.Init())
return NS_ERROR_OUT_OF_MEMORY;
const size_t bucketsizes[] = { sizeof(nsTemplateMatch) };
return mPool.Init("nsXULTemplateBuilder", bucketsizes, 1, 256);
}
void
nsXULTemplateBuilder::Uninit(bool aIsFinal)
{
if (mObservedDocument && aIsFinal) {
gObserverService->RemoveObserver(this, DOM_WINDOW_DESTROYED_TOPIC);
gObserverService->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
mObservedDocument->RemoveObserver(this);
mObservedDocument = nsnull;
}
if (mQueryProcessor)
mQueryProcessor->Done();
for (PRInt32 q = mQuerySets.Length() - 1; q >= 0; q--) {
nsTemplateQuerySet* qs = mQuerySets[q];
delete qs;
}
mQuerySets.Clear();
mMatchMap.Enumerate(DestroyMatchList, &mPool);
mRootResult = nsnull;
mRefVariable = nsnull;
mMemberVariable = nsnull;
mQueriesCompiled = false;
}
static PLDHashOperator
TraverseMatchList(nsISupports* aKey, nsTemplateMatch* aMatch, void* aContext)
{
nsCycleCollectionTraversalCallback *cb =
static_cast<nsCycleCollectionTraversalCallback*>(aContext);
cb->NoteXPCOMChild(aKey);
nsTemplateMatch* match = aMatch;
while (match) {
cb->NoteXPCOMChild(match->GetContainer());
cb->NoteXPCOMChild(match->mResult);
match = match->mNext;
}
return PL_DHASH_NEXT;
}
NS_IMPL_CYCLE_COLLECTION_CLASS(nsXULTemplateBuilder)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsXULTemplateBuilder)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDataSource)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDB)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCompDB)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRoot)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRootResult)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mListeners)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mQueryProcessor)
if (tmp->mMatchMap.IsInitialized()) {
tmp->mMatchMap.Enumerate(DestroyMatchList, &(tmp->mPool));
}
for (PRUint32 i = 0; i < tmp->mQuerySets.Length(); ++i) {
nsTemplateQuerySet* qs = tmp->mQuerySets[i];
delete qs;
}
tmp->mQuerySets.Clear();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsXULTemplateBuilder)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDataSource)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDB)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCompDB)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mRoot)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mRootResult)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mListeners)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mQueryProcessor)
if (tmp->mMatchMap.IsInitialized())
tmp->mMatchMap.EnumerateRead(TraverseMatchList, &cb);
{
PRUint32 i, count = tmp->mQuerySets.Length();
for (i = 0; i < count; ++i) {
nsTemplateQuerySet *set = tmp->mQuerySets[i];
cb.NoteXPCOMChild(set->mQueryNode);
cb.NoteXPCOMChild(set->mCompiledQuery);
PRUint16 j, rulesCount = set->RuleCount();
for (j = 0; j < rulesCount; ++j) {
set->GetRuleAt(j)->Traverse(cb);
}
}
}
tmp->Traverse(cb);
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsXULTemplateBuilder)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsXULTemplateBuilder)
DOMCI_DATA(XULTemplateBuilder, nsXULTemplateBuilder)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsXULTemplateBuilder)
NS_INTERFACE_MAP_ENTRY(nsIXULTemplateBuilder)
NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver)
NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
NS_INTERFACE_MAP_ENTRY(nsIObserver)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIXULTemplateBuilder)
NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(XULTemplateBuilder)
NS_INTERFACE_MAP_END
//----------------------------------------------------------------------
//
// nsIXULTemplateBuilder methods
//
NS_IMETHODIMP
nsXULTemplateBuilder::GetRoot(nsIDOMElement** aResult)
{
if (mRoot) {
return CallQueryInterface(mRoot, aResult);
}
*aResult = nsnull;
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::GetDatasource(nsISupports** aResult)
{
if (mCompDB)
NS_ADDREF(*aResult = mCompDB);
else
NS_IF_ADDREF(*aResult = mDataSource);
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::SetDatasource(nsISupports* aResult)
{
mDataSource = aResult;
mCompDB = do_QueryInterface(mDataSource);
return Rebuild();
}
NS_IMETHODIMP
nsXULTemplateBuilder::GetDatabase(nsIRDFCompositeDataSource** aResult)
{
NS_IF_ADDREF(*aResult = mCompDB);
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::GetQueryProcessor(nsIXULTemplateQueryProcessor** aResult)
{
NS_IF_ADDREF(*aResult = mQueryProcessor.get());
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::AddRuleFilter(nsIDOMNode* aRule, nsIXULTemplateRuleFilter* aFilter)
{
if (!aRule || !aFilter)
return NS_ERROR_NULL_POINTER;
// a custom rule filter may be added, one for each rule. If a new one is
// added, it replaces the old one. Look for the right rule and set its
// filter
PRInt32 count = mQuerySets.Length();
for (PRInt32 q = 0; q < count; q++) {
nsTemplateQuerySet* queryset = mQuerySets[q];
PRInt16 rulecount = queryset->RuleCount();
for (PRInt16 r = 0; r < rulecount; r++) {
nsTemplateRule* rule = queryset->GetRuleAt(r);
nsCOMPtr<nsIDOMNode> rulenode;
rule->GetRuleNode(getter_AddRefs(rulenode));
if (aRule == rulenode) {
rule->SetRuleFilter(aFilter);
return NS_OK;
}
}
}
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::Rebuild()
{
PRInt32 i;
for (i = mListeners.Count() - 1; i >= 0; --i) {
mListeners[i]->WillRebuild(this);
}
nsresult rv = RebuildAll();
for (i = mListeners.Count() - 1; i >= 0; --i) {
mListeners[i]->DidRebuild(this);
}
return rv;
}
NS_IMETHODIMP
nsXULTemplateBuilder::Refresh()
{
nsresult rv;
if (!mCompDB)
return NS_ERROR_FAILURE;
nsCOMPtr<nsISimpleEnumerator> dslist;
rv = mCompDB->GetDataSources(getter_AddRefs(dslist));
NS_ENSURE_SUCCESS(rv, rv);
bool hasMore;
nsCOMPtr<nsISupports> next;
nsCOMPtr<nsIRDFRemoteDataSource> rds;
while(NS_SUCCEEDED(dslist->HasMoreElements(&hasMore)) && hasMore) {
dslist->GetNext(getter_AddRefs(next));
if (next && (rds = do_QueryInterface(next))) {
rds->Refresh(false);
}
}
// XXXbsmedberg: it would be kinda nice to install an async nsIRDFXMLSink
// observer and call rebuild() once the load is complete. See bug 254600.
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::Init(nsIContent* aElement)
{
NS_ENSURE_TRUE(aElement, NS_ERROR_NULL_POINTER);
mRoot = aElement;
nsCOMPtr<nsIDocument> doc = mRoot->GetDocument();
NS_ASSERTION(doc, "element has no document");
if (! doc)
return NS_ERROR_UNEXPECTED;
bool shouldDelay;
nsresult rv = LoadDataSources(doc, &shouldDelay);
if (NS_SUCCEEDED(rv)) {
// Add ourselves as a document observer
doc->AddObserver(this);
mObservedDocument = doc;
gObserverService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID,
false);
gObserverService->AddObserver(this, DOM_WINDOW_DESTROYED_TOPIC,
false);
}
return rv;
}
NS_IMETHODIMP
nsXULTemplateBuilder::CreateContents(nsIContent* aElement, bool aForceCreation)
{
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::HasGeneratedContent(nsIRDFResource* aResource,
nsIAtom* aTag,
bool* aGenerated)
{
*aGenerated = false;
return NS_OK;
}
NS_IMETHODIMP
nsXULTemplateBuilder::AddResult(nsIXULTemplateResult* aResult,
nsIDOMNode* aQueryNode)
{
NS_ENSURE_ARG_POINTER(aResult);
NS_ENSURE_ARG_POINTER(aQueryNode);
return UpdateResult(nsnull, aResult, aQueryNode);
}
NS_IMETHODIMP
nsXULTemplateBuilder::RemoveResult(nsIXULTemplateResult* aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
return UpdateResult(aResult, nsnull, nsnull);
}
NS_IMETHODIMP
nsXULTemplateBuilder::ReplaceResult(nsIXULTemplateResult* aOldResult,
nsIXULTemplateResult* aNewResult,
nsIDOMNode* aQueryNode)
{
NS_ENSURE_ARG_POINTER(aOldResult);
NS_ENSURE_ARG_POINTER(aNewResult);
NS_ENSURE_ARG_POINTER(aQueryNode);
// just remove the old result and then add a new result separately
nsresult rv = UpdateResult(aOldResult, nsnull, nsnull);
if (NS_FAILED(rv))
return rv;
return UpdateResult(nsnull, aNewResult, aQueryNode);
}
nsresult
nsXULTemplateBuilder::UpdateResult(nsIXULTemplateResult* aOldResult,
nsIXULTemplateResult* aNewResult,
nsIDOMNode* aQueryNode)
{
PR_LOG(gXULTemplateLog, PR_LOG_ALWAYS,
("nsXULTemplateBuilder::UpdateResult %p %p %p",
aOldResult, aNewResult, aQueryNode));
if (!mRoot || !mQueriesCompiled)
return NS_OK;
// get the containers where content may be inserted. If
// GetInsertionLocations returns false, no container has generated
// any content yet so new content should not be generated either. This
// will be false if the result applies to content that is in a closed menu
// or treeitem for example.
nsAutoPtr<nsCOMArray<nsIContent> > insertionPoints;
bool mayReplace = GetInsertionLocations(aOldResult ? aOldResult : aNewResult,
getter_Transfers(insertionPoints));
if (! mayReplace)
return NS_OK;
nsresult rv = NS_OK;
nsCOMPtr<nsIRDFResource> oldId, newId;
nsTemplateQuerySet* queryset = nsnull;
if (aOldResult) {
rv = GetResultResource(aOldResult, getter_AddRefs(oldId));
if (NS_FAILED(rv))
return rv;
// Ignore re-entrant builds for content that is currently in our
// activation stack.
if (IsActivated(oldId))
return NS_OK;
}
if (aNewResult) {
rv = GetResultResource(aNewResult, getter_AddRefs(newId));
if (NS_FAILED(rv))
return rv;
// skip results that don't have ids
if (! newId)
return NS_OK;
// Ignore re-entrant builds for content that is currently in our
// activation stack.
if (IsActivated(newId))
return NS_OK;
// look for the queryset associated with the supplied query node
nsCOMPtr<nsIContent> querycontent = do_QueryInterface(aQueryNode);
PRInt32 count = mQuerySets.Length();
for (PRInt32 q = 0; q < count; q++) {
nsTemplateQuerySet* qs = mQuerySets[q];
if (qs->mQueryNode == querycontent) {
queryset = qs;
break;
}
}
if (! queryset)
return NS_OK;
}
if (insertionPoints) {
// iterate over each insertion point and add or remove the result from
// that container
PRUint32 count = insertionPoints->Count();
for (PRUint32 t = 0; t < count; t++) {
nsCOMPtr<nsIContent> insertionPoint = insertionPoints->SafeObjectAt(t);
if (insertionPoint) {
rv = UpdateResultInContainer(aOldResult, aNewResult, queryset,
oldId, newId, insertionPoint);
if (NS_FAILED(rv))
return rv;
}
}
}
else {
// The tree builder doesn't use insertion points, so no insertion
// points will be set. In this case, just update the one result.
rv = UpdateResultInContainer(aOldResult, aNewResult, queryset,
oldId, newId, nsnull);
}
return NS_OK;
}
nsresult
nsXULTemplateBuilder::UpdateResultInContainer(nsIXULTemplateResult* aOldResult,
nsIXULTemplateResult* aNewResult,
nsTemplateQuerySet* aQuerySet,
nsIRDFResource* aOldId,
nsIRDFResource* aNewId,
nsIContent* aInsertionPoint)
{
// This method takes a result that no longer applies (aOldResult) and
// replaces it with a new result (aNewResult). Either may be null
// indicating to just remove a result or add a new one without replacing.
//
// Matches are stored in the hashtable mMatchMap, keyed by result id. If
// there is more than one query, or the same id is found in different
// containers, the values in the hashtable will be a linked list of all
// the matches for that id. The matches are sorted according to the
// queries they are associated with. Matches for earlier queries in the
// template take priority over matches from later queries. The priority
// for a match is determined from the match's QuerySetPriority method.
// The first query has a priority 0, and higher numbers are for later
// queries with successively higher priorities. Thus, a match takes
// precedence if it has a lower priority than another. If there is only
// one query or container, then the match doesn't have any linked items.
//
// Matches are nsTemplateMatch objects. They are wrappers around
// nsIXULTemplateResult result objects and are created with
// nsTemplateMatch::Create below. The aQuerySet argument specifies which
// query the match is associated with.
//
// When a result id exists in multiple containers, the match's mContainer
// field is set to the container it corresponds to. The aInsertionPoint
// argument specifies which container is being updated. Even though they
// are stored in the same linked list as other matches of the same id, the
// matches for different containers are treated separately. They are only
// stored in the same hashtable to avoid a more complex data structure, as
// the use of the same id in multiple containers isn't a common occurance.
//
// Only one match with a given id per container is active at a time. When
// a match is active, content is generated for it. When a match is
// inactive, content is not generated for it. A match becomes active if
// another match with the same id and container with a lower priority
// isn't already active, and the match has a rule or conditions clause
// which evaluates to true. The former is checked by comparing the value
// of the QuerySetPriority method of the match with earlier matches. The
// latter is checked with the DetermineMatchedRule method.
//
// Naturally, if a match with a lower priority is active, it overrides
// the new match, so the new match is hooked up into the match linked
// list as inactive, and no content is generated for it. If a match with a
// higher priority is active, and the new match's conditions evaluate
// to true, then this existing match with the higher priority needs to have
// its generated content removed and replaced with the new match's
// generated content.
//
// Similar situations apply when removing an existing match. If the match
// is active, the existing generated content will need to be removed, and
// a match of higher priority that is revealed may become active and need
// to have content generated.
//
// Content removal and generation is done by the ReplaceMatch method which
// is overridden for the content builder and tree builder to update the
// generated output for each type.
//
// The code below handles all of the various cases and ensures that the
// match lists are maintained properly.
nsresult rv = NS_OK;
PRInt16 ruleindex;
nsTemplateRule* matchedrule = nsnull;
// Indicates that the old match was active and must have its content
// removed
bool oldMatchWasActive = false;
// acceptedmatch will be set to a new match that has to have new content
// generated for it. If a new match doesn't need to have content
// generated, (because for example, a match with a lower priority
// already applies), then acceptedmatch will be null, but the match will
// be still hooked up into the chain, since it may become active later
// as other results are updated.
nsTemplateMatch* acceptedmatch = nsnull;
// When aOldResult is specified, removematch will be set to the
// corresponding match. This match needs to be deleted as it no longer
// applies. However, removedmatch will be null when aOldResult is null, or
// when no match was found corresponding to aOldResult.
nsTemplateMatch* removedmatch = nsnull;
// These will be set when aNewResult is specified indicating to add a
// result, but will end up replacing an existing match. The former
// indicates a match being replaced that was active and had content
// generated for it, while the latter indicates a match that wasn't active
// and just needs to be deleted. Both may point to different matches. For
// example, if the new match becomes active, replacing an inactive match,
// the inactive match will need to be deleted. However, if another match
// with a higher priority is active, the new match will override it, so
// content will need to be generated for the new match and removed for
// this existing active match.
nsTemplateMatch* replacedmatch = nsnull, * replacedmatchtodelete = nsnull;
if (aOldResult) {
nsTemplateMatch* firstmatch;
if (mMatchMap.Get(aOldId, &firstmatch)) {
nsTemplateMatch* oldmatch = firstmatch;
nsTemplateMatch* prevmatch = nsnull;
// look for the right match if there was more than one
while (oldmatch && (oldmatch->mResult != aOldResult)) {
prevmatch = oldmatch;
oldmatch = oldmatch->mNext;
}
if (oldmatch) {
nsTemplateMatch* findmatch = oldmatch->mNext;
// Keep a reference so that linked list can be hooked up at
// the end in case an error occurs.
nsTemplateMatch* nextmatch = findmatch;
if (oldmatch->IsActive()) {
// Indicate that the old match was active so its content
// will be removed later.
oldMatchWasActive = true;
// The match being removed is the active match, so scan
// through the later matches to determine if one should
// now become the active match.
while (findmatch) {
// only other matches with the same container should
// now match, leave other containers alone
if (findmatch->GetContainer() == aInsertionPoint) {
nsTemplateQuerySet* qs =
mQuerySets[findmatch->QuerySetPriority()];
DetermineMatchedRule(aInsertionPoint, findmatch->mResult,
qs, &matchedrule, &ruleindex);
if (matchedrule) {
rv = findmatch->RuleMatched(qs,
matchedrule, ruleindex,
findmatch->mResult);
if (NS_FAILED(rv))
return rv;
acceptedmatch = findmatch;
break;
}
}
findmatch = findmatch->mNext;
}
}
if (oldmatch == firstmatch) {
// the match to remove is at the beginning
if (oldmatch->mNext) {
if (!mMatchMap.Put(aOldId, oldmatch->mNext))
return NS_ERROR_OUT_OF_MEMORY;
}
else {
mMatchMap.Remove(aOldId);
}
}
if (prevmatch)
prevmatch->mNext = nextmatch;
removedmatch = oldmatch;
if (mFlags & eLoggingEnabled)
OutputMatchToLog(aOldId, removedmatch, false);
}
}
}
nsTemplateMatch *newmatch = nsnull;
if (aNewResult) {
// only allow a result to be inserted into containers with a matching tag
nsIAtom* tag = aQuerySet->GetTag();
if (aInsertionPoint && tag && tag != aInsertionPoint->Tag())
return NS_OK;
PRInt32 findpriority = aQuerySet->Priority();
newmatch = nsTemplateMatch::Create(mPool, findpriority,
aNewResult, aInsertionPoint);
if (!newmatch)
return NS_ERROR_OUT_OF_MEMORY;
nsTemplateMatch* firstmatch;
if (mMatchMap.Get(aNewId, &firstmatch)) {
bool hasEarlierActiveMatch = false;
// Scan through the existing matches to find where the new one
// should be inserted. oldmatch will be set to the old match for
// the same query and prevmatch will be set to the match before it.
nsTemplateMatch* prevmatch = nsnull;
nsTemplateMatch* oldmatch = firstmatch;
while (oldmatch) {
// Break out once we've reached a query in the list with a
// lower priority. The new match will be inserted at this
// location so that the match list is sorted by priority.
PRInt32 priority = oldmatch->QuerySetPriority();
if (priority > findpriority) {
oldmatch = nsnull;
break;
}
// look for matches that belong in the same container
if (oldmatch->GetContainer() == aInsertionPoint) {
if (priority == findpriority)
break;
// If a match with a lower priority is active, the new
// match can't replace it.
if (oldmatch->IsActive())
hasEarlierActiveMatch = true;
}
prevmatch = oldmatch;
oldmatch = oldmatch->mNext;
}
// At this point, oldmatch will either be null, or set to a match
// with the same container and priority. If set, oldmatch will
// need to be replaced by newmatch.
if (oldmatch)
newmatch->mNext = oldmatch->mNext;
else if (prevmatch)
newmatch->mNext = prevmatch->mNext;
else
newmatch->mNext = firstmatch;
// hasEarlierActiveMatch will be set to true if a match with a
// lower priority was found. The new match won't replace it in
// this case. If hasEarlierActiveMatch is false, then the new match
// may be become active if it matches one of the rules, and will
// generate output. It's also possible however, that a match with
// the same priority already exists, which means that the new match
// will replace the old one. In this case, oldmatch will be set to
// the old match. The content for the old match must be removed and
// content for the new match generated in its place.
if (! hasEarlierActiveMatch) {
// If the old match was the active match, set replacedmatch to
// indicate that it needs its content removed.
if (oldmatch) {
if (oldmatch->IsActive())
replacedmatch = oldmatch;
replacedmatchtodelete = oldmatch;
}
// check if the new result matches the rules
rv = DetermineMatchedRule(aInsertionPoint, newmatch->mResult,
aQuerySet, &matchedrule, &ruleindex);
if (NS_FAILED(rv)) {
nsTemplateMatch::Destroy(mPool, newmatch, false);
return rv;
}
if (matchedrule) {
rv = newmatch->RuleMatched(aQuerySet,
matchedrule, ruleindex,
newmatch->mResult);
if (NS_FAILED(rv)) {
nsTemplateMatch::Destroy(mPool, newmatch, false);
return rv;
}
// acceptedmatch may have been set in the block handling
// aOldResult earlier. If so, we would only get here when
// that match has a higher priority than this new match.
// As only one match can have content generated for it, it
// is OK to set acceptedmatch here to the new match,
// ignoring the other one.
acceptedmatch = newmatch;
// Clear the matched state of the later results for the
// same container.
nsTemplateMatch* clearmatch = newmatch->mNext;
while (clearmatch) {
if (clearmatch->GetContainer() == aInsertionPoint &&
clearmatch->IsActive()) {
clearmatch->SetInactive();
// Replacedmatch should be null here. If not, it
// means that two matches were active which isn't
// a valid state
NS_ASSERTION(!replacedmatch,
"replaced match already set");
replacedmatch = clearmatch;
break;
}
clearmatch = clearmatch->mNext;
}
}
else if (oldmatch && oldmatch->IsActive()) {
// The result didn't match the rules, so look for a later
// one. However, only do this if the old match was the
// active match.
newmatch = newmatch->mNext;
while (newmatch) {
if (newmatch->GetContainer() == aInsertionPoint) {
rv = DetermineMatchedRule(aInsertionPoint, newmatch->mResult,
aQuerySet, &matchedrule, &ruleindex);
if (NS_FAILED(rv)) {
nsTemplateMatch::Destroy(mPool, newmatch,
false);
return rv;
}
if (matchedrule) {
rv = newmatch->RuleMatched(aQuerySet,
matchedrule, ruleindex,
newmatch->mResult);
if (NS_FAILED(rv)) {
nsTemplateMatch::Destroy(mPool, newmatch,
false);
return rv;
}
acceptedmatch = newmatch;
break;
}
}
newmatch = newmatch->mNext;
}
}
// put the match in the map if there isn't a previous match
if (! prevmatch) {
if (!mMatchMap.Put(aNewId, newmatch)) {
// The match may have already matched a rule above, so
// HasBeenRemoved should be called to indicate that it
// is being removed again.
nsTemplateMatch::Destroy(mPool, newmatch, true);
return rv;
}
}
}
// hook up the match last in case an error occurs
if (prevmatch)
prevmatch->mNext = newmatch;
}
else {
// The id is not used in the hashtable yet so create a new match
// and add it to the hashtable.
rv = DetermineMatchedRule(aInsertionPoint, aNewResult,
aQuerySet, &matchedrule, &ruleindex);
if (NS_FAILED(rv)) {
nsTemplateMatch::Destroy(mPool, newmatch, false);
return rv;
}
if (matchedrule) {
rv = newmatch->RuleMatched(aQuerySet, matchedrule,
ruleindex, aNewResult);
if (NS_FAILED(rv)) {
nsTemplateMatch::Destroy(mPool, newmatch, false);
return rv;
}
acceptedmatch = newmatch;
}
if (!mMatchMap.Put(aNewId, newmatch)) {
nsTemplateMatch::Destroy(mPool, newmatch, true);
return NS_ERROR_OUT_OF_MEMORY;
}
}
}
// The ReplaceMatch method is builder specific and removes the generated
// content for a match.
// Remove the content for a match that was active and needs to be replaced.
if (replacedmatch) {
rv = ReplaceMatch(replacedmatch->mResult, nsnull, nsnull,