From: uazo <uazo@users.noreply.github.com>
Date: Sun, 24 Oct 2021 16:54:04 +0000
Subject: Enable native Android autofill

There are 2 different types of autofill: one managed via GCM and the
native Android one that uses the provider assigned by the user
(which can be any user installed app like Bitwarden for example).
In chromium GCM is active while in the WebView the latter.
This patch uses WebView code to enable native Android autofill
along with browser-managed autofill.
A separate toggle is introduced to enable autofill in incognito mode.

See also: https://github.com/bromite/bromite/issues/547

Original License: GPL-2.0-or-later - https://spdx.org/licenses/GPL-2.0-or-later.html
License: GPL-3.0-only - https://spdx.org/licenses/GPL-3.0-only.html
---
 android_webview/browser/aw_contents.cc        |  3 +-
 chrome/android/BUILD.gn                       |  1 +
 .../settings/PasswordSettings.java            | 81 ++++++++++++++++++-
 .../chromium/chrome/browser/tab/TabImpl.java  | 50 ++++++++++++
 .../browser/tab/TabViewAndroidDelegate.java   | 14 ++++
 chrome/browser/BUILD.gn                       |  7 ++
 chrome/browser/android/tab_android.cc         | 23 ++++++
 chrome/browser/android/tab_android.h          |  2 +
 .../tab_web_contents_delegate_android.cc      |  3 +-
 .../strings/android_chrome_strings.grd        |  6 ++
 chrome/browser/ui/tab_helpers.cc              |  6 +-
 .../browser/android_autofill_manager.cc       |  2 +-
 .../browser/android_autofill_manager.h        | 10 +--
 .../browser/content_autofill_driver.cc        | 30 +++++++
 .../content/browser/content_autofill_driver.h |  9 ++-
 .../content_autofill_driver_factory.cc        |  7 +-
 .../browser/content_autofill_driver_factory.h |  1 +
 .../renderer/password_autofill_agent.cc       |  5 +-
 .../autofill/core/common/autofill_prefs.cc    |  8 ++
 .../autofill/core/common/autofill_prefs.h     |  2 +
 .../embedder_support/view/ContentView.java    | 46 +++++++++++
 .../chromium/ui/base/ViewAndroidDelegate.java |  8 ++
 22 files changed, 311 insertions(+), 13 deletions(-)

