File: autofill_driver_ios.mm

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (780 lines) | stat: -rw-r--r-- 28,906 bytes parent folder | download | duplicates (2)
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
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "components/autofill/ios/browser/autofill_driver_ios.h"

#import <variant>

#import "base/check_deref.h"
#import "base/containers/contains.h"
#import "base/containers/to_vector.h"
#import "base/feature_list.h"
#import "base/functional/bind.h"
#import "base/memory/ptr_util.h"
#import "base/memory/raw_ptr.h"
#import "base/memory/weak_ptr.h"
#import "base/metrics/histogram.h"
#import "base/metrics/histogram_functions.h"
#import "base/observer_list.h"
#import "base/types/optional_ref.h"
#import "components/autofill/core/browser/filling/form_filler.h"
#import "components/autofill/core/browser/form_structure.h"
#import "components/autofill/core/browser/foundations/autofill_driver_router.h"
#import "components/autofill/core/common/autofill_features.h"
#import "components/autofill/core/common/field_data_manager.h"
#import "components/autofill/core/common/mojom/autofill_types.mojom-shared.h"
#import "components/autofill/core/common/unique_ids.h"
#import "components/autofill/ios/browser/autofill_client_ios.h"
#import "components/autofill/ios/browser/autofill_driver_ios_bridge.h"
#import "components/autofill/ios/browser/autofill_driver_ios_factory.h"
#import "components/autofill/ios/browser/autofill_java_script_feature.h"
#import "components/autofill/ios/browser/autofill_util.h"
#import "components/autofill/ios/browser/form_fetch_batcher.h"
#import "components/autofill/ios/common/features.h"
#import "components/autofill/ios/common/field_data_manager_factory_ios.h"
#import "components/autofill/ios/form_util/child_frame_registrar.h"
#import "components/ukm/ios/ukm_url_recorder.h"
#import "ios/web/public/browser_state.h"
#import "ios/web/public/js_messaging/content_world.h"
#import "ios/web/public/js_messaging/web_frame.h"
#import "ios/web/public/js_messaging/web_frames_manager.h"
#import "ios/web/public/web_state.h"
#import "services/network/public/cpp/shared_url_loader_factory.h"
#import "url/origin.h"

