summaryrefslogtreecommitdiff
path: root/chromium/components/autofill/core/browser/ui/label_formatter_utils.cc
blob: 91f1a6ebf7a0da6a9f19447128d5b53f586751ef (plain)
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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/core/browser/ui/label_formatter_utils.h"

#include <algorithm>
#include <iterator>
#include <memory>

#include "base/bind.h"
#include "base/callback.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/autofill_data_util.h"
#include "components/autofill/core/browser/geo/address_i18n.h"
#include "components/autofill/core/browser/geo/phone_number_i18n.h"
#include "components/autofill/core/browser/validation.h"
#include "components/grit/components_scaled_resources.h"
#include "components/strings/grit/components_strings.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
#include "ui/base/l10n/l10n_util.h"

namespace autofill {

using data_util::ContainsAddress;
using data_util::ContainsEmail;
using data_util::ContainsName;
using data_util::ContainsPhone;

namespace {

// Returns true if all |profiles| have the same value for the data retrieved by
// |get_data|.
bool HaveSameData(
    const std::vector<AutofillProfile*>& profiles,
    const std::string& app_locale,
    base::RepeatingCallback<base::string16(const AutofillProfile&,
                                           const std::string&)> get_data,
    base::RepeatingCallback<bool(const base::string16& str1,
                                 const base::string16& str2)> matches) {
  if (profiles.size() <= 1) {
    return true;
  }

  const base::string16 first_profile_data =
      get_data.Run(*profiles[0], app_locale);
  for (size_t i = 1; i < profiles.size(); ++i) {
    const base::string16 current_profile_data =
        get_data.Run(*profiles[i], app_locale);
    if (!matches.Run(first_profile_data, current_profile_data)) {
      return false;
    }
  }
  return true;
}

// Used to avoid having the same lambda in HaveSameEmailAddresses,
// HaveSameFirstNames, HaveSameStreetAddresses.
bool Equals(const base::string16& str1, const base::string16& str2) {
  return str1 == str2;
}

}  // namespace

void AddLabelPartIfNotEmpty(const base::string16& part,
                            std::vector<base::string16>* parts) {
  if (!part.empty()) {
    parts->push_back(part);
  }
}

base::string16 ConstructLabelLine(const std::vector<base::string16>& parts) {
  return base::JoinString(parts, l10n_util::GetStringUTF16(
                                     IDS_AUTOFILL_SUGGESTION_LABEL_SEPARATOR));
}

base::string16 ConstructMobileLabelLine(
    const std::vector<base::string16>& parts) {
  return base::JoinString(
      parts, l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_SUMMARY_SEPARATOR));
}

bool IsNonStreetAddressPart(ServerFieldType type) {
  switch (type) {
    case ADDRESS_HOME_CITY:
    case ADDRESS_BILLING_CITY:
    case ADDRESS_HOME_ZIP:
    case ADDRESS_BILLING_ZIP:
    case ADDRESS_HOME_STATE:
    case ADDRESS_BILLING_STATE:
    case ADDRESS_HOME_COUNTRY:
    case ADDRESS_BILLING_COUNTRY:
    case ADDRESS_HOME_SORTING_CODE:
    case ADDRESS_BILLING_SORTING_CODE:
    case ADDRESS_HOME_DEPENDENT_LOCALITY:
    case ADDRESS_BILLING_DEPENDENT_LOCALITY:
      return true;
    default:
      return false;
  }
}

bool IsStreetAddressPart(ServerFieldType type) {
  switch (type) {
    case ADDRESS_HOME_LINE1:
    case ADDRESS_HOME_LINE2:
    case ADDRESS_HOME_APT_NUM:
    case ADDRESS_BILLING_LINE1:
    case ADDRESS_BILLING_LINE2:
    case ADDRESS_BILLING_APT_NUM:
    case ADDRESS_HOME_STREET_ADDRESS:
    case ADDRESS_BILLING_STREET_ADDRESS:
    case ADDRESS_HOME_LINE3:
    case ADDRESS_BILLING_LINE3:
      return true;
    default:
      return false;
  }
}