diff --git a/android_webview/browser/aw_contents.cc b/android_webview/browser/aw_contents.cc
--- a/android_webview/browser/aw_contents.cc
+++ b/android_webview/browser/aw_contents.cc
@@ -342,7 +342,8 @@ void AwContents::InitAutofillIfNecessary(bool autocomplete_enabled) {
                                 enable_download_manager)
           : base::BindRepeating(&autofill::BrowserDriverInitHook,
                                 AwAutofillClient::FromWebContents(web_contents),
-                                base::android::GetDefaultLocaleString());
+                                base::android::GetDefaultLocaleString(),
+                                /*enable_secondary_autofill_manager*/ false);
 
   ContentAutofillDriverFactory::CreateForWebContentsAndDelegate(
       web_contents, AwAutofillClient::FromWebContents(web_contents),
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn
--- a/chrome/android/BUILD.gn
+++ b/chrome/android/BUILD.gn
@@ -461,6 +461,7 @@ if (current_toolchain == default_toolchain) {
       "//chrome/browser/ui/android/layouts:java",
       "//chrome/browser/ui/android/layouts/glue:java",
       "//chrome/browser/ui/android/layouts/third_party/float_property:java",
+    "//components/android_autofill/browser:java",
       "//chrome/browser/ui/android/logo:java",
       "//chrome/browser/ui/android/management:java",
       "//chrome/browser/ui/android/multiwindow:java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/settings/PasswordSettings.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/settings/PasswordSettings.java
--- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/settings/PasswordSettings.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/settings/PasswordSettings.java
@@ -55,13 +55,18 @@ import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.util.Locale;
 
+import org.chromium.chrome.browser.ui.messages.snackbar.SnackbarManager;
+import org.chromium.chrome.browser.ui.messages.snackbar.INeedSnackbarManager;
+import org.chromium.chrome.browser.ui.messages.snackbar.Snackbar;
+import org.chromium.chrome.browser.ApplicationLifetime;
+
 /**
  * The "Passwords" screen in Settings, which allows the user to enable or disable password saving,
  * to view saved passwords (just the username and URL), and to delete saved passwords.
  */
 public class PasswordSettings extends PreferenceFragmentCompat
         implements PasswordManagerHandler.PasswordListObserver,
-                   Preference.OnPreferenceClickListener {
+                   Preference.OnPreferenceClickListener, INeedSnackbarManager {
     @IntDef({TrustedVaultBannerState.NOT_SHOWN, TrustedVaultBannerState.OFFER_OPT_IN,
             TrustedVaultBannerState.OPTED_IN})
     @Retention(RetentionPolicy.SOURCE)
@@ -90,6 +95,12 @@ public class PasswordSettings extends PreferenceFragmentCompat
     public static final String PASSWORD_EXPORT_EVENT_HISTOGRAM =
             "PasswordManager.PasswordExport.Event";
 
+    public static final String PREF_ANDROID_AUTOFILL_SWITCH = "android_autofill_switch";
+    public static final String PREF_ANDROID_AUTOFILL_INCOGNITO_SWITCH = "android_autofill_incognito_switch";
+
+    private SnackbarManager mSnackbarManager;
+    private Snackbar mSnackbar;
+
     private static final String PREF_KEY_CATEGORY_SAVED_PASSWORDS = "saved_passwords";
     private static final String PREF_KEY_CATEGORY_EXCEPTIONS = "exceptions";
     private static final String PREF_KEY_SAVED_PASSWORDS_NO_TEXT = "saved_passwords_no_text";
@@ -120,6 +131,8 @@ public class PasswordSettings extends PreferenceFragmentCompat
     private Preference mLinkPref;
     private Menu mMenu;
 
+    private ChromeSwitchPreference mEnableAndroidAutofillSwitch;
+    private ChromeSwitchPreference mEnableAndroidAutofillIncognitoSwitch;
     private @ManagePasswordsReferrer int mManagePasswordsReferrer;
 
     /**
@@ -284,6 +297,7 @@ public class PasswordSettings extends PreferenceFragmentCompat
         }
 
         createSavePasswordsSwitch();
+        createEnableAndroidAutofillSwitch();
         createAutoSignInCheckbox();
 
         if (mTrustedVaultBannerState == TrustedVaultBannerState.OPTED_IN) {
@@ -518,6 +532,71 @@ public class PasswordSettings extends PreferenceFragmentCompat
                 getPrefService().getBoolean(Pref.CREDENTIALS_ENABLE_SERVICE));
     }
 
+    private void createEnableAndroidAutofillSwitch() {
+        if (mSnackbar == null) {
+            mSnackbar = Snackbar.make(getActivity().getString(R.string.ui_relaunch_notice),
+                    new SnackbarManager.SnackbarController() {
+                            @Override
+                            public void onDismissNoAction(Object actionData) { }
+
+                            @Override
+                            public void onAction(Object actionData) {
+                                ApplicationLifetime.terminate(true);
+                            }
+                    }, Snackbar.TYPE_NOTIFICATION, Snackbar.UMA_UNKNOWN)
+                    .setSingleLine(false)
+                    .setAction(getActivity().getString(R.string.relaunch),
+                            /*actionData*/null)
+                    .setDuration(/*durationMs*/70000);
+        }
+
+        mEnableAndroidAutofillSwitch = new ChromeSwitchPreference(getStyledContext(), null);
+        mEnableAndroidAutofillSwitch.setKey(PREF_ANDROID_AUTOFILL_SWITCH);
+        mEnableAndroidAutofillSwitch.setTitle(R.string.enable_android_autofill);
+        mEnableAndroidAutofillSwitch.setOrder(ORDER_SWITCH);
+        mEnableAndroidAutofillSwitch.setSummaryOn(R.string.text_on);
+        mEnableAndroidAutofillSwitch.setSummaryOff(R.string.text_off);
+
+        try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
+            getPreferenceScreen().addPreference(mEnableAndroidAutofillSwitch);
+        }
+
+        mEnableAndroidAutofillSwitch.setChecked(
+                getPrefService().getBoolean(Pref.AUTOFILL_ANDROID_ENABLED));
+
+        mEnableAndroidAutofillSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
+            getPrefService().setBoolean(Pref.AUTOFILL_ANDROID_ENABLED, (boolean) newValue);
+            if (!mSnackbarManager.isShowing())
+                mSnackbarManager.showSnackbar(mSnackbar);
+            return true;
+        });
+
+        mEnableAndroidAutofillIncognitoSwitch = new ChromeSwitchPreference(getStyledContext(), null);
+        mEnableAndroidAutofillIncognitoSwitch.setKey(PREF_ANDROID_AUTOFILL_INCOGNITO_SWITCH);
+        mEnableAndroidAutofillIncognitoSwitch.setTitle(R.string.enable_android_autofill_incognito);
+        mEnableAndroidAutofillIncognitoSwitch.setOrder(ORDER_SWITCH);
+        mEnableAndroidAutofillIncognitoSwitch.setSummaryOn(R.string.text_on);
+        mEnableAndroidAutofillIncognitoSwitch.setSummaryOff(R.string.text_off);
+
+        try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) {
+            getPreferenceScreen().addPreference(mEnableAndroidAutofillIncognitoSwitch);
+        }
+
+        mEnableAndroidAutofillIncognitoSwitch.setChecked(
+                getPrefService().getBoolean(Pref.AUTOFILL_ANDROID_INCOGNITO_ENABLED));
+
+        mEnableAndroidAutofillIncognitoSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
+            getPrefService().setBoolean(Pref.AUTOFILL_ANDROID_INCOGNITO_ENABLED, (boolean) newValue);
+            if (!mSnackbarManager.isShowing())
+                mSnackbarManager.showSnackbar(mSnackbar);
+            return true;
+        });
+    }
+
+    public void setSnackbarManager(SnackbarManager manager) {
+        mSnackbarManager = manager;
+    }
+
     private void createAutoSignInCheckbox() {
         ChromeSwitchPreference autoSignInSwitch =
                 new ChromeSwitchPreference(getStyledContext(), null);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java
--- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabImpl.java
@@ -74,6 +74,17 @@ import org.chromium.ui.base.WindowAndroid;
 import org.chromium.ui.util.ColorUtils;
 import org.chromium.url.GURL;
 
+import android.os.Build;
+import android.util.SparseArray;
+import org.chromium.ui.base.EventOffsetHandler;
+import android.view.ViewStructure;
+import android.view.autofill.AutofillValue;
+import org.chromium.components.autofill.AutofillProvider;
+import org.chromium.components.autofill.AutofillActionModeCallback;
+import org.chromium.content_public.browser.SelectionPopupController;
+import org.chromium.chrome.browser.preferences.Pref;
+import org.chromium.components.user_prefs.UserPrefs;
+
 /**
  * Implementation of the interface {@link Tab}. Contains and manages a {@link ContentView}.
  * This class is not intended to be extended.
@@ -211,6 +222,8 @@ public class TabImpl implements Tab, TabObscuringHandler.Observer {
     private int mThemeColor;
     private boolean mUsedCriticalPersistedTabData;
 
+    AutofillProvider mAutofillProvider;
+
     /**
      * Creates an instance of a {@link TabImpl}.
      *
@@ -775,6 +788,11 @@ public class TabImpl implements Tab, TabObscuringHandler.Observer {
         for (TabObserver observer : mObservers) observer.onDestroyed(this);
         mObservers.clear();
 
+        if (mAutofillProvider != null) {
+            mAutofillProvider.destroy();
+            mAutofillProvider = null;
+        }
+
         mUserDataHost.destroy();
         mTabViewManager.destroy();
         hideNativePage(false, null);
@@ -1356,6 +1374,16 @@ public class TabImpl implements Tab, TabObscuringHandler.Observer {
         return tabsPtrArray;
     }
 
+    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
+        if (mAutofillProvider != null)
+            mAutofillProvider.onProvideAutoFillVirtualStructure(structure, flags);
+    }
+
+    public void autofill(final SparseArray<AutofillValue> values) {
+        if (mAutofillProvider != null)
+            mAutofillProvider.autofill(values);
+    }
+
     /**
      * Initializes the {@link WebContents}. Completes the browser content components initialization
      * around a native WebContents pointer.
@@ -1405,6 +1433,27 @@ public class TabImpl implements Tab, TabObscuringHandler.Observer {
                             mDelegateFactory.createContextMenuPopulatorFactory(this), this));
 
             mWebContents.notifyRendererPreferenceUpdate();
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+                boolean autofillEnabled = false;
+                if (isIncognito()) {
+                    autofillEnabled = UserPrefs.get(Profile.getLastUsedRegularProfile())
+                                               .getBoolean(Pref.AUTOFILL_ANDROID_INCOGNITO_ENABLED);
+                } else {
+                    autofillEnabled = UserPrefs.get(Profile.getLastUsedRegularProfile())
+                                               .getBoolean(Pref.AUTOFILL_ANDROID_ENABLED);
+                }
+
+                if (autofillEnabled) {
+                    SelectionPopupController selectionController =
+                            SelectionPopupController.fromWebContents(mWebContents);
+                    mAutofillProvider = new AutofillProvider(getContext(), cv, webContents, "bromite");
+                    TabImplJni.get().initializeAutofillIfNecessary(mNativeTabAndroid);
+                    mAutofillProvider.setWebContents(webContents);
+                    cv.setWebContents(webContents);
+                    selectionController.setNonSelectionActionModeCallback(
+                            new AutofillActionModeCallback(mThemedApplicationContext, mAutofillProvider));
+                }
+            }
             TabHelpers.initWebContentsHelpers(this);
             notifyContentChanged();
         } finally {
@@ -1742,6 +1791,7 @@ public class TabImpl implements Tab, TabObscuringHandler.Observer {
         void setActiveNavigationEntryTitleForUrl(long nativeTabAndroid, String url, String title);
         void loadOriginalImage(long nativeTabAndroid);
         boolean handleNonNavigationAboutURL(GURL url);
+        void initializeAutofillIfNecessary(long nativeTabAndroid);
         void onShow(long nativeTabAndroid);
     }
 }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabViewAndroidDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabViewAndroidDelegate.java
--- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabViewAndroidDelegate.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabViewAndroidDelegate.java
@@ -32,6 +32,10 @@ import org.chromium.ui.dragdrop.DragStateTracker;
 import org.chromium.ui.dragdrop.DropDataProviderImpl;
 import org.chromium.ui.dragdrop.DropDataProviderUtils;
 
+import android.util.SparseArray;
+import android.view.autofill.AutofillValue;
+import android.view.ViewStructure;
+
 /**
  * Implementation of the abstract class {@link ViewAndroidDelegate} for Chrome.
  */
@@ -216,4 +220,14 @@ public class TabViewAndroidDelegate extends ViewAndroidDelegate {
             return intent;
         }
     }
