forked from classilla/tenfourfox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTMLInputElement.cpp
More file actions
7869 lines (6861 loc) · 238 KB
/
HTMLInputElement.cpp
File metadata and controls
7869 lines (6861 loc) · 238 KB
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 "mozilla/dom/HTMLInputElement.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/dom/Date.h"
#include "mozilla/dom/Directory.h"
#include "mozilla/dom/FileSystemUtils.h"
#include "mozilla/dom/OSFileSystem.h"
#include "nsAttrValueInlines.h"
#include "nsCRTGlue.h"
#include "nsIDOMHTMLInputElement.h"
#include "nsITextControlElement.h"
#include "nsIDOMNSEditableElement.h"
#include "nsIRadioVisitor.h"
#include "nsIPhonetic.h"
#include "mozilla/Telemetry.h"
#include "nsIControllers.h"
#include "nsIStringBundle.h"
#include "nsFocusManager.h"
#include "nsColorControlFrame.h"
#include "nsNumberControlFrame.h"
#include "nsPIDOMWindow.h"
#include "nsRepeatService.h"
#include "nsContentCID.h"
#include "nsIComponentManager.h"
#include "nsIDOMHTMLFormElement.h"
#include "mozilla/dom/ProgressEvent.h"
#include "nsGkAtoms.h"
#include "nsStyleConsts.h"
#include "nsPresContext.h"
#include "nsMappedAttributes.h"
#include "nsIFormControl.h"
#include "nsIForm.h"
#include "nsFormSubmission.h"
#include "nsFormSubmissionConstants.h"
#include "nsIDocument.h"
#include "nsIPresShell.h"
#include "nsIFormControlFrame.h"
#include "nsITextControlFrame.h"
#include "nsIFrame.h"
#include "nsRangeFrame.h"
#include "nsIServiceManager.h"
#include "nsError.h"
#include "nsIEditor.h"
#include "nsIIOService.h"
#include "nsDocument.h"
#include "nsAttrValueOrString.h"
#include "nsPresState.h"
#include "nsIDOMEvent.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMHTMLCollection.h"
#include "nsLinebreakConverter.h" //to strip out carriage returns
#include "nsReadableUtils.h"
#include "nsUnicharUtils.h"
#include "nsLayoutUtils.h"
#include "nsVariant.h"
#include "nsIDOMMutationEvent.h"
#include "mozilla/ContentEvents.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventStates.h"
#include "mozilla/InternalMutationEvent.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TouchEvents.h"
#include "nsRuleData.h"
#include <algorithm>
// input type=radio
#include "nsIRadioGroupContainer.h"
// input type=file
#include "mozilla/dom/File.h"
#include "mozilla/dom/FileList.h"
#include "nsIFile.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsDirectoryServiceDefs.h"
#include "nsIContentPrefService.h"
#include "nsIMIMEService.h"
#include "nsIObserverService.h"
#include "nsIPopupWindowManager.h"
#include "nsGlobalWindow.h"
// input type=image
#include "nsImageLoadingContent.h"
#include "imgRequestProxy.h"
#include "mozAutoDocUpdate.h"
#include "nsContentCreatorFunctions.h"
#include "nsContentUtils.h"
#include "mozilla/dom/DirectionalityUtils.h"
#include "nsRadioVisitor.h"
#include "nsTextEditorState.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/Preferences.h"
#include "mozilla/MathAlgorithms.h"
#include "nsIIDNService.h"
#include <limits>
#include "nsIColorPicker.h"
#include "nsIStringEnumerator.h"
#include "HTMLSplitOnSpacesTokenizer.h"
#include "nsIController.h"
#include "nsIMIMEInfo.h"
#include "nsFrameSelection.h"
// input type=date
#include "js/Date.h"
#include "nsIDatePicker.h" // TenFourFox issue 405
// input type=time
#include "nsITimePicker.h" // TenFourFox issue 405
NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Input)
// XXX align=left, hspace, vspace, border? other nav4 attrs
static NS_DEFINE_CID(kXULControllersCID, NS_XULCONTROLLERS_CID);
// This must come outside of any namespace, or else it won't overload with the
// double based version in nsMathUtils.h
inline mozilla::Decimal
NS_floorModulo(mozilla::Decimal x, mozilla::Decimal y)
{
return (x - y * (x / y).floor());
}
namespace mozilla {
namespace dom {
// First bits are needed for the control type.
#define NS_OUTER_ACTIVATE_EVENT (1 << 9)
#define NS_ORIGINAL_CHECKED_VALUE (1 << 10)
#define NS_NO_CONTENT_DISPATCH (1 << 11)
#define NS_ORIGINAL_INDETERMINATE_VALUE (1 << 12)
#define NS_CONTROL_TYPE(bits) ((bits) & ~( \
NS_OUTER_ACTIVATE_EVENT | NS_ORIGINAL_CHECKED_VALUE | NS_NO_CONTENT_DISPATCH | \
NS_ORIGINAL_INDETERMINATE_VALUE))
// whether textfields should be selected once focused:
// -1: no, 1: yes, 0: uninitialized
static int32_t gSelectTextFieldOnFocus;
UploadLastDir* HTMLInputElement::gUploadLastDir;
static const nsAttrValue::EnumTable kInputTypeTable[] = {
{ "button", NS_FORM_INPUT_BUTTON },
{ "checkbox", NS_FORM_INPUT_CHECKBOX },
{ "color", NS_FORM_INPUT_COLOR },
{ "date", NS_FORM_INPUT_DATE },
{ "email", NS_FORM_INPUT_EMAIL },
{ "file", NS_FORM_INPUT_FILE },
{ "hidden", NS_FORM_INPUT_HIDDEN },
{ "reset", NS_FORM_INPUT_RESET },
{ "image", NS_FORM_INPUT_IMAGE },
{ "number", NS_FORM_INPUT_NUMBER },
{ "password", NS_FORM_INPUT_PASSWORD },
{ "radio", NS_FORM_INPUT_RADIO },
{ "range", NS_FORM_INPUT_RANGE },
{ "search", NS_FORM_INPUT_SEARCH },
{ "submit", NS_FORM_INPUT_SUBMIT },
{ "tel", NS_FORM_INPUT_TEL },
{ "text", NS_FORM_INPUT_TEXT },
{ "time", NS_FORM_INPUT_TIME },
{ "url", NS_FORM_INPUT_URL },
{ 0 }
};
// Default type is 'text'.
static const nsAttrValue::EnumTable* kInputDefaultType = &kInputTypeTable[16];
static const uint8_t NS_INPUT_INPUTMODE_AUTO = 0;
static const uint8_t NS_INPUT_INPUTMODE_NUMERIC = 1;
static const uint8_t NS_INPUT_INPUTMODE_DIGIT = 2;
static const uint8_t NS_INPUT_INPUTMODE_UPPERCASE = 3;
static const uint8_t NS_INPUT_INPUTMODE_LOWERCASE = 4;
static const uint8_t NS_INPUT_INPUTMODE_TITLECASE = 5;
static const uint8_t NS_INPUT_INPUTMODE_AUTOCAPITALIZED = 6;
static const nsAttrValue::EnumTable kInputInputmodeTable[] = {
{ "auto", NS_INPUT_INPUTMODE_AUTO },
{ "numeric", NS_INPUT_INPUTMODE_NUMERIC },
{ "digit", NS_INPUT_INPUTMODE_DIGIT },
{ "uppercase", NS_INPUT_INPUTMODE_UPPERCASE },
{ "lowercase", NS_INPUT_INPUTMODE_LOWERCASE },
{ "titlecase", NS_INPUT_INPUTMODE_TITLECASE },
{ "autocapitalized", NS_INPUT_INPUTMODE_AUTOCAPITALIZED },
{ 0 }
};
// Default inputmode value is "auto".
static const nsAttrValue::EnumTable* kInputDefaultInputmode = &kInputInputmodeTable[0];
const Decimal HTMLInputElement::kStepScaleFactorDate = Decimal(86400000);
const Decimal HTMLInputElement::kStepScaleFactorNumberRange = Decimal(1);
const Decimal HTMLInputElement::kStepScaleFactorTime = Decimal(1000);
const Decimal HTMLInputElement::kDefaultStepBase = Decimal(0);
const Decimal HTMLInputElement::kDefaultStep = Decimal(1);
const Decimal HTMLInputElement::kDefaultStepTime = Decimal(60);
const Decimal HTMLInputElement::kStepAny = Decimal(0);
#define NS_INPUT_ELEMENT_STATE_IID \
{ /* dc3b3d14-23e2-4479-b513-7b369343e3a0 */ \
0xdc3b3d14, \
0x23e2, \
0x4479, \
{0xb5, 0x13, 0x7b, 0x36, 0x93, 0x43, 0xe3, 0xa0} \
}
#define PROGRESS_STR "progress"
static const uint32_t kProgressEventInterval = 50; // ms
// Increase performance of checking for enabled types of input elements.
// TenFourFox issue 405
static bool sDOMInputPrefsCacheInitialized = false;
static bool sDOMInputEnableDate = false;
static bool sDOMInputEnableTime = false;
static bool sDOMInputEnableColor = false;
static bool sDOMInputEnableNumber = false;
static void InitializeDOMInputPrefCache() {
if (MOZ_UNLIKELY(sDOMInputPrefsCacheInitialized)) return;
Preferences::AddBoolVarCache(&sDOMInputEnableDate, "tenfourfox.dom.forms.date");
Preferences::AddBoolVarCache(&sDOMInputEnableTime, "tenfourfox.dom.forms.time");
// Mozilla implementations that existed prior
Preferences::AddBoolVarCache(&sDOMInputEnableColor, "dom.forms.color");
Preferences::AddBoolVarCache(&sDOMInputEnableNumber, "dom.forms.number");
sDOMInputPrefsCacheInitialized = true;
}
#define ENABLED(x) static inline bool Input ## x ## Enabled() { \
if (MOZ_UNLIKELY(!sDOMInputPrefsCacheInitialized)) InitializeDOMInputPrefCache(); \
return sDOMInputEnable ## x ; \
}
ENABLED(Date)
ENABLED(Time)
ENABLED(Color)
ENABLED(Number)
#undef ENABLED
class HTMLInputElementState final : public nsISupports
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_INPUT_ELEMENT_STATE_IID)
NS_DECL_ISUPPORTS
bool IsCheckedSet()
{
return mCheckedSet;
}
bool GetChecked()
{
return mChecked;
}
void SetChecked(bool aChecked)
{
mChecked = aChecked;
mCheckedSet = true;
}
const nsString& GetValue()
{
return mValue;
}
void SetValue(const nsAString& aValue)
{
mValue = aValue;
}
const nsTArray<RefPtr<BlobImpl>>& GetBlobImpls()
{
return mBlobImpls;
}
void SetBlobImpls(const nsTArray<RefPtr<File>>& aFile)
{
mBlobImpls.Clear();
for (uint32_t i = 0, len = aFile.Length(); i < len; ++i) {
mBlobImpls.AppendElement(aFile[i]->Impl());
}
}
HTMLInputElementState()
: mValue()
, mChecked(false)
, mCheckedSet(false)
{}
protected:
~HTMLInputElementState() {}
nsString mValue;
nsTArray<RefPtr<BlobImpl>> mBlobImpls;
bool mChecked;
bool mCheckedSet;
};
NS_DEFINE_STATIC_IID_ACCESSOR(HTMLInputElementState, NS_INPUT_ELEMENT_STATE_IID)
NS_IMPL_ISUPPORTS(HTMLInputElementState, HTMLInputElementState)
HTMLInputElement::nsFilePickerShownCallback::nsFilePickerShownCallback(
HTMLInputElement* aInput, nsIFilePicker* aFilePicker)
: mFilePicker(aFilePicker)
, mInput(aInput)
{
}
NS_IMPL_ISUPPORTS(UploadLastDir::ContentPrefCallback, nsIContentPrefCallback2)
NS_IMETHODIMP
UploadLastDir::ContentPrefCallback::HandleCompletion(uint16_t aReason)
{
nsCOMPtr<nsIFile> localFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
NS_ENSURE_STATE(localFile);
if (aReason == nsIContentPrefCallback2::COMPLETE_ERROR ||
!mResult) {
// Default to "desktop" directory for each platform
nsCOMPtr<nsIFile> homeDir;
NS_GetSpecialDirectory(NS_OS_DESKTOP_DIR, getter_AddRefs(homeDir));
localFile = do_QueryInterface(homeDir);
} else {
nsAutoString prefStr;
nsCOMPtr<nsIVariant> pref;
mResult->GetValue(getter_AddRefs(pref));
pref->GetAsAString(prefStr);
localFile->InitWithPath(prefStr);
}
mFilePicker->SetDisplayDirectory(localFile);
mFilePicker->Open(mFpCallback);
return NS_OK;
}
NS_IMETHODIMP
UploadLastDir::ContentPrefCallback::HandleResult(nsIContentPref* pref)
{
mResult = pref;
return NS_OK;
}
NS_IMETHODIMP
UploadLastDir::ContentPrefCallback::HandleError(nsresult error)
{
// HandleCompletion is always called (even with HandleError was called),
// so we don't need to do anything special here.
return NS_OK;
}
namespace {
/**
* This may return nullptr if aDomFile's implementation of
* File::mozFullPathInternal does not successfully return a non-empty
* string that is a valid path. This can happen on Firefox OS, for example,
* where the file picker can create Blobs.
*/
static already_AddRefed<nsIFile>
DOMFileToLocalFile(File* aDomFile)
{
nsString path;
ErrorResult rv;
aDomFile->GetMozFullPathInternal(path, rv);
if (rv.Failed() || path.IsEmpty()) {
rv.SuppressException();
return nullptr;
}
nsCOMPtr<nsIFile> localFile;
rv = NS_NewNativeLocalFile(NS_ConvertUTF16toUTF8(path), true,
getter_AddRefs(localFile));
if (NS_WARN_IF(rv.Failed())) {
rv.SuppressException();
return nullptr;
}
return localFile.forget();
}
} // namespace
NS_IMETHODIMP
HTMLInputElement::nsFilePickerShownCallback::Done(int16_t aResult)
{
mInput->PickerClosed();
if (aResult == nsIFilePicker::returnCancel) {
return NS_OK;
}
int16_t mode;
mFilePicker->GetMode(&mode);
// Collect new selected filenames
nsTArray<RefPtr<File>> newFiles;
if (mode == static_cast<int16_t>(nsIFilePicker::modeOpenMultiple)) {
nsCOMPtr<nsISimpleEnumerator> iter;
nsresult rv = mFilePicker->GetDomfiles(getter_AddRefs(iter));
NS_ENSURE_SUCCESS(rv, rv);
if (!iter) {
return NS_OK;
}
nsCOMPtr<nsISupports> tmp;
bool hasMore = true;
while (NS_SUCCEEDED(iter->HasMoreElements(&hasMore)) && hasMore) {
iter->GetNext(getter_AddRefs(tmp));
nsCOMPtr<nsIDOMBlob> domBlob = do_QueryInterface(tmp);
MOZ_ASSERT(domBlob,
"Null file object from FilePicker's file enumerator?");
if (domBlob) {
newFiles.AppendElement(static_cast<File*>(domBlob.get()));
}
}
} else {
MOZ_ASSERT(mode == static_cast<int16_t>(nsIFilePicker::modeOpen) ||
mode == static_cast<int16_t>(nsIFilePicker::modeGetFolder));
nsCOMPtr<nsISupports> tmp;
nsresult rv = mFilePicker->GetDomfile(getter_AddRefs(tmp));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDOMBlob> blob = do_QueryInterface(tmp);
if (blob) {
RefPtr<File> file = static_cast<Blob*>(blob.get())->ToFile();
newFiles.AppendElement(file);
}
}
if (newFiles.IsEmpty()) {
return NS_OK;
}
// Store the last used directory using the content pref service:
nsCOMPtr<nsIFile> file = DOMFileToLocalFile(newFiles[0]);
if (file) {
nsCOMPtr<nsIFile> lastUsedDir;
file->GetParent(getter_AddRefs(lastUsedDir));
HTMLInputElement::gUploadLastDir->StoreLastUsedDirectory(
mInput->OwnerDoc(), lastUsedDir);
}
// The text control frame (if there is one) isn't going to send a change
// event because it will think this is done by a script.
// So, we can safely send one by ourself.
mInput->SetFiles(newFiles, true);
return nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("change"), true,
false);
}
NS_IMPL_ISUPPORTS(HTMLInputElement::nsFilePickerShownCallback,
nsIFilePickerShownCallback)
class nsColorPickerShownCallback final
: public nsIColorPickerShownCallback
{
~nsColorPickerShownCallback() {}
public:
nsColorPickerShownCallback(HTMLInputElement* aInput,
nsIColorPicker* aColorPicker)
: mInput(aInput)
, mColorPicker(aColorPicker)
, mValueChanged(false)
{}
NS_DECL_ISUPPORTS
NS_IMETHOD Update(const nsAString& aColor) override;
NS_IMETHOD Done(const nsAString& aColor) override;
private:
/**
* Updates the internals of the object using aColor as the new value.
* If aTrustedUpdate is true, it will consider that aColor is a new value.
* Otherwise, it will check that aColor is different from the current value.
*/
nsresult UpdateInternal(const nsAString& aColor, bool aTrustedUpdate);
RefPtr<HTMLInputElement> mInput;
nsCOMPtr<nsIColorPicker> mColorPicker;
bool mValueChanged;
};
nsresult
nsColorPickerShownCallback::UpdateInternal(const nsAString& aColor,
bool aTrustedUpdate)
{
bool valueChanged = false;
nsAutoString oldValue;
if (aTrustedUpdate) {
valueChanged = true;
} else {
mInput->GetValue(oldValue);
}
mInput->SetValue(aColor);
if (!aTrustedUpdate) {
nsAutoString newValue;
mInput->GetValue(newValue);
if (!oldValue.Equals(newValue)) {
valueChanged = true;
}
}
if (valueChanged) {
mValueChanged = true;
return nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("input"), true,
false);
}
return NS_OK;
}
NS_IMETHODIMP
nsColorPickerShownCallback::Update(const nsAString& aColor)
{
return UpdateInternal(aColor, true);
}
NS_IMETHODIMP
nsColorPickerShownCallback::Done(const nsAString& aColor)
{
/**
* When Done() is called, we might be at the end of a serie of Update() calls
* in which case mValueChanged is set to true and a change event will have to
* be fired but we might also be in a one shot Done() call situation in which
* case we should fire a change event iif the value actually changed.
* UpdateInternal(bool) is taking care of that logic for us.
*/
nsresult rv = NS_OK;
mInput->PickerClosed();
if (!aColor.IsEmpty()) {
UpdateInternal(aColor, false);
}
if (mValueChanged) {
rv = nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("change"), true,
false);
}
return rv;
}
NS_IMPL_ISUPPORTS(nsColorPickerShownCallback, nsIColorPickerShownCallback)
HTMLInputElement::nsDatePickerShownCallback::nsDatePickerShownCallback(
HTMLInputElement* aInput, nsIDatePicker* aDatePicker)
: mDatePicker(aDatePicker)
, mInput(aInput)
{
}
NS_IMETHODIMP
HTMLInputElement::nsDatePickerShownCallback::Done(int16_t aResult)
{
mInput->PickerClosed();
if (aResult == nsIDatePicker::returnCancel) {
return NS_OK;
}
nsAutoString date;
nsresult rv = mDatePicker->GetSelectedDate(date);
NS_ENSURE_SUCCESS(rv, rv);
mInput->SetValue(date); // set value
// The text control frame (if there is one) isn't going to send a change
// event because it will think this is done by a script.
// So, we can safely send one by ourself.
// Send both input and change events at the same time, since from the
// browser's perspective that's exactly what's happening.
rv = nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("input"), true,
false);
NS_ENSURE_SUCCESS(rv, rv);
return nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("change"), true,
false);
}
NS_IMPL_ISUPPORTS(HTMLInputElement::nsDatePickerShownCallback,
nsIDatePickerShownCallback)
HTMLInputElement::nsTimePickerShownCallback::nsTimePickerShownCallback(
HTMLInputElement* aInput, nsITimePicker* aTimePicker)
: mTimePicker(aTimePicker)
, mInput(aInput)
{
}
NS_IMETHODIMP
HTMLInputElement::nsTimePickerShownCallback::Done(int16_t aResult)
{
mInput->PickerClosed();
if (aResult == nsITimePicker::returnCancel) {
return NS_OK;
}
// The result is automatically truncated by the NSDateFormatter;
// we don't have to post-process it here.
nsAutoString time;
nsresult rv = mTimePicker->GetSelectedTime(time);
NS_ENSURE_SUCCESS(rv, rv);
mInput->SetValue(time); // set value
// The text control frame (if there is one) isn't going to send a change
// event because it will think this is done by a script.
// So, we can safely send one by ourself.
// Send both input and change events as above.
rv = nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("input"), true,
false);
NS_ENSURE_SUCCESS(rv, rv);
return nsContentUtils::DispatchTrustedEvent(mInput->OwnerDoc(),
static_cast<nsIDOMHTMLInputElement*>(mInput.get()),
NS_LITERAL_STRING("change"), true,
false);
}
NS_IMPL_ISUPPORTS(HTMLInputElement::nsTimePickerShownCallback,
nsITimePickerShownCallback)
bool
HTMLInputElement::IsPopupBlocked() const
{
nsCOMPtr<nsPIDOMWindow> win = OwnerDoc()->GetWindow();
MOZ_ASSERT(win, "window should not be null");
if (!win) {
return true;
}
// Check if page is allowed to open the popup
if (win->GetPopupControlState() <= openControlled) {
return false;
}
nsCOMPtr<nsIPopupWindowManager> pm = do_GetService(NS_POPUPWINDOWMANAGER_CONTRACTID);
if (!pm) {
return true;
}
uint32_t permission;
pm->TestPermission(OwnerDoc()->NodePrincipal(), &permission);
return permission == nsIPopupWindowManager::DENY_POPUP;
}
/* Time and date picker implementations from TenFourFox issue 405. */
static bool
IsTimeInRightFormat(nsAutoString &aTime, double aStep)
{
// Avoid exposing web-defined time strings to OS X, since I have
// no idea what crap lurks in there. Check that there are digits
// and : in the right place. We assume NSDateFormatter can at least
// reject values that are out of range.
// XXX:
// Since the step determines the template that NSDateFormatter uses,
// an eight character (HH:MM:SS) time with step >= 60 should fail,
// and a five character (HH:MM) time with step < 60 should too, or the
// formatter may choose bizarre times. This is probably not websafe
// but that's too bad. As a real world example, one of the MDN time
// examples uses "9:00" as the minimum time. This fails this test, but
// the comments in ParseTime() indicates that HH:MM is the only valid
// format, not H:MM. Furthermore, the real Firefox 61 also doesn't
// accept it as a minimum time, so we are consistent with recent builds.
// The spec allows HH:MM:SS.ssss. There's no point to this because
// we can't express such times with the NSDatePicker control, so we
// just chop it off.
int32_t dot = aTime.Find(".", false, 0, -1);
if (dot != kNotFound) {
if (dot != 8) return false; // H:MM:SS.ssss not allowed
if (aStep >= 60.0) return false; // HH:MM required
aTime.SetLength(8);
} else {
if (aStep >= 60.0 && aTime.Length() != 5)
return false;
if (aStep < 60.0 && aTime.Length() != 8)
return false;
}
// Length is validated, so the loop here suffices for both cases.
const char16_t *cur = aTime.BeginReading();
const char16_t *end = aTime.EndReading();
size_t nchar = 0;
for (; cur < end; ++cur) {
nchar++;
if (nchar == 3 || nchar == 6) {
if (char16_t(':') == *cur)
continue;
return false;
}
if (char16_t('0') > *cur || char16_t('9') < *cur)
return false;
}
return true;
}
nsresult
HTMLInputElement::InitTimePicker(bool aNoMatterWhat)
{
if (mPickerRunning) {
NS_WARNING("Just one nsITimePicker is allowed");
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDocument> doc = OwnerDoc();
nsCOMPtr<nsPIDOMWindow> win = doc->GetWindow();
if (!win) {
return NS_ERROR_FAILURE;
}
if (!aNoMatterWhat && IsPopupBlocked()) {
win->FirePopupBlockedEvent(doc, nullptr, EmptyString(), EmptyString());
return NS_OK;
}
nsCOMPtr<nsITimePicker> timePicker = do_CreateInstance("@mozilla.org/timepicker;1");
if (!timePicker) {
return NS_ERROR_FAILURE;
}
nsAutoString initialValue;
GetValueInternal(initialValue);
// Step value is apparently in milliseconds.
double step = GetStep().toDouble() / 1000.0;
if (step == 0.0) step = 60.0; // XXX?
nsresult rv = timePicker->Init(win, EmptyString()); // title NYI
NS_ENSURE_SUCCESS(rv, rv);
rv = timePicker->SetStep(step);
NS_ENSURE_SUCCESS(rv, rv);
if (IsTimeInRightFormat(initialValue, step)) {
// Sanitized, therefore safe to give to the Cocoa time formatter.
rv = timePicker->SetDefaultTime(initialValue);
NS_ENSURE_SUCCESS(rv, rv);
}
if (HasAttr(kNameSpaceID_None, nsGkAtoms::min)) {
nsAutoString minStr;
GetAttr(kNameSpaceID_None, nsGkAtoms::min, minStr);
if (IsTimeInRightFormat(minStr, step)) {
rv = timePicker->SetMinTime(minStr);
NS_ENSURE_SUCCESS(rv, rv);
}
}
if (HasAttr(kNameSpaceID_None, nsGkAtoms::max)) {
nsAutoString maxStr;
GetAttr(kNameSpaceID_None, nsGkAtoms::max, maxStr);
if (IsTimeInRightFormat(maxStr, step)) {
rv = timePicker->SetMaxTime(maxStr);
NS_ENSURE_SUCCESS(rv, rv);
}
}
nsCOMPtr<nsITimePickerShownCallback> callback =
new nsTimePickerShownCallback(this, timePicker);
rv = timePicker->Open(callback);
if (NS_SUCCEEDED(rv)) {
mPickerRunning = true;
}
return rv;
}
static bool
IsDateInRightFormat(const nsAutoString& aDate)
{
// Avoid exposing web-defined date strings to OS X, since I have
// no idea what crap lurks in there. Instead, ensure the string
// is in nnnn-nn-nn format, and assume NSDateFormatter handles days
// and months that are out of range and rejects those as long as
// the basic format is acceptable.
if (aDate.Length() != 10)
return false;
const char16_t *cur = aDate.BeginReading();
const char16_t *end = aDate.EndReading();
size_t nchar = 0;
for (; cur < end; ++cur) {
nchar++;
if (nchar == 5 || nchar == 8) {
if (char16_t('-') == *cur)
continue;
return false;
}
if (char16_t('0') > *cur || char16_t('9') < *cur)
return false;
}
return true;
}
nsresult
HTMLInputElement::InitDatePicker(bool aNoMatterWhat)
{
if (mPickerRunning) {
NS_WARNING("Just one nsIDatePicker is allowed");
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDocument> doc = OwnerDoc();
nsCOMPtr<nsPIDOMWindow> win = doc->GetWindow();
if (!win) {
return NS_ERROR_FAILURE;
}
if (!aNoMatterWhat && IsPopupBlocked()) {
win->FirePopupBlockedEvent(doc, nullptr, EmptyString(), EmptyString());
return NS_OK;
}
nsCOMPtr<nsIDatePicker> datePicker = do_CreateInstance("@mozilla.org/datepicker;1");
if (!datePicker) {
return NS_ERROR_FAILURE;
}
nsAutoString initialValue;
GetValueInternal(initialValue);
nsresult rv = datePicker->Init(win, EmptyString()); // title NYI
NS_ENSURE_SUCCESS(rv, rv);
if (IsDateInRightFormat(initialValue)) {
// Sanitized, therefore safe to give to the Cocoa date formatter.
rv = datePicker->SetDefaultDate(initialValue);
NS_ENSURE_SUCCESS(rv, rv);
}
if (HasAttr(kNameSpaceID_None, nsGkAtoms::min)) {
nsAutoString minStr;
GetAttr(kNameSpaceID_None, nsGkAtoms::min, minStr);
if (IsDateInRightFormat(minStr)) {
rv = datePicker->SetMinDate(minStr);
NS_ENSURE_SUCCESS(rv, rv);
}
}
if (HasAttr(kNameSpaceID_None, nsGkAtoms::max)) {
nsAutoString maxStr;
GetAttr(kNameSpaceID_None, nsGkAtoms::max, maxStr);
if (IsDateInRightFormat(maxStr)) {
rv = datePicker->SetMaxDate(maxStr);
NS_ENSURE_SUCCESS(rv, rv);
}
}
nsCOMPtr<nsIDatePickerShownCallback> callback =
new nsDatePickerShownCallback(this, datePicker);
rv = datePicker->Open(callback);
if (NS_SUCCEEDED(rv)) {
mPickerRunning = true;
}
return rv;
}
nsresult
HTMLInputElement::InitColorPicker()
{
if (mPickerRunning) {
NS_WARNING("Just one nsIColorPicker is allowed");
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDocument> doc = OwnerDoc();
nsCOMPtr<nsPIDOMWindow> win = doc->GetWindow();
if (!win) {
return NS_ERROR_FAILURE;
}
if (IsPopupBlocked()) {
win->FirePopupBlockedEvent(doc, nullptr, EmptyString(), EmptyString());
return NS_OK;
}
// Get Loc title
nsXPIDLString title;
nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
"ColorPicker", title);
nsCOMPtr<nsIColorPicker> colorPicker = do_CreateInstance("@mozilla.org/colorpicker;1");
if (!colorPicker) {
return NS_ERROR_FAILURE;
}
nsAutoString initialValue;
GetValueInternal(initialValue);
nsresult rv = colorPicker->Init(win, title, initialValue);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIColorPickerShownCallback> callback =
new nsColorPickerShownCallback(this, colorPicker);
rv = colorPicker->Open(callback);
if (NS_SUCCEEDED(rv)) {
mPickerRunning = true;
}
return rv;
}
nsresult
HTMLInputElement::InitFilePicker(FilePickerType aType)
{
if (mPickerRunning) {
NS_WARNING("Just one nsIFilePicker is allowed");
return NS_ERROR_FAILURE;
}
// Get parent nsPIDOMWindow object.
nsCOMPtr<nsIDocument> doc = OwnerDoc();
nsCOMPtr<nsPIDOMWindow> win = doc->GetWindow();
if (!win) {
return NS_ERROR_FAILURE;
}
if (IsPopupBlocked()) {
win->FirePopupBlockedEvent(doc, nullptr, EmptyString(), EmptyString());
return NS_OK;
}
// Get Loc title
nsXPIDLString title;
nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
"FileUpload", title);
nsCOMPtr<nsIFilePicker> filePicker = do_CreateInstance("@mozilla.org/filepicker;1");
if (!filePicker)
return NS_ERROR_FAILURE;
int16_t mode;
if (aType == FILE_PICKER_DIRECTORY) {
mode = static_cast<int16_t>(nsIFilePicker::modeGetFolder);
} else if (HasAttr(kNameSpaceID_None, nsGkAtoms::multiple)) {
mode = static_cast<int16_t>(nsIFilePicker::modeOpenMultiple);
} else {
mode = static_cast<int16_t>(nsIFilePicker::modeOpen);
}
nsresult rv = filePicker->Init(win, title, mode);
NS_ENSURE_SUCCESS(rv, rv);
// Native directory pickers ignore file type filters, so we don't spend
// cycles adding them for FILE_PICKER_DIRECTORY.
if (HasAttr(kNameSpaceID_None, nsGkAtoms::accept) &&
aType != FILE_PICKER_DIRECTORY) {
SetFilePickerFiltersFromAccept(filePicker);
} else {
filePicker->AppendFilters(nsIFilePicker::filterAll);
}
// Set default directry and filename
nsAutoString defaultName;
const nsTArray<RefPtr<File>>& oldFiles = GetFilesInternal();
nsCOMPtr<nsIFilePickerShownCallback> callback =
new HTMLInputElement::nsFilePickerShownCallback(this, filePicker);
if (!oldFiles.IsEmpty() &&
aType != FILE_PICKER_DIRECTORY) {