bool HasNonStreetAddress(const std::vector<ServerFieldType>& types) {
  return base::ranges::any_of(types, IsNonStreetAddressPart);
}

bool HasStreetAddress(const std::vector<ServerFieldType>& types) {
  return base::ranges::any_of(types, IsStreetAddressPart);
}

std::vector<ServerFieldType> ExtractSpecifiedAddressFieldTypes(
    bool extract_street_address_types,
    const std::vector<ServerFieldType>& types) {
  auto should_be_extracted =
      [&extract_street_address_types](ServerFieldType type) -> bool {
    return AutofillType(AutofillType(type).GetStorableType()).group() ==
               ADDRESS_HOME &&
           (extract_street_address_types ? IsStreetAddressPart(type)
                                         : !IsStreetAddressPart(type));
  };

  std::vector<ServerFieldType> extracted_address_types;
  std::copy_if(types.begin(), types.end(),
               std::back_inserter(extracted_address_types),
               should_be_extracted);

  return extracted_address_types;
}

std::vector<ServerFieldType> ExtractAddressFieldTypes(
    const std::vector<ServerFieldType>& types) {
  std::vector<ServerFieldType> only_address_types;

  // Note that GetStorableType maps billing fields to their corresponding non-
  // billing fields, e.g. ADDRESS_HOME_ZIP is mapped to ADDRESS_BILLING_ZIP.
  std::copy_if(
      types.begin(), types.end(), std::back_inserter(only_address_types),
      [](ServerFieldType type) {
        return AutofillType(AutofillType(type).GetStorableType()).group() ==
               ADDRESS_HOME;
      });
  return only_address_types;
}

std::vector<ServerFieldType> TypesWithoutFocusedField(
    const std::vector<ServerFieldType>& types,
    ServerFieldType field_type_to_remove) {
  std::vector<ServerFieldType> types_without_field;
  std::copy_if(types.begin(), types.end(),
               std::back_inserter(types_without_field),
               [&field_type_to_remove](ServerFieldType type) -> bool {
                 return type != field_type_to_remove;
               });
  return types_without_field;
}

AutofillProfile MakeTrimmedProfile(const AutofillProfile& profile,
                                   const std::string& app_locale,
                                   const std::vector<ServerFieldType>& types) {
  AutofillProfile trimmed_profile(profile.guid(), profile.origin());
  trimmed_profile.set_language_code(profile.language_code());

  const AutofillType country_code_type(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE);
  const base::string16 country_code =
      profile.GetInfo(country_code_type, app_locale);
  trimmed_profile.SetInfo(country_code_type, country_code, app_locale);

  for (const ServerFieldType& type : types) {
    trimmed_profile.SetInfo(type, profile.GetInfo(type, app_locale),
                            app_locale);
  }
  return trimmed_profile;
}

base::string16 GetLabelForFocusedAddress(
    ServerFieldType focused_field_type,
    bool form_has_street_address,
    const AutofillProfile& profile,
    const std::string& app_locale,
    const std::vector<ServerFieldType>& types) {
  return GetLabelAddress(
      form_has_street_address && !IsStreetAddressPart(focused_field_type),
      profile, app_locale, types);
}

base::string16 GetLabelAddress(bool use_street_address,
                               const AutofillProfile& profile,
                               const std::string& app_locale,
                               const std::vector<ServerFieldType>& types) {
  return use_street_address
             ? GetLabelStreetAddress(
                   ExtractSpecifiedAddressFieldTypes(use_street_address, types),
                   profile, app_locale)
             : GetLabelNationalAddress(
                   ExtractSpecifiedAddressFieldTypes(use_street_address, types),
                   profile, app_locale);
}

base::string16 GetLabelNationalAddress(
    const std::vector<ServerFieldType>& types,
    const AutofillProfile& profile,
    const std::string& app_locale) {
  std::unique_ptr<::i18n::addressinput::AddressData> address_data =
      i18n::CreateAddressDataFromAutofillProfile(
          MakeTrimmedProfile(profile, app_locale, types), app_locale);

  std::string address_line;
  ::i18n::addressinput::GetFormattedNationalAddressLine(*address_data,
                                                        &address_line);
  return base::UTF8ToUTF16(address_line);
}