+
+    @Override
+    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
+        mTab.onProvideAutofillVirtualStructure(structure, flags);
+    }
+
+    @Override
+    public void autofill(final SparseArray<AutofillValue> values) {
+        mTab.autofill(values);
+    }
 }
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn
--- a/chrome/browser/BUILD.gn
+++ b/chrome/browser/BUILD.gn
@@ -2494,6 +2494,13 @@ static_library("browser") {
     deps += [ "//chrome/browser/error_reporting" ]
   }
 
+  if (is_android) {
+    deps += [
+        "//components/android_autofill/browser",
+        "//components/android_autofill/browser:android"
+    ]
+  }
+
   if (use_ozone) {
     deps += [
       "//ui/events/ozone",
diff --git a/chrome/browser/android/tab_android.cc b/chrome/browser/android/tab_android.cc
--- a/chrome/browser/android/tab_android.cc
+++ b/chrome/browser/android/tab_android.cc
@@ -70,6 +70,13 @@
 #include "url/android/gurl_android.h"
 #include "url/gurl.h"
 
+#include "components/android_autofill/browser/android_autofill_manager.h"
+#include "components/android_autofill/browser/autofill_provider.h"
+#include "components/android_autofill/browser/autofill_provider_android.h"
+#include "components/autofill/content/browser/content_autofill_driver_factory.h"
+#include "chrome/browser/ui/autofill/chrome_autofill_client.h"
+#include "chrome/browser/browser_process.h"
+
 using base::android::AttachCurrentThread;
 using base::android::ConvertUTF8ToJavaString;
 using base::android::JavaParamRef;
@@ -505,3 +512,19 @@ static void JNI_TabImpl_Init(JNIEnv* env, const JavaParamRef<jobject>& obj) {
   // This will automatically bind to the Java object and pass ownership there.
   new TabAndroid(env, obj);
 }
+
+void TabAndroid::InitializeAutofillIfNecessary(JNIEnv* env) {
+  if (!autofill::ContentAutofillDriverFactory::FromWebContents(
+          web_contents_.get())) {
+     content::WebContents* web_contents = web_contents_.get();
+    autofill::ChromeAutofillClient::CreateForWebContents(web_contents);
+    autofill::ContentAutofillDriverFactory::CreateForWebContentsAndDelegate(
+        web_contents,
+        autofill::ChromeAutofillClient::FromWebContents(web_contents),
+        base::BindRepeating(
+            &autofill::BrowserDriverInitHook,
+            autofill::ChromeAutofillClient::FromWebContents(web_contents),
+            g_browser_process->GetApplicationLocale(),
+            /*enable_secondary_autofill_manager*/ true));
+  }
+}
diff --git a/chrome/browser/android/tab_android.h b/chrome/browser/android/tab_android.h
--- a/chrome/browser/android/tab_android.h
+++ b/chrome/browser/android/tab_android.h
@@ -162,6 +162,8 @@ class TabAndroid : public base::SupportsUserData {
 
   void SetDevToolsAgentHost(scoped_refptr<content::DevToolsAgentHost> host);
 
+  void InitializeAutofillIfNecessary(JNIEnv* env);
+
  private:
   JavaObjectWeakGlobalRef weak_java_tab_;
 
diff --git a/chrome/browser/android/tab_web_contents_delegate_android.cc b/chrome/browser/android/tab_web_contents_delegate_android.cc
--- a/chrome/browser/android/tab_web_contents_delegate_android.cc
+++ b/chrome/browser/android/tab_web_contents_delegate_android.cc
@@ -168,7 +168,8 @@ void TabWebContentsDelegateAndroid::PortalWebContentsCreated(
       base::BindRepeating(
           &autofill::BrowserDriverInitHook,
           autofill::ChromeAutofillClient::FromWebContents(portal_contents),
-          g_browser_process->GetApplicationLocale()));
+          g_browser_process->GetApplicationLocale(),
+          /*enable_secondary_autofill_manager*/ true));
   ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient(
       portal_contents,
       autofill::ChromeAutofillClient::FromWebContents(portal_contents));
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd
--- a/chrome/browser/ui/android/strings/android_chrome_strings.grd
+++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -601,6 +601,12 @@ CHAR_LIMIT guidelines:
       <message name="IDS_PASSWORD_SETTINGS_SAVE_PASSWORDS" desc="Title for the checkbox toggling whether passwords are saved or not. [CHAR_LIMIT=32]">
         Save passwords
       </message>
+      <message name="IDS_ENABLE_ANDROID_AUTOFILL" desc="Title for the checkbox toggling whether enable Android native autofill or not. [CHAR_LIMIT=32]">
+        Enable native Android autofill
+      </message>
+      <message name="IDS_ENABLE_ANDROID_AUTOFILL_INCOGNITO" desc="Title for the checkbox toggling whether enable Android native autofill or not in incognito mode. [CHAR_LIMIT=32]">
+        Enable native Android autofill in incognito
+      </message>
       <message name="IDS_PASSWORDS_AUTO_SIGNIN_TITLE" desc="Title for checkbox to enable automatically signing the user in to websites">
         Auto Sign-in
       </message>
diff --git a/chrome/browser/ui/tab_helpers.cc b/chrome/browser/ui/tab_helpers.cc
--- a/chrome/browser/ui/tab_helpers.cc
+++ b/chrome/browser/ui/tab_helpers.cc
@@ -168,6 +168,9 @@
 #include "chrome/browser/ui/javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_android.h"
 #include "chrome/browser/video_tutorials/video_tutorial_tab_helper.h"
 #include "content/public/common/content_features.h"
+#include "components/android_autofill/browser/android_autofill_manager.h"
+#include "components/android_autofill/browser/autofill_provider.h"
+#include "components/android_autofill/browser/autofill_provider_android.h"
 #else
 #include "chrome/browser/accuracy_tips/accuracy_service_factory.h"
 #include "chrome/browser/banners/app_banner_manager_desktop.h"
@@ -330,7 +333,8 @@ void TabHelpers::AttachTabHelpers(WebContents* web_contents) {
       base::BindRepeating(
           &autofill::BrowserDriverInitHook,
           autofill::ChromeAutofillClient::FromWebContents(web_contents),
-          g_browser_process->GetApplicationLocale()));
+          g_browser_process->GetApplicationLocale(),
+          /*enable_secondary_autofill_manager*/true));
   if (breadcrumbs::IsEnabled())
     BreadcrumbManagerTabHelper::CreateForWebContents(web_contents);
   chrome_browser_net::NetErrorTabHelper::CreateForWebContents(web_contents);
