forked from sailfishos/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsAutoCompleteController.cpp
1767 lines (1498 loc) · 59.6 KB
/
nsAutoCompleteController.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: 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 "nsAutoCompleteController.h"
#include "nsAutoCompleteSimpleResult.h"
#include "nsNetCID.h"
#include "nsIIOService.h"
#include "nsReadableUtils.h"
#include "nsUnicharUtils.h"
#include "nsIScriptSecurityManager.h"
#include "nsIObserverService.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/Services.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/KeyboardEventBinding.h"
#include "mozilla/dom/Event.h"
static const char* kAutoCompleteSearchCID =
"@mozilla.org/autocomplete/search;1?name=";
using namespace mozilla;
NS_IMPL_CYCLE_COLLECTION_CLASS(nsAutoCompleteController)
MOZ_CAN_RUN_SCRIPT_BOUNDARY
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsAutoCompleteController)
MOZ_KnownLive(tmp)->SetInput(nullptr);
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsAutoCompleteController)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInput)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSearches)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResults)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResultCache)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsAutoCompleteController)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsAutoCompleteController)
NS_INTERFACE_TABLE_HEAD(nsAutoCompleteController)
NS_INTERFACE_TABLE(nsAutoCompleteController, nsIAutoCompleteController,
nsIAutoCompleteObserver, nsITimerCallback, nsINamed)
NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(nsAutoCompleteController)
NS_INTERFACE_MAP_END
nsAutoCompleteController::nsAutoCompleteController()
: mDefaultIndexCompleted(false),
mPopupClosedByCompositionStart(false),
mProhibitAutoFill(false),
mUserClearedAutoFill(false),
mClearingAutoFillSearchesAgain(false),
mCompositionState(eCompositionState_None),
mSearchStatus(nsAutoCompleteController::STATUS_NONE),
mMatchCount(0),
mSearchesOngoing(0),
mSearchesFailed(0),
mImmediateSearchesCount(0),
mCompletedSelectionIndex(-1) {}
nsAutoCompleteController::~nsAutoCompleteController() { SetInput(nullptr); }
void nsAutoCompleteController::SetValueOfInputTo(const nsString& aValue) {
mSetValue = aValue;
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
input->SetTextValue(aValue);
}
////////////////////////////////////////////////////////////////////////
//// nsIAutoCompleteController
NS_IMETHODIMP
nsAutoCompleteController::GetSearchStatus(uint16_t* aSearchStatus) {
*aSearchStatus = mSearchStatus;
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::GetMatchCount(uint32_t* aMatchCount) {
*aMatchCount = mMatchCount;
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::GetInput(nsIAutoCompleteInput** aInput) {
*aInput = mInput;
NS_IF_ADDREF(*aInput);
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::SetInitiallySelectedIndex(int32_t aSelectedIndex) {
// First forward to the popup.
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
NS_ENSURE_STATE(input);
nsCOMPtr<nsIAutoCompletePopup> popup(GetPopup());
NS_ENSURE_STATE(popup);
popup->SetSelectedIndex(aSelectedIndex);
// Now take care of internal stuff.
bool completeSelection;
if (NS_SUCCEEDED(input->GetCompleteSelectedIndex(&completeSelection)) &&
completeSelection) {
mCompletedSelectionIndex = aSelectedIndex;
}
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::SetInput(nsIAutoCompleteInput* aInput) {
// Don't do anything if the input isn't changing.
if (mInput == aInput) return NS_OK;
Unused << ResetInternalState();
if (mInput) {
mSearches.Clear();
ClosePopup();
}
mInput = aInput;
// Nothing more to do if the input was just being set to null.
if (!mInput) {
return NS_OK;
}
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
// Reset the current search string.
nsAutoString value;
input->GetTextValue(value);
SetSearchStringInternal(value);
// Since the controller can be used as a service it's important to reset this.
mClearingAutoFillSearchesAgain = false;
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::ResetInternalState() {
// Clear out the current search context
if (mInput) {
nsAutoString value;
mInput->GetTextValue(value);
// Stop all searches in case they are async.
Unused << StopSearch();
Unused << ClearResults();
SetSearchStringInternal(value);
}
mPlaceholderCompletionString.Truncate();
mDefaultIndexCompleted = false;
mProhibitAutoFill = false;
mSearchStatus = nsIAutoCompleteController::STATUS_NONE;
mMatchCount = 0;
mCompletedSelectionIndex = -1;
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::StartSearch(const nsAString& aSearchString) {
// If composition is ongoing don't start searching yet, until it is committed.
if (mCompositionState == eCompositionState_Composing) {
return NS_OK;
}
SetSearchStringInternal(aSearchString);
StartSearches();
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleText(bool* _retval) {
*_retval = false;
// Note: the events occur in the following order when IME is used.
// 1. a compositionstart event(HandleStartComposition)
// 2. some input events (HandleText), eCompositionState_Composing
// 3. a compositionend event(HandleEndComposition)
// 4. an input event(HandleText), eCompositionState_Committing
// We should do nothing during composition.
if (mCompositionState == eCompositionState_Composing) {
return NS_OK;
}
bool handlingCompositionCommit =
(mCompositionState == eCompositionState_Committing);
bool popupClosedByCompositionStart = mPopupClosedByCompositionStart;
if (handlingCompositionCommit) {
mCompositionState = eCompositionState_None;
mPopupClosedByCompositionStart = false;
}
if (!mInput) {
// Stop all searches in case they are async.
StopSearch();
// Note: if now is after blur and IME end composition,
// check mInput before calling.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=193544#c31
NS_ERROR(
"Called before attaching to the control or after detaching from the "
"control");
return NS_OK;
}
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
nsAutoString newValue;
input->GetTextValue(newValue);
// Stop all searches in case they are async.
StopSearch();
if (!mInput) {
// StopSearch() can call PostSearchCleanup() which might result
// in a blur event, which could null out mInput, so we need to check it
// again. See bug #395344 for more details
return NS_OK;
}
bool disabled;
input->GetDisableAutoComplete(&disabled);
NS_ENSURE_TRUE(!disabled, NS_OK);
// Usually we don't search again if the new string is the same as the last
// one. However, if this is called immediately after compositionend event, we
// need to search the same value again since the search was canceled at
// compositionstart event handler. The new string might also be the same as
// the last search if the autofilled portion was cleared. In this case, we may
// want to search again.
// Whether the user removed some text at the end.
bool userRemovedText =
newValue.Length() < mSearchString.Length() &&
Substring(mSearchString, 0, newValue.Length()).Equals(newValue);
// Whether the user is repeating the previous search.
bool repeatingPreviousSearch =
!userRemovedText && newValue.Equals(mSearchString);
mUserClearedAutoFill =
repeatingPreviousSearch &&
newValue.Length() < mPlaceholderCompletionString.Length() &&
Substring(mPlaceholderCompletionString, 0, newValue.Length())
.Equals(newValue);
bool searchAgainOnAutoFillClear =
mUserClearedAutoFill && mClearingAutoFillSearchesAgain;
if (!handlingCompositionCommit && !searchAgainOnAutoFillClear &&
newValue.Length() > 0 && repeatingPreviousSearch) {
return NS_OK;
}
if (userRemovedText || searchAgainOnAutoFillClear) {
if (userRemovedText) {
// We need to throw away previous results so we don't try to search
// through them again.
ClearResults();
}
mProhibitAutoFill = true;
mPlaceholderCompletionString.Truncate();
} else {
mProhibitAutoFill = false;
}
SetSearchStringInternal(newValue);
bool noRollupOnEmptySearch;
nsresult rv = input->GetNoRollupOnEmptySearch(&noRollupOnEmptySearch);
NS_ENSURE_SUCCESS(rv, rv);
// Don't search if the value is empty
if (newValue.Length() == 0 && !noRollupOnEmptySearch) {
// If autocomplete popup was closed by compositionstart event handler,
// we should reopen it forcibly even if the value is empty.
if (popupClosedByCompositionStart && handlingCompositionCommit) {
bool cancel;
HandleKeyNavigation(dom::KeyboardEvent_Binding::DOM_VK_DOWN, &cancel);
return NS_OK;
}
ClosePopup();
return NS_OK;
}
*_retval = true;
StartSearches();
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleEnter(bool aIsPopupSelection,
dom::Event* aEvent, bool* _retval) {
*_retval = false;
if (!mInput) return NS_OK;
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
// allow the event through unless there is something selected in the popup
input->GetPopupOpen(_retval);
if (*_retval) {
nsCOMPtr<nsIAutoCompletePopup> popup(GetPopup());
if (popup) {
int32_t selectedIndex;
popup->GetSelectedIndex(&selectedIndex);
*_retval = selectedIndex >= 0;
}
}
// Stop the search, and handle the enter.
StopSearch();
// StopSearch() can call PostSearchCleanup() which might result
// in a blur event, which could null out mInput, so we need to check it
// again. See bug #408463 for more details
if (!mInput) {
return NS_OK;
}
EnterMatch(aIsPopupSelection, aEvent);
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleEscape(bool* _retval) {
*_retval = false;
if (!mInput) return NS_OK;
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
// allow the event through if the popup is closed
input->GetPopupOpen(_retval);
// Stop all searches in case they are async.
StopSearch();
ClearResults();
RevertTextValue();
ClosePopup();
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleStartComposition() {
NS_ENSURE_TRUE(mCompositionState != eCompositionState_Composing, NS_OK);
mPopupClosedByCompositionStart = false;
mCompositionState = eCompositionState_Composing;
if (!mInput) return NS_OK;
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
bool disabled;
input->GetDisableAutoComplete(&disabled);
if (disabled) return NS_OK;
// Stop all searches in case they are async.
StopSearch();
bool isOpen = false;
input->GetPopupOpen(&isOpen);
if (isOpen) {
ClosePopup();
bool stillOpen = false;
input->GetPopupOpen(&stillOpen);
mPopupClosedByCompositionStart = !stillOpen;
}
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleEndComposition() {
NS_ENSURE_TRUE(mCompositionState == eCompositionState_Composing, NS_OK);
// We can't yet retrieve the committed value from the editor, since it isn't
// completely committed yet. Set mCompositionState to
// eCompositionState_Committing, so that when HandleText() is called (in
// response to the "input" event), we know that we should handle the
// committed text.
mCompositionState = eCompositionState_Committing;
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleTab() {
bool cancel;
return HandleEnter(false, nullptr, &cancel);
}
NS_IMETHODIMP
nsAutoCompleteController::HandleKeyNavigation(uint32_t aKey, bool* _retval) {
// By default, don't cancel the event
*_retval = false;
if (!mInput) {
// Stop all searches in case they are async.
StopSearch();
// Note: if now is after blur and IME end composition,
// check mInput before calling.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=193544#c31
NS_ERROR(
"Called before attaching to the control or after detaching from the "
"control");
return NS_OK;
}
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
nsCOMPtr<nsIAutoCompletePopup> popup(GetPopup());
NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
bool disabled;
input->GetDisableAutoComplete(&disabled);
NS_ENSURE_TRUE(!disabled, NS_OK);
if (aKey == dom::KeyboardEvent_Binding::DOM_VK_UP ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_DOWN ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_PAGE_UP ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_PAGE_DOWN) {
bool isOpen = false;
input->GetPopupOpen(&isOpen);
if (isOpen) {
// Prevent the input from handling up/down events, as it may move
// the cursor to home/end on some systems
*_retval = true;
bool reverse = aKey == dom::KeyboardEvent_Binding::DOM_VK_UP ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_PAGE_UP;
bool page = aKey == dom::KeyboardEvent_Binding::DOM_VK_PAGE_UP ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_PAGE_DOWN;
// Fill in the value of the textbox with whatever is selected in the popup
// if the completeSelectedIndex attribute is set. We check this before
// calling SelectBy of an earlier attempt to avoid crashing.
bool completeSelection;
input->GetCompleteSelectedIndex(&completeSelection);
// The user has keyed up or down to change the selection. Stop the search
// (if there is one) now so that the results do not change while the user
// is making a selection.
Unused << StopSearch();
// Instruct the result view to scroll by the given amount and direction
popup->SelectBy(reverse, page);
if (completeSelection) {
int32_t selectedIndex;
popup->GetSelectedIndex(&selectedIndex);
if (selectedIndex >= 0) {
// A result is selected, so fill in its value
nsAutoString value;
if (NS_SUCCEEDED(GetResultValueAt(selectedIndex, false, value))) {
// If the result is the previously autofilled string, then restore
// the search string and selection that existed when the result was
// autofilled. Else, fill the result and move the caret to the end.
int32_t start;
if (value.Equals(mPlaceholderCompletionString,
nsCaseInsensitiveStringComparator)) {
start = mSearchString.Length();
value = mPlaceholderCompletionString;
SetValueOfInputTo(value);
} else {
start = value.Length();
SetValueOfInputTo(value);
}
input->SelectTextRange(start, value.Length());
}
mCompletedSelectionIndex = selectedIndex;
} else {
// Nothing is selected, so fill in the last typed value
SetValueOfInputTo(mSearchString);
input->SelectTextRange(mSearchString.Length(),
mSearchString.Length());
mCompletedSelectionIndex = -1;
}
}
} else {
// Only show the popup if the caret is at the start or end of the input
// and there is no selection, so that the default defined key shortcuts
// for up and down move to the beginning and end of the field otherwise.
if (aKey == dom::KeyboardEvent_Binding::DOM_VK_UP ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_DOWN) {
const bool isUp = aKey == dom::KeyboardEvent_Binding::DOM_VK_UP;
int32_t start, end;
input->GetSelectionStart(&start);
input->GetSelectionEnd(&end);
if (isUp) {
if (start > 0 || start != end) {
return NS_OK;
}
} else {
nsAutoString text;
input->GetTextValue(text);
if (start != end || end < (int32_t)text.Length()) {
return NS_OK;
}
}
}
nsAutoString oldSearchString;
uint16_t oldResult = 0;
// Open the popup if there has been a previous non-errored search, or
// else kick off a new search
if (!mResults.IsEmpty() &&
NS_SUCCEEDED(mResults[0]->GetSearchResult(&oldResult)) &&
oldResult != nsIAutoCompleteResult::RESULT_FAILURE &&
NS_SUCCEEDED(mResults[0]->GetSearchString(oldSearchString)) &&
oldSearchString.Equals(mSearchString,
nsCaseInsensitiveStringComparator)) {
if (mMatchCount) {
OpenPopup();
}
} else {
// Stop all searches in case they are async.
StopSearch();
if (!mInput) {
// StopSearch() can call PostSearchCleanup() which might result
// in a blur event, which could null out mInput, so we need to check
// it again. See bug #395344 for more details
return NS_OK;
}
// Some script may have changed the value of the text field since our
// last keypress or after our focus handler and we don't want to
// search for a stale string.
nsAutoString value;
input->GetTextValue(value);
SetSearchStringInternal(value);
StartSearches();
}
bool isOpen = false;
input->GetPopupOpen(&isOpen);
if (isOpen) {
// Prevent the default action if we opened the popup in any of the code
// paths above.
*_retval = true;
}
}
} else if (aKey == dom::KeyboardEvent_Binding::DOM_VK_LEFT ||
aKey == dom::KeyboardEvent_Binding::DOM_VK_RIGHT
#ifndef XP_MACOSX
|| aKey == dom::KeyboardEvent_Binding::DOM_VK_HOME
#endif
) {
// The user hit a text-navigation key.
bool isOpen = false;
input->GetPopupOpen(&isOpen);
// If minresultsforpopup > 1 and there's less matches than the minimum
// required, the popup is not open, but the search suggestion is showing
// inline, so we should proceed as if we had the popup.
uint32_t minResultsForPopup;
input->GetMinResultsForPopup(&minResultsForPopup);
if (isOpen || (mMatchCount > 0 && mMatchCount < minResultsForPopup)) {
// For completeSelectedIndex autocomplete fields, if the popup shouldn't
// close when the caret is moved, don't adjust the text value or caret
// position.
bool completeSelection;
input->GetCompleteSelectedIndex(&completeSelection);
if (isOpen) {
bool noRollup;
input->GetNoRollupOnCaretMove(&noRollup);
if (noRollup) {
if (completeSelection) {
return NS_OK;
}
}
}
int32_t selectionEnd;
input->GetSelectionEnd(&selectionEnd);
int32_t selectionStart;
input->GetSelectionStart(&selectionStart);
bool shouldCompleteSelection =
(uint32_t)selectionEnd == mPlaceholderCompletionString.Length() &&
selectionStart < selectionEnd;
int32_t selectedIndex;
popup->GetSelectedIndex(&selectedIndex);
bool completeDefaultIndex;
input->GetCompleteDefaultIndex(&completeDefaultIndex);
if (completeDefaultIndex && shouldCompleteSelection) {
// We usually try to preserve the casing of what user has typed, but
// if he wants to autocomplete, we will replace the value with the
// actual autocomplete result. Note that the autocomplete input can also
// be showing e.g. "bar >> foo bar" if the search matched "bar", a
// word not at the start of the full value "foo bar".
// The user wants explicitely to use that result, so this ensures
// association of the result with the autocompleted text.
nsAutoString value;
nsAutoString inputValue;
input->GetTextValue(inputValue);
if (NS_SUCCEEDED(GetDefaultCompleteValue(-1, false, value))) {
nsAutoString suggestedValue;
int32_t pos = inputValue.Find(u" >> ");
if (pos > 0) {
inputValue.Right(suggestedValue, inputValue.Length() - pos - 4);
} else {
suggestedValue = inputValue;
}
if (value.Equals(suggestedValue, nsCaseInsensitiveStringComparator)) {
SetValueOfInputTo(value);
input->SelectTextRange(value.Length(), value.Length());
}
}
} else if (!completeDefaultIndex && !completeSelection &&
selectedIndex >= 0) {
// The pop-up is open and has a selection, take its value
nsAutoString value;
if (NS_SUCCEEDED(GetResultValueAt(selectedIndex, false, value))) {
SetValueOfInputTo(value);
input->SelectTextRange(value.Length(), value.Length());
}
}
// Close the pop-up even if nothing was selected
ClearSearchTimer();
ClosePopup();
}
// Update last-searched string to the current input, since the input may
// have changed. Without this, subsequent backspaces look like text
// additions, not text deletions.
nsAutoString value;
input->GetTextValue(value);
SetSearchStringInternal(value);
}
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::HandleDelete(bool* _retval) {
*_retval = false;
if (!mInput) return NS_OK;
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
bool isOpen = false;
input->GetPopupOpen(&isOpen);
if (!isOpen || mMatchCount == 0) {
// Nothing left to delete, proceed as normal
bool unused = false;
HandleText(&unused);
return NS_OK;
}
nsCOMPtr<nsIAutoCompletePopup> popup(GetPopup());
NS_ENSURE_TRUE(popup, NS_ERROR_FAILURE);
int32_t index, searchIndex, matchIndex;
popup->GetSelectedIndex(&index);
if (index == -1) {
// No match is selected in the list
bool unused = false;
HandleText(&unused);
return NS_OK;
}
MatchIndexToSearch(index, &searchIndex, &matchIndex);
NS_ENSURE_TRUE(searchIndex >= 0 && matchIndex >= 0, NS_ERROR_FAILURE);
nsIAutoCompleteResult* result = mResults.SafeObjectAt(searchIndex);
NS_ENSURE_TRUE(result, NS_ERROR_FAILURE);
bool removable;
nsresult rv = result->IsRemovableAt(matchIndex, &removable);
NS_ENSURE_SUCCESS(rv, rv);
if (!removable) {
return NS_OK;
}
nsAutoString search;
input->GetSearchParam(search);
// Clear the match in our result and in the DB.
result->RemoveValueAt(matchIndex);
--mMatchCount;
// We removed it, so make sure we cancel the event that triggered this call.
*_retval = true;
// Unselect the current item.
popup->SetSelectedIndex(-1);
// Adjust index, if needed.
MOZ_ASSERT(index >= 0); // We verified this above, after MatchIndexToSearch.
if (static_cast<uint32_t>(index) >= mMatchCount) index = mMatchCount - 1;
if (mMatchCount > 0) {
// There are still matches in the popup, select the current index again.
popup->SetSelectedIndex(index);
// Complete to the new current value.
bool shouldComplete = false;
input->GetCompleteDefaultIndex(&shouldComplete);
if (shouldComplete) {
nsAutoString value;
if (NS_SUCCEEDED(GetResultValueAt(index, false, value))) {
CompleteValue(value);
}
}
// Invalidate the popup.
popup->Invalidate(nsIAutoCompletePopup::INVALIDATE_REASON_DELETE);
} else {
// Nothing left in the popup, clear any pending search timers and
// close the popup.
ClearSearchTimer();
uint32_t minResults;
input->GetMinResultsForPopup(&minResults);
if (minResults) {
ClosePopup();
}
}
return NS_OK;
}
nsresult nsAutoCompleteController::GetResultAt(int32_t aIndex,
nsIAutoCompleteResult** aResult,
int32_t* aMatchIndex) {
int32_t searchIndex;
MatchIndexToSearch(aIndex, &searchIndex, aMatchIndex);
NS_ENSURE_TRUE(searchIndex >= 0 && *aMatchIndex >= 0, NS_ERROR_FAILURE);
*aResult = mResults.SafeObjectAt(searchIndex);
NS_ENSURE_TRUE(*aResult, NS_ERROR_FAILURE);
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::GetValueAt(int32_t aIndex, nsAString& _retval) {
GetResultLabelAt(aIndex, _retval);
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::GetLabelAt(int32_t aIndex, nsAString& _retval) {
GetResultLabelAt(aIndex, _retval);
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::GetCommentAt(int32_t aIndex, nsAString& _retval) {
int32_t matchIndex;
nsIAutoCompleteResult* result;
nsresult rv = GetResultAt(aIndex, &result, &matchIndex);
NS_ENSURE_SUCCESS(rv, rv);
return result->GetCommentAt(matchIndex, _retval);
}
NS_IMETHODIMP
nsAutoCompleteController::GetStyleAt(int32_t aIndex, nsAString& _retval) {
int32_t matchIndex;
nsIAutoCompleteResult* result;
nsresult rv = GetResultAt(aIndex, &result, &matchIndex);
NS_ENSURE_SUCCESS(rv, rv);
return result->GetStyleAt(matchIndex, _retval);
}
NS_IMETHODIMP
nsAutoCompleteController::GetImageAt(int32_t aIndex, nsAString& _retval) {
int32_t matchIndex;
nsIAutoCompleteResult* result;
nsresult rv = GetResultAt(aIndex, &result, &matchIndex);
NS_ENSURE_SUCCESS(rv, rv);
return result->GetImageAt(matchIndex, _retval);
}
NS_IMETHODIMP
nsAutoCompleteController::GetFinalCompleteValueAt(int32_t aIndex,
nsAString& _retval) {
int32_t matchIndex;
nsIAutoCompleteResult* result;
nsresult rv = GetResultAt(aIndex, &result, &matchIndex);
NS_ENSURE_SUCCESS(rv, rv);
return result->GetFinalCompleteValueAt(matchIndex, _retval);
}
NS_IMETHODIMP
nsAutoCompleteController::SetSearchString(const nsAString& aSearchString) {
SetSearchStringInternal(aSearchString);
return NS_OK;
}
NS_IMETHODIMP
nsAutoCompleteController::GetSearchString(nsAString& aSearchString) {
aSearchString = mSearchString;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////
//// nsIAutoCompleteObserver
NS_IMETHODIMP
nsAutoCompleteController::OnSearchResult(nsIAutoCompleteSearch* aSearch,
nsIAutoCompleteResult* aResult) {
MOZ_ASSERT(mSearchesOngoing > 0 && mSearches.Contains(aSearch));
uint16_t result = 0;
if (aResult) {
aResult->GetSearchResult(&result);
}
// If our results are incremental, the search is still ongoing.
if (result != nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING &&
result != nsIAutoCompleteResult::RESULT_NOMATCH_ONGOING) {
--mSearchesOngoing;
}
// Look up the index of the search which is returning.
for (uint32_t i = 0; i < mSearches.Length(); ++i) {
if (mSearches[i] == aSearch) {
ProcessResult(i, aResult);
break;
}
}
// If a match is found in ProcessResult, PostSearchCleanup will open the popup
PostSearchCleanup();
return NS_OK;
}
////////////////////////////////////////////////////////////////////////
//// nsITimerCallback
MOZ_CAN_RUN_SCRIPT_BOUNDARY
NS_IMETHODIMP
nsAutoCompleteController::Notify(nsITimer* timer) {
mTimer = nullptr;
if (mImmediateSearchesCount == 0) {
// If there were no immediate searches, BeforeSearches has not yet been
// called, so do it now.
nsresult rv = BeforeSearches();
if (NS_FAILED(rv)) return rv;
}
StartSearch(nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_DELAYED);
AfterSearches();
return NS_OK;
}
////////////////////////////////////////////////////////////////////////
//// nsINamed
NS_IMETHODIMP
nsAutoCompleteController::GetName(nsACString& aName) {
aName.AssignLiteral("nsAutoCompleteController");
return NS_OK;
}
////////////////////////////////////////////////////////////////////////
//// nsAutoCompleteController
nsresult nsAutoCompleteController::OpenPopup() {
uint32_t minResults;
mInput->GetMinResultsForPopup(&minResults);
if (mMatchCount >= minResults) {
nsCOMPtr<nsIAutoCompleteInput> input = mInput;
return input->SetPopupOpen(true);
}
return NS_OK;
}
nsresult nsAutoCompleteController::ClosePopup() {
if (!mInput) {
return NS_OK;
}
nsCOMPtr<nsIAutoCompleteInput> input(mInput);
bool isOpen = false;
input->GetPopupOpen(&isOpen);
if (!isOpen) return NS_OK;
nsCOMPtr<nsIAutoCompletePopup> popup(GetPopup());
NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
MOZ_ALWAYS_SUCCEEDS(input->SetPopupOpen(false));
return popup->SetSelectedIndex(-1);
}
nsresult nsAutoCompleteController::BeforeSearches() {
NS_ENSURE_STATE(mInput);
mSearchStatus = nsIAutoCompleteController::STATUS_SEARCHING;
mDefaultIndexCompleted = false;
bool invalidatePreviousResult = false;
mInput->GetInvalidatePreviousResult(&invalidatePreviousResult);
if (!invalidatePreviousResult) {
// ClearResults will clear the mResults array, but we should pass the
// previous result to each search to allow reusing it. So we temporarily
// cache the current results until AfterSearches().
if (!mResultCache.AppendObjects(mResults)) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
ClearResults(true);
mSearchesOngoing = mSearches.Length();
mSearchesFailed = 0;
// notify the input that the search is beginning
mInput->OnSearchBegin();
return NS_OK;
}
nsresult nsAutoCompleteController::StartSearch(uint16_t aSearchType) {
NS_ENSURE_STATE(mInput);
nsCOMPtr<nsIAutoCompleteInput> input = mInput;
// Iterate a copy of |mSearches| so that we don't run into trouble if the
// array is mutated while we're still in the loop. An nsIAutoCompleteSearch
// implementation could synchronously start a new search when StartSearch()
// is called and that would lead to assertions down the way.
nsCOMArray<nsIAutoCompleteSearch> searchesCopy(mSearches);
for (uint32_t i = 0; i < searchesCopy.Length(); ++i) {
nsCOMPtr<nsIAutoCompleteSearch> search = searchesCopy[i];
// Filter on search type. Not all the searches implement this interface,
// in such a case just consider them delayed.
uint16_t searchType = nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_DELAYED;
nsCOMPtr<nsIAutoCompleteSearchDescriptor> searchDesc =
do_QueryInterface(search);
if (searchDesc) searchDesc->GetSearchType(&searchType);
if (searchType != aSearchType) continue;
nsIAutoCompleteResult* result = mResultCache.SafeObjectAt(i);
if (result) {
uint16_t searchResult;
result->GetSearchResult(&searchResult);
if (searchResult != nsIAutoCompleteResult::RESULT_SUCCESS &&
searchResult != nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING &&
searchResult != nsIAutoCompleteResult::RESULT_NOMATCH)
result = nullptr;
}
nsAutoString searchParam;
nsresult rv = input->GetSearchParam(searchParam);
if (NS_FAILED(rv)) return rv;
// FormFill expects the searchParam to only contain the input element id,
// other consumers may have other expectations, so this modifies it only
// for new consumers handling autoFill by themselves.
if (mProhibitAutoFill && mClearingAutoFillSearchesAgain) {
searchParam.AppendLiteral(" prohibit-autofill");
}
uint32_t userContextId;
rv = input->GetUserContextId(&userContextId);
if (NS_SUCCEEDED(rv) &&
userContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
searchParam.AppendLiteral(" user-context-id:");
searchParam.AppendInt(userContextId, 10);
}
rv = search->StartSearch(mSearchString, searchParam, result,
static_cast<nsIAutoCompleteObserver*>(this),
nullptr);
if (NS_FAILED(rv)) {
++mSearchesFailed;
MOZ_ASSERT(mSearchesOngoing > 0);
--mSearchesOngoing;
}
// Because of the joy of nested event loops (which can easily happen when
// some code uses a generator for an asynchronous AutoComplete search),
// nsIAutoCompleteSearch::StartSearch might cause us to be detached from our
// input field. The next time we iterate, we'd be touching something that
// we shouldn't be, and result in a crash.
if (!mInput) {
// The search operation has been finished.
return NS_OK;
}
}
return NS_OK;
}
void nsAutoCompleteController::AfterSearches() {
mResultCache.Clear();
// if the below evaluates to true, that means mSearchesOngoing must be 0
if (mSearchesFailed == mSearches.Length()) {
PostSearchCleanup();