base::string16 GetLabelStreetAddress(const std::vector<ServerFieldType>& types,
                                     const AutofillProfile& profile,
                                     const std::string& app_locale) {
  std::unique_ptr<::i18n::addressinput::AddressData> address_data =
      i18n::CreateAddressDataFromAutofillProfile(
          MakeTrimmedProfile(profile, app_locale, types), app_locale);

  std::string address_line;
  ::i18n::addressinput::GetStreetAddressLinesAsSingleLine(*address_data,
                                                          &address_line);
  return base::UTF8ToUTF16(address_line);
}

base::string16 GetLabelForProfileOnFocusedNonStreetAddress(
    bool form_has_street_address,
    const AutofillProfile& profile,
    const std::string& app_locale,
    const std::vector<ServerFieldType>& types,
    const base::string16& contact_info) {
  std::vector<base::string16> label_parts;
  AddLabelPartIfNotEmpty(
      GetLabelAddress(form_has_street_address, profile, app_locale, types),
      &label_parts);
  AddLabelPartIfNotEmpty(contact_info, &label_parts);
  return ConstructLabelLine(label_parts);
}

base::string16 GetLabelName(const std::vector<ServerFieldType>& types,
                            const AutofillProfile& profile,
                            const std::string& app_locale) {
  bool has_first_name = false;
  bool has_last_name = false;
  bool has_full_name = false;

  for (const ServerFieldType type : types) {
    if (type == NAME_FULL) {
      has_full_name = true;
      break;
    }
    if (type == NAME_FIRST) {
      has_first_name = true;
    }
    if (type == NAME_LAST) {
      has_last_name = true;
    }
  }

  if (has_full_name) {
    return profile.GetInfo(AutofillType(NAME_FULL), app_locale);
  }

  if (has_first_name && has_last_name) {
    std::vector<base::string16> name_parts;
    AddLabelPartIfNotEmpty(GetLabelFirstName(profile, app_locale), &name_parts);
    AddLabelPartIfNotEmpty(profile.GetInfo(AutofillType(NAME_LAST), app_locale),
                           &name_parts);
    return base::JoinString(name_parts, base::ASCIIToUTF16(" "));
  }

  if (has_first_name) {
    return GetLabelFirstName(profile, app_locale);
  }

  if (has_last_name) {
    return profile.GetInfo(AutofillType(NAME_LAST), app_locale);
  }

  // The form contains neither a full name field nor a first name field,
  // so choose some name field in the form and make it the label text.
  for (const ServerFieldType type : types) {
    if (AutofillType(AutofillType(type).GetStorableType()).group() == NAME) {
      return profile.GetInfo(AutofillType(type), app_locale);
    }
  }
  return base::string16();
}

base::string16 GetLabelFirstName(const AutofillProfile& profile,
                                 const std::string& app_locale) {
  return profile.GetInfo(AutofillType(NAME_FIRST), app_locale);
}

base::string16 GetLabelEmail(const AutofillProfile& profile,
                             const std::string& app_locale) {
  const base::string16 email =
      profile.GetInfo(AutofillType(EMAIL_ADDRESS), app_locale);
  return IsValidEmailAddress(email) ? email : base::string16();
}

base::string16 GetLabelPhone(const AutofillProfile& profile,
                             const std::string& app_locale) {
  const std::string unformatted_phone = base::UTF16ToUTF8(
      profile.GetInfo(AutofillType(PHONE_HOME_WHOLE_NUMBER), app_locale));
  return unformatted_phone.empty()
             ? base::string16()
             : base::UTF8ToUTF16(i18n::FormatPhoneNationallyForDisplay(
                   unformatted_phone,
                   data_util::GetCountryCodeWithFallback(profile, app_locale)));
}