diff --git a/components/android_autofill/browser/android_autofill_manager.cc b/components/android_autofill/browser/android_autofill_manager.cc
--- a/components/android_autofill/browser/android_autofill_manager.cc
+++ b/components/android_autofill/browser/android_autofill_manager.cc
@@ -19,7 +19,7 @@ void AndroidDriverInitHook(
     AutofillManager::EnableDownloadManager enable_download_manager,
     ContentAutofillDriver* driver) {
   driver->set_autofill_manager(base::WrapUnique(
-      new AndroidAutofillManager(driver, client, enable_download_manager)));
+      new AndroidAutofillManager(driver, client, enable_download_manager)), nullptr);
   driver->GetAutofillAgent()->SetUserGestureRequired(false);
   driver->GetAutofillAgent()->SetSecureContextRequired(true);
   driver->GetAutofillAgent()->SetFocusRequiresScroll(false);
diff --git a/components/android_autofill/browser/android_autofill_manager.h b/components/android_autofill/browser/android_autofill_manager.h
--- a/components/android_autofill/browser/android_autofill_manager.h
+++ b/components/android_autofill/browser/android_autofill_manager.h
@@ -82,17 +82,17 @@ class AndroidAutofillManager : public AutofillManager {
   void SetCreditCardFillViaAutofillAssistantIntent(
       const autofill_assistant::AutofillAssistantIntent intent) override;
 
+  AndroidAutofillManager(
+      AutofillDriver* driver,
+      AutofillClient* client,
+      AutofillManager::EnableDownloadManager enable_download_manager);
+
  protected:
   friend void AndroidDriverInitHook(
       AutofillClient* client,
       AutofillManager::EnableDownloadManager enable_download_manager,
       ContentAutofillDriver* driver);
 
-  AndroidAutofillManager(
-      AutofillDriver* driver,
-      AutofillClient* client,
-      AutofillManager::EnableDownloadManager enable_download_manager);
-
   void OnFormSubmittedImpl(const FormData& form,
                            bool known_success,
                            mojom::SubmissionSource source) override;
diff --git a/components/autofill/content/browser/content_autofill_driver.cc b/components/autofill/content/browser/content_autofill_driver.cc
--- a/components/autofill/content/browser/content_autofill_driver.cc
+++ b/components/autofill/content/browser/content_autofill_driver.cc
@@ -317,6 +317,8 @@ void ContentAutofillDriver::FormsSeen(
          const std::vector<FormData>& updated_forms,
          const std::vector<FormGlobalId>& removed_forms) {
         target->autofill_manager_->OnFormsSeen(updated_forms, removed_forms);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnFormsSeen(updated_forms, removed_forms);
       });
 }
 
