ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / components / autofill / core / browser / autofill_field.cc
blob75a0d0a4220a61e4f8f9c92a523bbb12363974cf
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/autofill/core/browser/autofill_field.h"
7 #include "base/command_line.h"
8 #include "base/logging.h"
9 #include "base/metrics/field_trial.h"
10 #include "base/sha1.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_split.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "components/autofill/core/browser/autofill_country.h"
16 #include "components/autofill/core/browser/autofill_type.h"
17 #include "components/autofill/core/browser/phone_number.h"
18 #include "components/autofill/core/browser/state_names.h"
19 #include "components/autofill/core/common/autofill_switches.h"
20 #include "grit/components_strings.h"
21 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
22 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
23 #include "ui/base/l10n/l10n_util.h"
25 using ::i18n::addressinput::AddressData;
26 using ::i18n::addressinput::GetStreetAddressLinesAsSingleLine;
27 using base::ASCIIToUTF16;
28 using base::StringToInt;
30 namespace autofill {
31 namespace {
33 const char* const kMonthsAbbreviated[] = {
34 NULL, // Padding so index 1 = month 1 = January.
35 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
36 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
39 const char* const kMonthsFull[] = {
40 NULL, // Padding so index 1 = month 1 = January.
41 "January", "February", "March", "April", "May", "June",
42 "July", "August", "September", "October", "November", "December",
45 // Returns true if the value was successfully set, meaning |value| was found in
46 // the list of select options in |field|.
47 bool SetSelectControlValue(const base::string16& value,
48 FormFieldData* field) {
49 base::string16 value_lowercase = base::StringToLowerASCII(value);
51 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
52 base::string16 best_match;
53 for (size_t i = 0; i < field->option_values.size(); ++i) {
54 if (value == field->option_values[i] ||
55 value == field->option_contents[i]) {
56 // An exact match, use it.
57 best_match = field->option_values[i];
58 break;
61 if (value_lowercase == base::StringToLowerASCII(field->option_values[i]) ||
62 value_lowercase ==
63 base::StringToLowerASCII(field->option_contents[i])) {
64 // A match, but not in the same case. Save it in case an exact match is
65 // not found.
66 best_match = field->option_values[i];
70 if (best_match.empty())
71 return false;
73 field->value = best_match;
74 return true;
77 // Like SetSelectControlValue, but searches within the field values and options
78 // for |value|. For example, "NC - North Carolina" would match "north carolina".
79 bool SetSelectControlValueSubstringMatch(const base::string16& value,
80 FormFieldData* field) {
81 base::string16 value_lowercase = base::StringToLowerASCII(value);
82 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
83 int best_match = -1;
85 for (size_t i = 0; i < field->option_values.size(); ++i) {
86 if (base::StringToLowerASCII(field->option_values[i]).find(value_lowercase) !=
87 std::string::npos ||
88 base::StringToLowerASCII(field->option_contents[i]).find(
89 value_lowercase) != std::string::npos) {
90 // The best match is the shortest one.
91 if (best_match == -1 ||
92 field->option_values[best_match].size() >
93 field->option_values[i].size()) {
94 best_match = i;
99 if (best_match >= 0) {
100 field->value = field->option_values[best_match];
101 return true;
104 return false;
107 // Like SetSelectControlValue, but searches within the field values and options
108 // for |value|. First it tokenizes the options, then tries to match against
109 // tokens. For example, "NC - North Carolina" would match "nc" but not "ca".
110 bool SetSelectControlValueTokenMatch(const base::string16& value,
111 FormFieldData* field) {
112 base::string16 value_lowercase = base::StringToLowerASCII(value);
113 std::vector<base::string16> tokenized;
114 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
116 for (size_t i = 0; i < field->option_values.size(); ++i) {
117 base::SplitStringAlongWhitespace(
118 base::StringToLowerASCII(field->option_values[i]), &tokenized);
119 if (std::find(tokenized.begin(), tokenized.end(), value_lowercase) !=
120 tokenized.end()) {
121 field->value = field->option_values[i];
122 return true;
125 base::SplitStringAlongWhitespace(
126 base::StringToLowerASCII(field->option_contents[i]), &tokenized);
127 if (std::find(tokenized.begin(), tokenized.end(), value_lowercase) !=
128 tokenized.end()) {
129 field->value = field->option_values[i];
130 return true;
134 return false;
137 // Try to fill a numeric |value| into the given |field|.
138 bool FillNumericSelectControl(int value,
139 FormFieldData* field) {
140 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
141 for (size_t i = 0; i < field->option_values.size(); ++i) {
142 int option;
143 if ((StringToInt(field->option_values[i], &option) && option == value) ||
144 (StringToInt(field->option_contents[i], &option) && option == value)) {
145 field->value = field->option_values[i];
146 return true;
150 return false;
153 bool FillStateSelectControl(const base::string16& value,
154 FormFieldData* field) {
155 base::string16 full, abbreviation;
156 state_names::GetNameAndAbbreviation(value, &full, &abbreviation);
158 // Try an exact match of the abbreviation first.
159 if (!abbreviation.empty() && SetSelectControlValue(abbreviation, field)) {
160 return true;
163 // Try an exact match of the full name.
164 if (!full.empty() && SetSelectControlValue(full, field)) {
165 return true;
168 // Then try an inexact match of the full name.
169 if (!full.empty() && SetSelectControlValueSubstringMatch(full, field)) {
170 return true;
173 // Then try an inexact match of the abbreviation name.
174 return !abbreviation.empty() &&
175 SetSelectControlValueTokenMatch(abbreviation, field);
178 bool FillCountrySelectControl(const base::string16& value,
179 const std::string& app_locale,
180 FormFieldData* field_data) {
181 std::string country_code = AutofillCountry::GetCountryCode(value, app_locale);
182 if (country_code.empty())
183 return false;
185 DCHECK_EQ(field_data->option_values.size(),
186 field_data->option_contents.size());
187 for (size_t i = 0; i < field_data->option_values.size(); ++i) {
188 // Canonicalize each <option> value to a country code, and compare to the
189 // target country code.
190 base::string16 value = field_data->option_values[i];
191 base::string16 contents = field_data->option_contents[i];
192 if (country_code == AutofillCountry::GetCountryCode(value, app_locale) ||
193 country_code == AutofillCountry::GetCountryCode(contents, app_locale)) {
194 field_data->value = value;
195 return true;
199 return false;
202 bool FillExpirationMonthSelectControl(const base::string16& value,
203 FormFieldData* field) {
204 int index = 0;
205 if (!StringToInt(value, &index) ||
206 index <= 0 ||
207 static_cast<size_t>(index) >= arraysize(kMonthsFull))
208 return false;
210 bool filled =
211 SetSelectControlValue(ASCIIToUTF16(kMonthsAbbreviated[index]), field) ||
212 SetSelectControlValue(ASCIIToUTF16(kMonthsFull[index]), field) ||
213 FillNumericSelectControl(index, field);
214 return filled;
217 // Returns true if the last two digits in |year| match those in |str|.
218 bool LastTwoDigitsMatch(const base::string16& year,
219 const base::string16& str) {
220 int year_int;
221 int str_int;
222 if (!StringToInt(year, &year_int) || !StringToInt(str, &str_int))
223 return false;
225 return (year_int % 100) == (str_int % 100);
228 // Try to fill a year |value| into the given |field| by comparing the last two
229 // digits of the year to the field's options.
230 bool FillYearSelectControl(const base::string16& value,
231 FormFieldData* field) {
232 if (value.size() != 2U && value.size() != 4U)
233 return false;
235 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
236 for (size_t i = 0; i < field->option_values.size(); ++i) {
237 if (LastTwoDigitsMatch(value, field->option_values[i]) ||
238 LastTwoDigitsMatch(value, field->option_contents[i])) {
239 field->value = field->option_values[i];
240 return true;
244 return false;
247 // Try to fill a credit card type |value| (Visa, MasterCard, etc.) into the
248 // given |field|.
249 bool FillCreditCardTypeSelectControl(const base::string16& value,
250 FormFieldData* field) {
251 // Try stripping off spaces.
252 base::string16 value_stripped;
253 base::RemoveChars(base::StringToLowerASCII(value), base::kWhitespaceUTF16,
254 &value_stripped);
256 for (size_t i = 0; i < field->option_values.size(); ++i) {
257 base::string16 option_value_lowercase;
258 base::RemoveChars(base::StringToLowerASCII(field->option_values[i]),
259 base::kWhitespaceUTF16, &option_value_lowercase);
260 base::string16 option_contents_lowercase;
261 base::RemoveChars(base::StringToLowerASCII(field->option_contents[i]),
262 base::kWhitespaceUTF16, &option_contents_lowercase);
264 // Perform a case-insensitive comparison; but fill the form with the
265 // original text, not the lowercased version.
266 if (value_stripped == option_value_lowercase ||
267 value_stripped == option_contents_lowercase) {
268 field->value = field->option_values[i];
269 return true;
273 // For American Express, also try filling as "AmEx".
274 if (value == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
275 return FillCreditCardTypeSelectControl(ASCIIToUTF16("AmEx"), field);
277 return false;
280 // Set |field_data|'s value to |number|, or possibly an appropriate substring of
281 // |number|. The |field| specifies the type of the phone and whether this is a
282 // phone prefix or suffix.
283 void FillPhoneNumberField(const AutofillField& field,
284 const base::string16& number,
285 FormFieldData* field_data) {
286 field_data->value =
287 AutofillField::GetPhoneNumberValue(field, number, *field_data);
290 // Set |field_data|'s value to |number|, or possibly an appropriate substring
291 // of |number| for cases where credit card number splits across multiple HTML
292 // form input fields.
293 // The |field| specifies the |credit_card_number_offset_| to the substring
294 // within credit card number.
295 void FillCreditCardNumberField(const AutofillField& field,
296 const base::string16& number,
297 FormFieldData* field_data) {
298 base::string16 value = number;
300 // |field|'s max_length truncates credit card number to fit within.
301 if (field.credit_card_number_offset() < value.length())
302 value = value.substr(field.credit_card_number_offset());
304 field_data->value = value;
307 // Fills in the select control |field| with |value|. If an exact match is not
308 // found, falls back to alternate filling strategies based on the |type|.
309 bool FillSelectControl(const AutofillType& type,
310 const base::string16& value,
311 const std::string& app_locale,
312 FormFieldData* field) {
313 DCHECK_EQ("select-one", field->form_control_type);
315 // Guard against corrupted values passed over IPC.
316 if (field->option_values.size() != field->option_contents.size())
317 return false;
319 if (value.empty())
320 return false;
322 // First, search for exact matches.
323 if (SetSelectControlValue(value, field))
324 return true;
326 // If that fails, try specific fallbacks based on the field type.
327 ServerFieldType storable_type = type.GetStorableType();
328 if (storable_type == ADDRESS_HOME_STATE) {
329 return FillStateSelectControl(value, field);
330 } else if (storable_type == ADDRESS_HOME_COUNTRY) {
331 return FillCountrySelectControl(value, app_locale, field);
332 } else if (storable_type == CREDIT_CARD_EXP_MONTH) {
333 return FillExpirationMonthSelectControl(value, field);
334 } else if (storable_type == CREDIT_CARD_EXP_2_DIGIT_YEAR ||
335 storable_type == CREDIT_CARD_EXP_4_DIGIT_YEAR) {
336 return FillYearSelectControl(value, field);
337 } else if (storable_type == CREDIT_CARD_TYPE) {
338 return FillCreditCardTypeSelectControl(value, field);
341 return false;
344 // Fills in the month control |field| with |value|. |value| should be a date
345 // formatted as MM/YYYY. If it isn't, filling will fail.
346 bool FillMonthControl(const base::string16& value, FormFieldData* field) {
347 // Autofill formats a combined date as month/year.
348 std::vector<base::string16> pieces;
349 base::SplitString(value, base::char16('/'), &pieces);
350 if (pieces.size() != 2)
351 return false;
353 // HTML5 input="month" is formatted as year-month.
354 base::string16 month = pieces[0];
355 base::string16 year = pieces[1];
356 if ((month.size() != 1 && month.size() != 2) || year.size() != 4)
357 return false;
359 // HTML5 input="month" expects zero-padded months.
360 if (month.size() == 1)
361 month = ASCIIToUTF16("0") + month;
363 field->value = year + ASCIIToUTF16("-") + month;
364 return true;
367 // Fills |field| with the street address in |value|. Translates newlines into
368 // equivalent separators when necessary, i.e. when filling a single-line field.
369 // The separators depend on |address_language_code|.
370 void FillStreetAddress(const base::string16& value,
371 const std::string& address_language_code,
372 FormFieldData* field) {
373 if (field->form_control_type == "textarea") {
374 field->value = value;
375 return;
378 AddressData address_data;
379 address_data.language_code = address_language_code;
380 base::SplitString(base::UTF16ToUTF8(value), '\n', &address_data.address_line);
381 std::string line;
382 GetStreetAddressLinesAsSingleLine(address_data, &line);
383 field->value = base::UTF8ToUTF16(line);
386 std::string Hash32Bit(const std::string& str) {
387 std::string hash_bin = base::SHA1HashString(str);
388 DCHECK_EQ(20U, hash_bin.length());
390 uint32 hash32 = ((hash_bin[0] & 0xFF) << 24) |
391 ((hash_bin[1] & 0xFF) << 16) |
392 ((hash_bin[2] & 0xFF) << 8) |
393 (hash_bin[3] & 0xFF);
395 return base::UintToString(hash32);
398 } // namespace
400 AutofillField::AutofillField()
401 : server_type_(NO_SERVER_DATA),
402 heuristic_type_(UNKNOWN_TYPE),
403 html_type_(HTML_TYPE_UNKNOWN),
404 html_mode_(HTML_MODE_NONE),
405 phone_part_(IGNORED),
406 credit_card_number_offset_(0) {
409 AutofillField::AutofillField(const FormFieldData& field,
410 const base::string16& unique_name)
411 : FormFieldData(field),
412 unique_name_(unique_name),
413 server_type_(NO_SERVER_DATA),
414 heuristic_type_(UNKNOWN_TYPE),
415 html_type_(HTML_TYPE_UNKNOWN),
416 html_mode_(HTML_MODE_NONE),
417 phone_part_(IGNORED),
418 credit_card_number_offset_(0) {
421 AutofillField::~AutofillField() {}
423 void AutofillField::set_heuristic_type(ServerFieldType type) {
424 if (type >= 0 && type < MAX_VALID_FIELD_TYPE &&
425 type != FIELD_WITH_DEFAULT_VALUE) {
426 heuristic_type_ = type;
427 } else {
428 NOTREACHED();
429 // This case should not be reachable; but since this has potential
430 // implications on data uploaded to the server, better safe than sorry.
431 heuristic_type_ = UNKNOWN_TYPE;
435 void AutofillField::set_server_type(ServerFieldType type) {
436 // Chrome no longer supports fax numbers, but the server still does.
437 if (type >= PHONE_FAX_NUMBER && type <= PHONE_FAX_WHOLE_NUMBER)
438 return;
440 server_type_ = type;
443 void AutofillField::SetHtmlType(HtmlFieldType type, HtmlFieldMode mode) {
444 html_type_ = type;
445 html_mode_ = mode;
447 if (type == HTML_TYPE_TEL_LOCAL_PREFIX)
448 phone_part_ = PHONE_PREFIX;
449 else if (type == HTML_TYPE_TEL_LOCAL_SUFFIX)
450 phone_part_ = PHONE_SUFFIX;
451 else
452 phone_part_ = IGNORED;
455 AutofillType AutofillField::Type() const {
456 if (html_type_ != HTML_TYPE_UNKNOWN)
457 return AutofillType(html_type_, html_mode_);
459 if (server_type_ != NO_SERVER_DATA) {
460 // See http://crbug.com/429236 for background on why we might not always
461 // believe the server.
462 // See http://crbug.com/441488 for potential improvements to the server
463 // which may obviate the need for this logic.
464 bool believe_server =
465 !(server_type_ == NAME_FULL && heuristic_type_ == CREDIT_CARD_NAME) &&
466 !(server_type_ == CREDIT_CARD_NAME && heuristic_type_ == NAME_FULL);
467 if (believe_server)
468 return AutofillType(server_type_);
471 return AutofillType(heuristic_type_);
474 bool AutofillField::IsEmpty() const {
475 return value.empty();
478 std::string AutofillField::FieldSignature() const {
479 std::string field_name = base::UTF16ToUTF8(name);
480 std::string field_string = field_name + "&" + form_control_type;
481 return Hash32Bit(field_string);
484 bool AutofillField::IsFieldFillable() const {
485 return (should_autocomplete ||
486 !base::CommandLine::ForCurrentProcess()->HasSwitch(
487 switches::kRespectAutocompleteOffForAutofill)) &&
488 !Type().IsUnknown();
491 // static
492 bool AutofillField::FillFormField(const AutofillField& field,
493 const base::string16& value,
494 const std::string& address_language_code,
495 const std::string& app_locale,
496 FormFieldData* field_data) {
497 AutofillType type = field.Type();
499 if (type.GetStorableType() == PHONE_HOME_NUMBER) {
500 FillPhoneNumberField(field, value, field_data);
501 return true;
502 } else if (field_data->form_control_type == "select-one") {
503 return FillSelectControl(type, value, app_locale, field_data);
504 } else if (field_data->form_control_type == "month") {
505 return FillMonthControl(value, field_data);
506 } else if (type.GetStorableType() == ADDRESS_HOME_STREET_ADDRESS) {
507 FillStreetAddress(value, address_language_code, field_data);
508 return true;
509 } else if (type.GetStorableType() == CREDIT_CARD_NUMBER) {
510 FillCreditCardNumberField(field, value, field_data);
511 return true;
514 field_data->value = value;
515 return true;
518 base::string16 AutofillField::GetPhoneNumberValue(
519 const AutofillField& field,
520 const base::string16& number,
521 const FormFieldData& field_data) {
522 // Check to see if the size field matches the "prefix" or "suffix" size.
523 // If so, return the appropriate substring.
524 if (number.length() !=
525 PhoneNumber::kPrefixLength + PhoneNumber::kSuffixLength) {
526 return number;
529 if (field.phone_part() == AutofillField::PHONE_PREFIX ||
530 field_data.max_length == PhoneNumber::kPrefixLength) {
531 return
532 number.substr(PhoneNumber::kPrefixOffset, PhoneNumber::kPrefixLength);
535 if (field.phone_part() == AutofillField::PHONE_SUFFIX ||
536 field_data.max_length == PhoneNumber::kSuffixLength) {
537 return
538 number.substr(PhoneNumber::kSuffixOffset, PhoneNumber::kSuffixLength);
541 return number;
544 } // namespace autofill