namespace autofill {

namespace {
// AutofillDriverIOS::router_ only ever routes between instances of
// AutofillDriverIOS, so this cast is safe.
AutofillDriverIOS* cast(AutofillDriver* driver) {
  return static_cast<AutofillDriverIOS*>(driver);
}

bool IsAcrossIframesEnabled() {
  return base::FeatureList::IsEnabled(
      autofill::features::kAutofillAcrossIframesIos);
}

base::TimeDelta GetDocumentFormScanPeriod() {
  return base::Milliseconds(kAutofillDocumentFormScanPeriodMs.Get());
}

base::TimeDelta GetFilteredDocumentFormScanPeriod() {
  return base::Milliseconds(kAutofillFilteredDocumentFormScanPeriodMs.Get());
}

bool UseXhrFix() {
  return base::FeatureList::IsEnabled(kAutofillFixXhrForXframe);
}

}  // namespace

// static
AutofillDriverIOS* AutofillDriverIOS::FromWebStateAndWebFrame(
    web::WebState* web_state,
    web::WebFrame* web_frame) {
  if (AutofillClientIOS* client = AutofillClientIOS::FromWebState(web_state)) {
    return client->GetAutofillDriverFactory().DriverForFrame(web_frame);
  }
  return nullptr;
}

// static
AutofillDriverIOS* AutofillDriverIOS::FromWebStateAndLocalFrameToken(
    web::WebState* web_state,
    LocalFrameToken token) {
  web::WebFramesManager* frames_manager =
      AutofillJavaScriptFeature::GetInstance()->GetWebFramesManager(web_state);
  web::WebFrame* frame = frames_manager->GetFrameWithId(token.ToString());
  return frame ? FromWebStateAndWebFrame(web_state, frame) : nullptr;
}

AutofillDriverIOS::AutofillDriverIOS(
    web::WebState* web_state,
    web::WebFrame* web_frame,
    AutofillClient* client,
    AutofillDriverRouter* router,
    id<AutofillDriverIOSBridge> bridge,
    base::PassKey<AutofillDriverIOSFactory> pass_key)
    : web_state_(web_state),
      web_frame_id_(web_frame ? web_frame->GetFrameId() : ""),
      bridge_(bridge),
      client_(*client),
      manager_(std::make_unique<BrowserAutofillManager>(this)),
      router_(router),
      document_scan_batcher_(bridge,
                             web_frame ? web_frame->AsWeakPtr() : nullptr,
                             GetDocumentFormScanPeriod()),
      document_filtered_scan_batcher_(
          bridge,
          web_frame ? web_frame->AsWeakPtr() : nullptr,
          GetFilteredDocumentFormScanPeriod()) {
  manager_observation_.Observe(manager_.get());

  if (IsAcrossIframesEnabled()) {
    std::optional<base::UnguessableToken> token_temp =
        DeserializeJavaScriptFrameId(web_frame_id_);
    if (token_temp) {
      local_frame_token_ = LocalFrameToken(*token_temp);
    }
  }
}

AutofillDriverIOS::~AutofillDriverIOS() {
  Unregister();
  RecordTriggeredFormExtractionMetrics();
}

LocalFrameToken AutofillDriverIOS::GetFrameToken() const {
  return local_frame_token_;
}

std::optional<LocalFrameToken> AutofillDriverIOS::Resolve(FrameToken query) {
  if (!IsAcrossIframesEnabled()) {
    return std::nullopt;
  }

  if (std::holds_alternative<LocalFrameToken>(query)) {
    return std::get<LocalFrameToken>(query);
  }
  CHECK(std::holds_alternative<RemoteFrameToken>(query));
  auto remote_token = std::get<RemoteFrameToken>(query);
  auto* registrar = ChildFrameRegistrar::FromWebState(web_state_);
  return registrar ? registrar->LookupChildFrame(remote_token) : std::nullopt;
}

AutofillDriverIOS* AutofillDriverIOS::GetParent() {
  return parent_.get();
}

AutofillClient& AutofillDriverIOS::GetAutofillClient() {
  return *client_;
}

BrowserAutofillManager& AutofillDriverIOS::GetAutofillManager() {
  return *manager_;
}

ukm::SourceId AutofillDriverIOS::GetPageUkmSourceId() const {
  return ukm::GetSourceIdForWebStateDocument(web_state_);
}

// Return true as iOS has no MPArch.
bool AutofillDriverIOS::IsActive() const {
  return true;
}

bool AutofillDriverIOS::HasSharedAutofillPermission() const {
  // Give the shared-autofill permission to the main frame of the webstate by
  // default.
  if (!web_frame() || web_frame()->IsMainFrame()) {
    return true;
  }

  // Also propagate that permission to the direct children of the main
  // frame on the same origin as the main frame.
  if (parent_ && parent_->web_frame() && parent_->web_frame()->IsMainFrame() &&
      web_frame()) {
    return parent_->web_frame()->GetSecurityOrigin() ==
           web_frame()->GetSecurityOrigin();
  }

  // Return false as share-autofill is not allowed.
  return false;
}

bool AutofillDriverIOS::CanShowAutofillUi() const {
  return true;
}

base::flat_set<FieldGlobalId> AutofillDriverIOS::ApplyFormAction(
    mojom::FormActionType action_type,
    mojom::ActionPersistence action_persistence,
    base::span<const FormFieldData> fields,
    const url::Origin& triggered_origin,
    const base::flat_map<FieldGlobalId, FieldType>& field_type_map) {
  switch (action_type) {
    case mojom::FormActionType::kUndo:
      // TODO(crbug.com/40266549) Add Undo support on iOS.
      return {};
    case mojom::FormActionType::kFill: {
      auto callback = [](AutofillDriver& driver,
                         mojom::FormActionType action_type,
                         mojom::ActionPersistence action_persistence,
                         const std::vector<FormFieldData::FillData>& fields) {
        web::WebFrame* frame = cast(&driver)->web_frame();
        if (frame) {
          [cast(&driver)->bridge_ fillData:fields inFrame:frame];
        }
      };

      const url::Origin main_origin =
          client_->GetLastCommittedPrimaryMainFrameOrigin();
      if (IsAcrossIframesEnabled()) {
        return router_->ApplyFormAction(callback, action_type,
                                        action_persistence, fields, main_origin,
                                        triggered_origin, field_type_map);
      } else {
        std::vector<FieldGlobalId> safe_fields;
        for (const auto& field : fields) {
          safe_fields.push_back(field.global_id());
        }

        callback(
            *this, action_type, action_persistence,
            std::vector<FormFieldData::FillData>(fields.begin(), fields.end()));
        return safe_fields;
      }
    }
  }
}

void AutofillDriverIOS::ApplyFieldAction(
    mojom::FieldActionType action_type,
    mojom::ActionPersistence action_persistence,
    const FieldGlobalId& field_id,
    const std::u16string& value) {
  auto callback = [](AutofillDriver& driver, mojom::FieldActionType action_type,
                     mojom::ActionPersistence action_persistence,
                     FieldRendererId field, const std::u16string& value) {
    // For now, only support filling.
    switch (action_persistence) {
      case mojom::ActionPersistence::kFill: {
        [cast(&driver)->bridge_
            fillSpecificFormField:field
                        withValue:value
                          inFrame:cast(&driver)->web_frame()];
        break;
      }
      case mojom::ActionPersistence::kPreview:
        return;
    }
  };
  if (IsAcrossIframesEnabled()) {
    router_->ApplyFieldAction(callback, action_type, action_persistence,
                              field_id, value);
  } else {
    callback(*this, action_type, action_persistence, field_id.renderer_id,
             value);
  }
}

void AutofillDriverIOS::ExtractForm(
    FormGlobalId form,
    base::OnceCallback<void(AutofillDriver*, const std::optional<FormData>&)>
        response_callback) {
  // TODO(crbug.com/40284824): Implement ExtractForm().
  NOTIMPLEMENTED();
}

void AutofillDriverIOS::ExposeDomNodeIDs() {}

void AutofillDriverIOS::SendTypePredictionsToRenderer(
    const FormStructure& form) {
  CHECK(base::FeatureList::IsEnabled(
      features::test::kAutofillShowTypePredictions));
  auto callback = [](AutofillDriver& driver,
                     const std::vector<FormDataPredictions>& preds) {
    web::WebFrame* frame = cast(&driver)->web_frame();
    if (!frame) {
      return;
    }
    [cast(&driver)->bridge_ fillFormDataPredictions:preds inFrame:frame];
  };

  if (IsAcrossIframesEnabled()) {
    router_->SendTypePredictionsToRenderer(callback,
                                           form.GetFieldTypePredictions());
  } else {
    callback(*this, {form.GetFieldTypePredictions()});
  }
}

void AutofillDriverIOS::RendererShouldAcceptDataListSuggestion(
    const FieldGlobalId& field_id,
    const std::u16string& value) {}

void AutofillDriverIOS::TriggerFormExtractionInDriverFrame(
    AutofillDriverRouterAndFormForestPassKey pass_key) {
  if (!is_processed()) {
    return;
  }

  if (base::FeatureList::IsEnabled(
          features::kAutofillAcrossIframesIosTriggerFormExtraction)) {
    ScanForms();
  }
}

void AutofillDriverIOS::ScanForms(bool immediately) {
  if (!web_frame()) {
    return;
  }

  const auto callback =
      [](id<AutofillDriverIOSBridge> bridge, base::WeakPtr<web::WebFrame> frame,
         std::optional<std::vector<autofill::FormData>> forms) {
        if (!frame || !forms || forms->empty()) {
          return;
        }
        [bridge notifyFormsSeen:*std::move(forms) inFrame:frame.get()];
      };

  if (base::FeatureList::IsEnabled(kAutofillThrottleDocumentFormScanIos)) {
    immediately ? document_scan_batcher_.PushRequestAndRun(base::BindOnce(
                      callback, bridge_, web_frame()->AsWeakPtr()))
                : document_scan_batcher_.PushRequest(base::BindOnce(
                      callback, bridge_, web_frame()->AsWeakPtr()));
  } else {
    [bridge_ fetchFormsFiltered:NO
                       withName:std::u16string()
                        inFrame:web_frame()
              completionHandler:base::BindOnce(callback, bridge_,
                                               web_frame()->AsWeakPtr())];
  }
}

void AutofillDriverIOS::FetchFormsFilteredByName(
    const std::u16string& form_name,
    FormFetchCompletion completion) {
  if (!web_frame()) {
    return;
  }

  if (base::FeatureList::IsEnabled(
          kAutofillThrottleFilteredDocumentFormScanIos)) {
    document_filtered_scan_batcher_.PushRequest(std::move(completion),
                                                form_name);
  } else {
    [bridge_ fetchFormsFiltered:YES
                       withName:form_name
                        inFrame:web_frame()
              completionHandler:std::move(completion)];
  }
}

void AutofillDriverIOS::TriggerFormExtractionInAllFrames(
    base::OnceCallback<void(bool)> form_extraction_finished_callback) {
  NOTIMPLEMENTED();
}

void AutofillDriverIOS::GetFourDigitCombinationsFromDom(
    base::OnceCallback<void(const std::vector<std::string>&)>
        potential_matches) {
  // TODO(crbug.com/40260122): Implement GetFourDigitCombinationsFromDom() in
  // iOS.
  NOTIMPLEMENTED();
}

void AutofillDriverIOS::ExtractLabeledTextNodeValue(
    const std::u16string& value_regex,
    const std::u16string& label_regex,
    uint32_t number_of_ancestor_levels_to_search,
    base::OnceCallback<void(const std::string& amount)> response_callback) {
  NOTIMPLEMENTED();
}

void AutofillDriverIOS::RendererShouldClearPreviewedForm() {}

void AutofillDriverIOS::RendererShouldTriggerSuggestions(
    const FieldGlobalId& field_id,
    AutofillSuggestionTriggerSource trigger_source) {
  // Triggering suggestions from the browser process is currently only used for
  // manual fallbacks on Desktop. It is not implemented on iOS.
  NOTIMPLEMENTED();
}

void AutofillDriverIOS::RendererShouldSetSuggestionAvailability(
    const FieldGlobalId& field_id,
    mojom::AutofillSuggestionAvailability suggestion_availability) {}

std::optional<net::IsolationInfo> AutofillDriverIOS::GetIsolationInfo() {
  // On iOS we have a single, shared URLLoaderFactory provided by BrowserState.
  // As it is shared, it is not trusted and we cannot assign trusted_params
  // to the network request. On iOS, the IsolationInfo should always be nullopt.
  return std::nullopt;
}

web::WebFrame* AutofillDriverIOS::web_frame() const {
  web::WebFramesManager* frames_manager =
      AutofillJavaScriptFeature::GetInstance()->GetWebFramesManager(web_state_);
  return frames_manager->GetFrameWithId(web_frame_id_);
}

void AutofillDriverIOS::AskForValuesToFill(const FormData& form,
                                           const FieldGlobalId& field_id) {
  auto callback =
      [](AutofillDriver& driver, const FormData& form,
         const FieldGlobalId& field_id, const gfx::Rect& bounding_box,
         AutofillSuggestionTriggerSource trigger_source,
         base::optional_ref<const PasswordSuggestionRequest> request) {
        driver.GetAutofillManager().OnAskForValuesToFill(
            form, field_id, bounding_box, trigger_source, request);
      };
  // The caret position is currently not extracted on iOS.
  gfx::Rect caret_bounds;
  if (IsAcrossIframesEnabled()) {
    // TODO(crbug.com/40269303): Distinguish between different trigger sources.
    router_->AskForValuesToFill(callback, *this, form, field_id, caret_bounds,
                                autofill::AutofillSuggestionTriggerSource::kiOS,
                                std::nullopt);
  } else {
    callback(*this, form, field_id, caret_bounds,
             autofill::AutofillSuggestionTriggerSource::kiOS, std::nullopt);
  }
}

void AutofillDriverIOS::DidFillAutofillFormData(const FormData& form,
                                                base::TimeTicks timestamp) {
  if (UseXhrFix()) {
    // Update the last_interacted_form_ locally in the renderer frame before
    // routing so XHR detection can be done when a renderer form is deleted.
    UpdateLastInteractedForm(/*form_data=*/form);
  }
  auto callback = [](AutofillDriver& driver, const FormData& form,
                     base::TimeTicks timestamp) {
    if (!UseXhrFix()) {
      cast(&driver)->UpdateLastInteractedForm(/*form_data=*/form);
    }
    driver.GetAutofillManager().OnDidFillAutofillFormData(form, timestamp);
  };
  if (IsAcrossIframesEnabled()) {
    router_->DidFillAutofillFormData(callback, *this, form, timestamp);
  } else {
    callback(*this, form, timestamp);
  }
}

void AutofillDriverIOS::FormsSeen(
    const std::vector<FormData>& updated_forms,
    const std::vector<FormGlobalId>& removed_forms) {
  auto callback = [](AutofillDriver& driver,
                     const std::vector<FormData>& updated_forms,
                     const std::vector<FormGlobalId>& removed_forms) {
    driver.GetAutofillManager().OnFormsSeen(updated_forms, removed_forms);
  };

  if (IsAcrossIframesEnabled()) {
    // Any RemoteFrameTokens encountered for the first time should be posted to
    // the registrar, which allows this driver to be established as the parent
    // of the child frame.
    for (const autofill::FormData& form : updated_forms) {
      for (const autofill::FrameTokenWithPredecessor& child_frame :
           form.child_frames()) {
        // This std::get is safe because on iOS, FormData::child_frames is
        // only ever populated with RemoteFrameTokens. std::get will fail a
        // CHECK if this assumption is ever wrong.
        auto token = std::get<autofill::RemoteFrameToken>(child_frame.token);
        auto* registrar =
            ChildFrameRegistrar::GetOrCreateForWebState(web_state_);
        if (registrar && known_child_frames_.insert(token).second) {
          registrar->DeclareNewRemoteToken(
              token, base::BindOnce(&AutofillDriverIOS::SetSelfAsParent,
                                    weak_ptr_factory_.GetWeakPtr(), form));
        }
      }
    }
    router_->FormsSeen(callback, *this, updated_forms, removed_forms);
  } else {
    callback(*this, updated_forms, removed_forms);
  }
}

void AutofillDriverIOS::FormSubmitted(
    const FormData& form,
    mojom::SubmissionSource submission_source) {
  auto callback = [webstate_ptr = web_state_](
                      AutofillDriver& driver, const FormData& form,
                      mojom::SubmissionSource submission_source) {
    CHECK(webstate_ptr);
    base::UmaHistogramEnumeration(kAutofillSubmissionDetectionSourceHistogram,
                                  submission_source);
    driver.GetAutofillManager().OnFormSubmitted(form, submission_source);
    if (UseXhrFix()) {
      // Clear the last interacted form on the child frames to not trigger
      // XHR again in case there were some interactions with forms in these
      // frames prior to submission. This is to avoid spamming submits.
      for (const auto& remote_token : form.child_frames()) {
        if (std::optional<LocalFrameToken> local_token =
                driver.Resolve(remote_token.token)) {
          if (AutofillDriverIOS* child_driver =
                  FromWebStateAndLocalFrameToken(webstate_ptr, *local_token)) {
            child_driver->ClearLastInteractedForm();
          }
        }
      }
    }
    cast(&driver)->ClearLastInteractedForm();
  };
  if (IsAcrossIframesEnabled()) {
    router_->FormSubmitted(callback, *this, form, submission_source);
  } else {
    callback(*this, form, submission_source);
  }
  if (UseXhrFix()) {
    ClearLastInteractedForm();
  }
}

void AutofillDriverIOS::CaretMovedInFormField(const FormData& form,
                                              const FieldGlobalId& field_id,
                                              const gfx::Rect& caret_bounds) {
  GetAutofillManager().OnCaretMovedInFormField(form, field_id, caret_bounds);
}

void AutofillDriverIOS::TextFieldValueChanged(const FormData& form,
                                              const FieldGlobalId& field_id,
                                              base::TimeTicks timestamp) {
  if (UseXhrFix()) {
    // Update the last_interacted_form_ locally in the renderer frame before
    // routing so XHR detection can be done when a renderer form is deleted.
    UpdateLastInteractedForm(
        /*form_data=*/form,
        /*formless_field=*/form.renderer_id() ? FieldRendererId()
                                              : field_id.renderer_id);
  }
  auto callback = [&](AutofillDriver& driver, const FormData& form,
                      const FieldGlobalId& field_global_id,
                      base::TimeTicks timestamp) {
    if (!UseXhrFix()) {
      cast(&driver)->UpdateLastInteractedForm(
          /*form_data=*/form,
          /*formless_field=*/form.renderer_id() ? FieldRendererId()
                                                : field_global_id.renderer_id);
    }
    driver.GetAutofillManager().OnTextFieldValueChanged(form, field_id,
                                                        timestamp);
  };

  if (IsAcrossIframesEnabled()) {
    router_->TextFieldValueChanged(callback, *this, form, field_id, timestamp);
  } else {
    callback(*this, form, field_id, timestamp);
  }
}

void AutofillDriverIOS::SetParent(base::WeakPtr<AutofillDriverIOS> parent) {
  if (unregistered_) {
    // Do not set parent if the driver was unregistered to avoid any risk
    // of connecting it back into a form tree, where it has to be kept alone as
    // a standalone node.
    return;
  }

  parent_ = std::move(parent);
}

void AutofillDriverIOS::SetSelfAsParent(const autofill::FormData& form,
                                        LocalFrameToken token) {
  AutofillDriverIOS* child_driver =
      FromWebStateAndLocalFrameToken(web_state_, token);
  if (child_driver) {
    child_driver->SetParent(weak_ptr_factory_.GetWeakPtr());
  }
  // Redeclare the forms as seen to take into account the new parent to
  // establish the relation between the child frames and their host form in the
  // forms tree.
  auto callback = [](AutofillDriver& driver,
                     const std::vector<FormData>& updated_forms,
                     const std::vector<FormGlobalId>& removed_forms) {
    driver.GetAutofillManager().OnFormsSeen(updated_forms, removed_forms);
  };
  router_->FormsSeen(callback, *this, {form}, {});
}

void AutofillDriverIOS::UpdateLastInteractedForm(
    const FormData& form_data,
    const FieldRendererId& formless_field) {
  last_interacted_form_.emplace(form_data, formless_field);
}

void AutofillDriverIOS::ClearLastInteractedForm() {
  last_interacted_form_.reset();
}

void AutofillDriverIOS::OnAutofillManagerStateChanged(
    AutofillManager& manager,
    LifecycleState old_state,
    LifecycleState new_state) {
  switch (new_state) {
    case LifecycleState::kInactive:
    case LifecycleState::kActive:
    case LifecycleState::kPendingReset:
      break;
    case LifecycleState::kPendingDeletion:
      manager_observation_.Reset();
      break;
  }
}

void AutofillDriverIOS::OnAfterFormsSeen(
    AutofillManager& manager,
    base::span<const FormGlobalId> updated_forms,
    base::span<const FormGlobalId> removed_forms) {
  DCHECK_EQ(&manager, manager_.get());
  if (updated_forms.empty()) {
    return;
  }
  std::vector<raw_ptr<FormStructure, VectorExperimental>> form_structures;
  form_structures.reserve(updated_forms.size());
  for (const FormGlobalId& form : updated_forms) {
    if (FormStructure* form_structure = manager.FindCachedFormById(form)) {
      form_structures.push_back(form_structure);
    }
  }
  if (web::WebFrame* frame = web_frame()) {
    [bridge_ handleParsedForms:form_structures inFrame:frame];
  }
}

void AutofillDriverIOS::FormsRemoved(
    const std::set<FormRendererId>& removed_forms,
    const std::set<FieldRendererId>& removed_unowned_fields) {
  bool submission_detected = DetectFormSubmissionAfterFormRemoval(
      removed_forms, removed_unowned_fields);
  RecordFormRemoval(
      submission_detected, /*removed_forms_count=*/removed_forms.size(),
      /*removed_unowned_fields_count=*/removed_unowned_fields.size());

  if (submission_detected) {
    UpdateLastInteractedFormFromFieldDataManager();

    FormSubmitted(last_interacted_form_->form_data,
                  mojom::SubmissionSource::XHR_SUCCEEDED);
  }

  // Report the removed forms so Autofill can be synced with the DOM state.

  std::vector<FormGlobalId> forms_to_report =
      base::ToVector(removed_forms, [&](const auto& renderer_id) {
        return FormGlobalId{.frame_token = local_frame_token_,
                            .renderer_id = renderer_id};
      });

  if (!removed_unowned_fields.empty()) {
    // Determine whether the synthetic form should be reported as removed based
    // on the removed fields, where having all fields removed is considered as
    // a deletion.
    FormGlobalId synthetic_global_id = {.frame_token = local_frame_token_,
                                        .renderer_id = FormRendererId(0)};
    if (FormStructure* form =
            GetAutofillManager().FindCachedFormById(synthetic_global_id)) {
      std::set<FieldRendererId> form_fields;
      std::ranges::transform(form->fields(),
                             std::inserter(form_fields, form_fields.begin()),
                             [](const std::unique_ptr<AutofillField>& field) {
                               return field->renderer_id();
                             });
      // If the synthetic form fields are a subset of the removed fields, it
      // means that all the synthetic form fields were removed.
      const bool is_deleted =
          std::ranges::includes(removed_unowned_fields, form_fields);
      if (is_deleted) {
        forms_to_report.emplace_back(synthetic_global_id);
      }
    }

    // TODO(crbug.com/351685487): Trigger forms extraction if there are some
    // fields removed but not all of them.
  }

  if (!forms_to_report.empty()) {
    FormsSeen(/*updated_forms=*/{}, /*removed_forms=*/forms_to_report);
  }
}

bool AutofillDriverIOS::DetectFormSubmissionAfterFormRemoval(
    const std::set<FormRendererId>& removed_forms,
    const std::set<FieldRendererId>& removed_unowned_fields) const {
  // Detect a form submission only if the last interacted form or formless field
  // was removed.
  if (!last_interacted_form_) {
    return false;
  }

  const auto& last_interacted_form_id =
      last_interacted_form_->form_data.renderer_id();
  // Check if the last interacted form was removed.
  if (last_interacted_form_id &&
      removed_forms.find(last_interacted_form_id) != removed_forms.end()) {
    return true;
  }

  const auto& last_formless_field_id = last_interacted_form_->formless_field;

  // Check if the last interacted formless field was removed.
  return removed_unowned_fields.find(last_formless_field_id) !=
         removed_unowned_fields.end();
}

void AutofillDriverIOS::Unregister() {
  router_->UnregisterDriver(*this, /*driver_is_dying=*/true);
  unregistered_ = true;
}

void AutofillDriverIOS::OnDidTriggerFormFetch() {
  ++form_extraction_trigger_count_;
}

void AutofillDriverIOS::UpdateLastInteractedFormFromFieldDataManager() {
  CHECK(last_interacted_form_);

  auto* frame = web_frame();
  if (!frame) {
    return;
  }

  FieldDataManager* field_data_manager =
      FieldDataManagerFactoryIOS::FromWebFrame(frame);

  // Update the snapshot of the last interacted form with the data in
  // FieldDataManager.
  std::vector<FormFieldData> fields =
      last_interacted_form_->form_data.ExtractFields();
  for (auto& field : fields) {
    const auto& field_id = field.renderer_id();
    if (!field_data_manager->HasFieldData(field_id)) {
      continue;
    }
    field.set_value(field_data_manager->GetUserInput(field_id));
    field.set_properties_mask(
        field_data_manager->GetFieldPropertiesMask(field_id));
  }
  last_interacted_form_->form_data.set_fields(std::move(fields));
}

void AutofillDriverIOS::RecordFormRemoval(bool submission_detected,
                                          int removed_forms_count,
                                          int removed_unowned_fields_count) {
  base::UmaHistogramBoolean(/*name=*/kFormSubmissionAfterFormRemovalHistogram,
                            /*sample=*/submission_detected);
  base::UmaHistogramCounts100(
      /*name=*/kFormRemovalRemovedUnownedFieldsHistogram,
      /*sample=*/removed_unowned_fields_count);

}

void AutofillDriverIOS::RecordTriggeredFormExtractionMetrics() {
  if (form_extraction_trigger_count_ < 1) {
    // Do not record anything if no extraction was performed to not pollute
    // the data with 0 extraction cases that don't really mean anything.
    // We usually expect at least one extraction to be triggered in the frame
    // when its content is loaded. We are not interested in tracking the cases
    // where extraction didn't happen, not for these metrics at least.
    return;
  }

  base::UmaHistogramCounts100(
      "Autofill.iOS.TriggeredFormExtractionFromDriver.SmallRange",
      form_extraction_trigger_count_);
  base::UmaHistogramCounts1000(
      "Autofill.iOS.TriggeredFormExtractionFromDriver.MediumRange",
      form_extraction_trigger_count_);
  base::UmaHistogramCounts10000(
      "Autofill.iOS.TriggeredFormExtractionFromDriver.LargeRange",
      form_extraction_trigger_count_);
}

}  // namespace autofill