@@ -343,6 +345,8 @@ void ContentAutofillDriver::FormSubmitted(
         }
         target->autofill_manager_->OnFormSubmitted(form, known_success,
                                                    submission_source);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnFormSubmitted(form, known_success, submission_source);
       });
 }
 
@@ -363,6 +367,8 @@ void ContentAutofillDriver::TextFieldDidChange(const FormData& raw_form,
          base::TimeTicks timestamp) {
         target->autofill_manager_->OnTextFieldDidChange(
             form, field, bounding_box, timestamp);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnTextFieldDidChange(form, field, bounding_box, timestamp);
       });
 }
 
@@ -381,6 +387,8 @@ void ContentAutofillDriver::TextFieldDidScroll(const FormData& raw_form,
          const FormFieldData& field, const gfx::RectF& bounding_box) {
         target->autofill_manager_->OnTextFieldDidScroll(form, field,
                                                         bounding_box);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnTextFieldDidScroll(form, field, bounding_box);
       });
 }
 
@@ -400,6 +408,8 @@ void ContentAutofillDriver::SelectControlDidChange(
          const FormFieldData& field, const gfx::RectF& bounding_box) {
         target->autofill_manager_->OnSelectControlDidChange(form, field,
                                                             bounding_box);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnSelectControlDidChange(form, field, bounding_box);
       });
 }
 