bool HaveSameEmailAddresses(const std::vector<AutofillProfile*>& profiles,
                            const std::string& app_locale) {
  return HaveSameData(profiles, app_locale, base::BindRepeating(&GetLabelEmail),
                      base::BindRepeating(base::BindRepeating(&Equals)));
}

bool HaveSameFirstNames(const std::vector<AutofillProfile*>& profiles,
                        const std::string& app_locale) {
  return HaveSameData(profiles, app_locale,
                      base::BindRepeating(&GetLabelFirstName),
                      base::BindRepeating(base::BindRepeating(&Equals)));
}

bool HaveSameNonStreetAddresses(const std::vector<AutofillProfile*>& profiles,
                                const std::string& app_locale,
                                const std::vector<ServerFieldType>& types) {
  // In general, comparing non street addresses with Equals, which uses ==, is
  // not ideal since Düsseldorf and Dusseldorf will be considered distinct. It's
  // okay to use it here because near-duplicate non street addresses like this
  // are filtered out before a LabelFormatter is created.
  return HaveSameData(profiles, app_locale,
                      base::BindRepeating(&GetLabelNationalAddress, types),
                      base::BindRepeating(&Equals));
}

bool HaveSamePhoneNumbers(const std::vector<AutofillProfile*>& profiles,
                          const std::string& app_locale) {
  // Note that the same country code is used in all comparisons.
  auto equals = [](const std::string& country_code,
                   const std::string& app_locale, const base::string16& phone1,
                   const base::string16& phone2) -> bool {
    return (phone1.empty() && phone2.empty()) ||
           i18n::PhoneNumbersMatch(phone1, phone2, country_code, app_locale);
  };

  return profiles.size() <= 1
             ? true
             : HaveSameData(
                   profiles, app_locale, base::BindRepeating(&GetLabelPhone),
                   base::BindRepeating(equals,
                                       base::UTF16ToASCII(profiles[0]->GetInfo(
                                           ADDRESS_HOME_COUNTRY, app_locale)),
                                       app_locale));
}

bool HaveSameStreetAddresses(const std::vector<AutofillProfile*>& profiles,
                             const std::string& app_locale,
                             const std::vector<ServerFieldType>& types) {
  // In general, comparing street addresses with Equals, which uses ==, is not
  // ideal since 3 Elm St and 3 Elm St. will be considered distinct. It's okay
  // to use it here because near-duplicate addresses like this are filtered
  // out before a LabelFormatter is created.
  return HaveSameData(profiles, app_locale,
                      base::BindRepeating(&GetLabelStreetAddress, types),
                      base::BindRepeating(&Equals));
}

bool HasUnfocusedEmailField(FieldTypeGroup focused_group,
                            uint32_t form_groups) {
  return ContainsEmail(form_groups) && focused_group != EMAIL;
}

bool HasUnfocusedNameField(FieldTypeGroup focused_group, uint32_t form_groups) {
  return ContainsName(form_groups) && focused_group != NAME;
}

bool HasUnfocusedNonStreetAddressField(
    ServerFieldType focused_field,
    FieldTypeGroup focused_group,
    const std::vector<ServerFieldType>& types) {
  return HasNonStreetAddress(types) && (focused_group != ADDRESS_HOME ||
                                        !IsNonStreetAddressPart(focused_field));
}

bool HasUnfocusedPhoneField(FieldTypeGroup focused_group,
                            uint32_t form_groups) {
  return ContainsPhone(form_groups) && focused_group != PHONE_HOME;
}

bool HasUnfocusedStreetAddressField(ServerFieldType focused_field,
                                    FieldTypeGroup focused_group,
                                    const std::vector<ServerFieldType>& types) {
  return HasStreetAddress(types) &&
         (focused_group != ADDRESS_HOME || !IsStreetAddressPart(focused_field));
}

bool FormHasOnlyNonStreetAddressFields(
    const std::vector<ServerFieldType>& types,
    uint32_t form_groups) {
  return ContainsAddress(form_groups) && !HasStreetAddress(types) &&
         !(ContainsName(form_groups) || ContainsPhone(form_groups) ||
           ContainsEmail(form_groups));
}

}  // namespace autofill