@@ -426,6 +436,10 @@ void ContentAutofillDriver::AskForValuesToFill(
         target->autofill_manager_->OnAskForValuesToFill(
             form, field, bounding_box, query_id, autoselect_first_suggestion,
             form_element_was_clicked);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnAskForValuesToFill(form, field, bounding_box, query_id,
+                                                autoselect_first_suggestion,
+                                                form_element_was_clicked);
       });
 }
 
@@ -436,12 +450,16 @@ void ContentAutofillDriver::HidePopup() {
     DCHECK(!target->IsPrerendering())
         << "We should never affect UI while prerendering";
     target->autofill_manager_->OnHidePopup();
+    if (target->secondary_autofill_manager_)
+      target->secondary_autofill_manager_->OnHidePopup();
   });
 }
 
 void ContentAutofillDriver::FocusNoLongerOnFormCallback(
     bool had_interacted_form) {
   autofill_manager_->OnFocusNoLongerOnForm(had_interacted_form);
+  if (secondary_autofill_manager_)
+    secondary_autofill_manager_->OnFocusNoLongerOnForm(had_interacted_form);
 }
 
 void ContentAutofillDriver::FocusNoLongerOnForm(bool had_interacted_form) {
@@ -469,6 +487,8 @@ void ContentAutofillDriver::FocusOnFormField(const FormData& raw_form,
          const FormFieldData& field, const gfx::RectF& bounding_box) {
         target->autofill_manager_->OnFocusOnFormField(form, field,
                                                       bounding_box);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnFocusOnFormField(form, field, bounding_box);
       });
 }
 
@@ -481,6 +501,8 @@ void ContentAutofillDriver::DidFillAutofillFormData(const FormData& raw_form,
       [](ContentAutofillDriver* target, const FormData& form,
          base::TimeTicks timestamp) {
         target->autofill_manager_->OnDidFillAutofillFormData(form, timestamp);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnDidFillAutofillFormData(form, timestamp);
       });
 }
 
@@ -490,6 +512,8 @@ void ContentAutofillDriver::DidPreviewAutofillFormData() {
   autofill_router().DidPreviewAutofillFormData(
       this, [](ContentAutofillDriver* target) {
         target->autofill_manager_->OnDidPreviewAutofillFormData();
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnDidPreviewAutofillFormData();
       });
 }
 
@@ -499,6 +523,8 @@ void ContentAutofillDriver::DidEndTextFieldEditing() {
   autofill_router().DidEndTextFieldEditing(
       this, [](ContentAutofillDriver* target) {
         target->autofill_manager_->OnDidEndTextFieldEditing();
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnDidEndTextFieldEditing();
       });
 }
 
@@ -510,6 +536,8 @@ void ContentAutofillDriver::SelectFieldOptionsDidChange(
       this, GetFormWithFrameAndFormMetaData(raw_form),
       [](ContentAutofillDriver* target, const FormData& form) {
         target->autofill_manager_->OnSelectFieldOptionsDidChange(form);
+        if (target->secondary_autofill_manager_)
+          target->secondary_autofill_manager_->OnSelectFieldOptionsDidChange(form);
       });
 }
 
@@ -597,6 +625,8 @@ void ContentAutofillDriver::DidNavigateFrame(
   if (autofill_router_)  // Can be nullptr only in tests.
     autofill_router_->UnregisterDriver(this);
   autofill_manager_->Reset();
+  if (secondary_autofill_manager_)
+    secondary_autofill_manager_->Reset();
 }
 
 const mojo::AssociatedRemote<mojom::AutofillAgent>&
diff --git a/components/autofill/content/browser/content_autofill_driver.h b/components/autofill/content/browser/content_autofill_driver.h
--- a/components/autofill/content/browser/content_autofill_driver.h
+++ b/components/autofill/content/browser/content_autofill_driver.h
@@ -132,10 +132,13 @@ class ContentAutofillDriver : public AutofillDriver,
   ContentAutofillDriver& operator=(const ContentAutofillDriver&) = delete;
   ~ContentAutofillDriver() override;
 
-  void set_autofill_manager(std::unique_ptr<AutofillManager> autofill_manager) {
+  void set_autofill_manager(std::unique_ptr<AutofillManager> autofill_manager,
+      std::unique_ptr<AutofillManager> secondary_autofill_manager) {
     autofill_manager_ = std::move(autofill_manager);
+    secondary_autofill_manager_ = std::move(secondary_autofill_manager);
   }
   AutofillManager* autofill_manager() { return autofill_manager_.get(); }
+  AutofillManager* secondary_autofill_manager() { return secondary_autofill_manager_.get(); }
 
   content::RenderFrameHost* render_frame_host() { return render_frame_host_; }
 
@@ -364,6 +367,10 @@ class ContentAutofillDriver : public AutofillDriver,
   // code.
   std::unique_ptr<AutofillManager> autofill_manager_ = nullptr;
 
+  // adds a reference for AndroidAutofillManager, since native autofill works in
+  // conjunction with browser autofill in Bromite
+  std::unique_ptr<AutofillManager> secondary_autofill_manager_ = nullptr;
+
   content::RenderWidgetHost::KeyPressEventCallback key_press_handler_;
 
   mojo::AssociatedReceiver<mojom::AutofillDriver> receiver_{this};
diff --git a/components/autofill/content/browser/content_autofill_driver_factory.cc b/components/autofill/content/browser/content_autofill_driver_factory.cc
--- a/components/autofill/content/browser/content_autofill_driver_factory.cc
+++ b/components/autofill/content/browser/content_autofill_driver_factory.cc
@@ -13,6 +13,7 @@
 #include "components/autofill/content/browser/content_autofill_driver.h"
 #include "components/autofill/core/browser/browser_autofill_manager.h"
 #include "components/autofill/core/common/autofill_features.h"
+#include "components/android_autofill/browser/android_autofill_manager.h"
 #include "content/public/browser/global_routing_id.h"
 #include "content/public/browser/navigation_handle.h"
 #include "content/public/browser/render_frame_host.h"
@@ -41,10 +42,14 @@ bool ShouldEnableHeavyFormDataScraping(const version_info::Channel channel) {
 
 void BrowserDriverInitHook(AutofillClient* client,
                            const std::string& app_locale,
+                           bool enable_secondary_autofill_manager,
                            ContentAutofillDriver* driver) {
   driver->set_autofill_manager(std::make_unique<BrowserAutofillManager>(
       driver, client, app_locale,
-      AutofillManager::EnableDownloadManager(true)));
+      AutofillManager::EnableDownloadManager(false)),
+    enable_secondary_autofill_manager == false ? nullptr :
+      base::WrapUnique(new AndroidAutofillManager(driver, client,
+          AutofillManager::EnableDownloadManager(false))));
   if (client && ShouldEnableHeavyFormDataScraping(client->GetChannel()))
     driver->GetAutofillAgent()->EnableHeavyFormDataScraping();
 }
diff --git a/components/autofill/content/browser/content_autofill_driver_factory.h b/components/autofill/content/browser/content_autofill_driver_factory.h
--- a/components/autofill/content/browser/content_autofill_driver_factory.h
+++ b/components/autofill/content/browser/content_autofill_driver_factory.h
@@ -34,6 +34,7 @@ class ContentAutofillDriver;
 // other implementations.
 void BrowserDriverInitHook(AutofillClient* client,
                            const std::string& app_locale,
+                           bool enable_secondary_autofill_manager,
                            ContentAutofillDriver* driver);
 
 // Manages lifetime of ContentAutofillDriver. One Factory per WebContents
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc
--- a/components/autofill/content/renderer/password_autofill_agent.cc
+++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -799,7 +799,10 @@ void PasswordAutofillAgent::UpdateStateForTextChange(
 
 void PasswordAutofillAgent::TrackAutofilledElement(
     const blink::WebFormControlElement& element) {
-  autofill_agent_->TrackAutofilledElement(element);
+  // fix for https://github.com/bromite/bromite/issues/1570
+  AutofillAgent* agent = autofill_agent_.get();
+  if (agent)
+    agent->TrackAutofilledElement(element);
 }
 
 bool PasswordAutofillAgent::FillSuggestion(
diff --git a/components/autofill/core/common/autofill_prefs.cc b/components/autofill/core/common/autofill_prefs.cc
--- a/components/autofill/core/common/autofill_prefs.cc
+++ b/components/autofill/core/common/autofill_prefs.cc
@@ -109,6 +109,10 @@ const char kAutofillWalletImportStorageCheckboxState[] =
 const char kAutocompleteLastVersionRetentionPolicy[] =
     "autocomplete.retention_policy_last_version";
 
+// Boolean that is true to enable native Android Autofill
+const char kAutofillAndroidEnabled[] = "autofill.android_autofill_enabled";
+const char kAutofillAndroidIncognitoEnabled[] = "autofill.android_autofill_incognito_enabled";
+
 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
   // Synced prefs. Used for cross-device choices, e.g., credit card Autofill.
   registry->RegisterBooleanPref(
@@ -135,6 +139,10 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
   registry->RegisterBooleanPref(
       prefs::kAutofillCreditCardFidoAuthOfferCheckboxState, true);
 #endif
+  registry->RegisterBooleanPref(
+      prefs::kAutofillAndroidEnabled, true);
+  registry->RegisterBooleanPref(
+      prefs::kAutofillAndroidIncognitoEnabled, false);
   registry->RegisterIntegerPref(
       prefs::kAutofillCreditCardSigninPromoImpressionCount, 0);
   registry->RegisterBooleanPref(prefs::kAutofillWalletImportEnabled, true);
diff --git a/components/autofill/core/common/autofill_prefs.h b/components/autofill/core/common/autofill_prefs.h
--- a/components/autofill/core/common/autofill_prefs.h
+++ b/components/autofill/core/common/autofill_prefs.h
@@ -46,6 +46,8 @@ extern const char kAutofillUploadEventsLastResetTimestamp[];
 extern const char kAutofillWalletImportEnabled[];
 extern const char kAutofillWalletImportStorageCheckboxState[];
 extern const char kAutocompleteLastVersionRetentionPolicy[];
+extern const char kAutofillAndroidEnabled[];
+extern const char kAutofillAndroidIncognitoEnabled[];
 
 namespace sync_transport_opt_in {
 enum Flags {
diff --git a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java
--- a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java
+++ b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/view/ContentView.java
@@ -37,6 +37,11 @@ import org.chromium.content_public.browser.WebContentsAccessibility;
 import org.chromium.ui.base.EventForwarder;
 import org.chromium.ui.base.EventOffsetHandler;
 
+import org.chromium.base.Log;
+import android.util.SparseArray;
+import android.view.autofill.AutofillValue;
+import org.chromium.ui.base.ViewAndroidDelegate;
+
 /**
  * The containing view for {@link WebContents} that exists in the Android UI hierarchy and exposes
  * the various {@link View} functionality to it.
@@ -84,6 +89,8 @@ public class ContentView extends FrameLayout
      */
     public static ContentView createContentView(Context context,
             @Nullable EventOffsetHandler eventOffsetHandler, @Nullable WebContents webContents) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
+            return new ContentViewWithAutofill(context, eventOffsetHandler, webContents);
         return new ContentView(context, eventOffsetHandler, webContents);
     }
 
@@ -573,4 +580,43 @@ public class ContentView extends FrameLayout
     private boolean webContentsAttached() {
         return hasValidWebContents() && mWebContents.getTopLevelNativeWindow() != null;
     }
+
+    /**
+    * API level 26 implementation that includes autofill.
+    */
+    public static class ContentViewWithAutofill extends ContentView {
+        private ViewAndroidDelegate viewAndroidDelegate;
+
+        private ContentViewWithAutofill(Context context, EventOffsetHandler eventOffsetHandler, WebContents webContents) {
+            super(context, eventOffsetHandler, webContents);
+
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+                // The Autofill system-level infrastructure has heuristics for which Views it considers
+                // important for autofill; only these Views will be queried for their autofill
+                // structure on notifications that a new (virtual) View was entered. By default,
+                // FrameLayout is not considered important for autofill. Thus, for ContentView to be
+                // queried for its autofill structure, we must explicitly inform the autofill system
+                // that this View is important for autofill.
+                setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_YES);
+            }
+        }
+
+        @Override
+        public void setWebContents(WebContents webContents) {
+            viewAndroidDelegate = webContents.getViewAndroidDelegate();
+            super.setWebContents(webContents);
+        }
+
+        @Override
+        public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
+            if (viewAndroidDelegate != null)
+                viewAndroidDelegate.onProvideAutofillVirtualStructure(structure, flags);
+        }
+
+        @Override
+        public void autofill(final SparseArray<AutofillValue> values) {
+            if (viewAndroidDelegate != null)
+                viewAndroidDelegate.autofill(values);
+        }
+    }
 }
diff --git a/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java b/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java
--- a/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java
+++ b/ui/android/java/src/org/chromium/ui/base/ViewAndroidDelegate.java
@@ -32,6 +32,10 @@ import org.chromium.ui.dragdrop.DragStateTracker;
 import org.chromium.ui.dragdrop.DropDataAndroid;
 import org.chromium.ui.mojom.CursorType;
 
+import android.util.SparseArray;
+import android.view.autofill.AutofillValue;
+import android.view.ViewStructure;
+
 /**
  * Class to acquire, position, and remove anchor views from the implementing View.
  */
@@ -597,4 +601,8 @@ public class ViewAndroidDelegate {
     public static void setDragAndDropDelegateForTest(DragAndDropDelegate testDelegate) {
         sDragAndDropTestDelegate = testDelegate;
     }
+
+    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {}
+
+    public void autofill(final SparseArray<AutofillValue> values) {}
 }
--
2.25.1
