/**
   * Marks a given flow as completed.
   *
   * @param activity An activity.
   * @param data Resulting FRE properties bundle.
   */
  public static void markFlowAsCompleted(Activity activity, Bundle data) {
    // When the user accepts ToS in the Setup Wizard (see ToSAckedReceiver), we do not
    // show the ToS page to the user because the user has already accepted one outside FRE.
    if (!PrefServiceBridge.getInstance().isFirstRunEulaAccepted()) {
      PrefServiceBridge.getInstance().setEulaAccepted();
    }

    // Mark the FRE flow as complete and set the sign-in flow preferences if necessary.
    FirstRunSignInProcessor.finalizeFirstRunFlowState(activity, data);
  }
 protected final void clearBrowsingData(EnumSet<DialogOption> selectedOptions) {
   PrefServiceBridge.getInstance()
       .clearBrowsingData(
           this,
           selectedOptions.contains(DialogOption.CLEAR_HISTORY),
           selectedOptions.contains(DialogOption.CLEAR_CACHE),
           selectedOptions.contains(DialogOption.CLEAR_COOKIES_AND_SITE_DATA),
           selectedOptions.contains(DialogOption.CLEAR_PASSWORDS),
           selectedOptions.contains(DialogOption.CLEAR_FORM_DATA));
 }
  /** Updates the summaries for several preferences. */
  public void updateSummaries() {
    PrefServiceBridge prefServiceBridge = PrefServiceBridge.getInstance();

    CheckBoxPreference navigationErrorPref =
        (CheckBoxPreference) findPreference(PREF_NAVIGATION_ERROR);
    navigationErrorPref.setChecked(prefServiceBridge.isResolveNavigationErrorEnabled());

    CheckBoxPreference searchSuggestionsPref =
        (CheckBoxPreference) findPreference(PREF_SEARCH_SUGGESTIONS);
    searchSuggestionsPref.setChecked(prefServiceBridge.isSearchSuggestEnabled());

    CheckBoxPreference extendedReportingPref =
        (CheckBoxPreference) findPreference(PREF_SAFE_BROWSING_EXTENDED_REPORTING);
    if (extendedReportingPref != null) {
      extendedReportingPref.setChecked(prefServiceBridge.isSafeBrowsingExtendedReportingEnabled());
    }

    CheckBoxPreference safeBrowsingPref = (CheckBoxPreference) findPreference(PREF_SAFE_BROWSING);
    if (safeBrowsingPref != null) {
      safeBrowsingPref.setChecked(prefServiceBridge.isSafeBrowsingEnabled());
    }

    Preference doNotTrackPref = findPreference(PREF_DO_NOT_TRACK);
    if (prefServiceBridge.isDoNotTrackEnabled()) {
      doNotTrackPref.setSummary(getActivity().getResources().getText(R.string.text_on));
    } else {
      doNotTrackPref.setSummary(getActivity().getResources().getText(R.string.text_off));
    }
    Preference contextualPref = findPreference(PREF_CONTEXTUAL_SEARCH);
    if (contextualPref != null) {
      if (prefServiceBridge.isContextualSearchDisabled()) {
        contextualPref.setSummary(getActivity().getResources().getText(R.string.text_off));
      } else {
        contextualPref.setSummary(getActivity().getResources().getText(R.string.text_on));
      }
    }
    PrivacyPreferencesManager privacyPrefManager =
        PrivacyPreferencesManager.getInstance(getActivity());
    if (privacyPrefManager.isCellularExperimentEnabled()) {
      Preference usageAndCrashPref = findPreference(PREF_USAGE_AND_CRASH_REPORTING);
      if (privacyPrefManager.isUsageAndCrashReportingEnabled()) {
        usageAndCrashPref.setSummary(getActivity().getResources().getText(R.string.text_on));
      } else {
        usageAndCrashPref.setSummary(getActivity().getResources().getText(R.string.text_off));
      }
    }
  }
  @Override
  public boolean onPreferenceChange(Preference preference, Object newValue) {
    // CrashDumpUploadPreference listens to its own PreferenceChanged to update its text.
    // We have replaced the listener. If we do run into a CrashDumpUploadPreference change,
    // we will call onPreferenceChange to change the displayed text.
    if (preference instanceof CrashDumpUploadPreference) {
      ((CrashDumpUploadPreference) preference).onPreferenceChange(preference, newValue);
    }

    // NetworkPredictionPreference listens to its own PreferenceChanged to update its text.
    // We have replaced the listener. If we do run into a NetworkPredictionPreference change,
    // we will call onPreferenceChange to change the displayed text.
    if (preference instanceof NetworkPredictionPreference) {
      ((NetworkPredictionPreference) preference).onPreferenceChange(preference, newValue);
    }

    String key = preference.getKey();
    if (PREF_SEARCH_SUGGESTIONS.equals(key)) {
      PrefServiceBridge.getInstance().setSearchSuggestEnabled((boolean) newValue);
    } else if (PREF_SAFE_BROWSING.equals(key)) {
      PrefServiceBridge.getInstance().setSafeBrowsingEnabled((boolean) newValue);
    } else if (PREF_SAFE_BROWSING_EXTENDED_REPORTING.equals(key)) {
      PrefServiceBridge.getInstance().setSafeBrowsingExtendedReportingEnabled((boolean) newValue);
    } else if (PREF_NETWORK_PREDICTIONS.equals(key)) {
      PrefServiceBridge.getInstance()
          .setNetworkPredictionOptions(NetworkPredictionOptions.stringToEnum((String) newValue));
      PrecacheLauncher.updatePrecachingEnabled(getActivity());
    } else if (PREF_NETWORK_PREDICTIONS_NO_CELLULAR.equals(key)) {
      PrefServiceBridge.getInstance()
          .setNetworkPredictionOptions(
              (boolean) newValue
                  ? NetworkPredictionOptions.NETWORK_PREDICTION_ALWAYS
                  : NetworkPredictionOptions.NETWORK_PREDICTION_NEVER);
      PrecacheLauncher.updatePrecachingEnabled(getActivity());
    } else if (PREF_NAVIGATION_ERROR.equals(key)) {
      PrefServiceBridge.getInstance().setResolveNavigationErrorEnabled((boolean) newValue);
    } else if (PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR.equals(key)) {
      PrefServiceBridge.getInstance().setCrashReporting((boolean) newValue);
    } else if (PREF_CRASH_DUMP_UPLOAD.equals(key)) {
      PrivacyPreferencesManager.getInstance(getActivity()).setUploadCrashDump((String) newValue);
    }

    return true;
  }
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    mCanDeleteBrowsingHistory = PrefServiceBridge.getInstance().canDeleteBrowsingHistory();

    DialogOption[] options = getDialogOptions();
    String[] optionNames = new String[options.length];
    Resources resources = getResources();
    for (int i = 0; i < options.length; i++) {
      optionNames[i] = resources.getString(options[i].getResourceId());
    }
    mSelectedOptions = getDefaultDialogOptionsSelections();
    mAdapter = new ClearBrowsingDataAdapter(options, optionNames, getDisabledDialogOptions());
    final AlertDialog.Builder builder =
        new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
            .setTitle(R.string.clear_browsing_data_title)
            .setPositiveButton(R.string.clear_data_delete, this)
            .setNegativeButton(R.string.cancel, this)
            .setAdapter(mAdapter, null); // OnClickListener is registered manually.

    if (ChromeSigninController.get(getActivity()).isSignedIn()) {
      final String message = getString(R.string.clear_cookies_no_sign_out_summary);
      final SpannableString messageWithLink =
          SpanApplier.applySpans(
              message,
              new SpanApplier.SpanInfo(
                  "<link>",
                  "</link>",
                  new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                      dismiss();
                      Preferences prefActivity = (Preferences) getActivity();
                      prefActivity.startFragment(AccountManagementFragment.class.getName(), null);
                    }

                    // Change link formatting to use no underline
                    @Override
                    public void updateDrawState(TextPaint textPaint) {
                      textPaint.setColor(textPaint.linkColor);
                      textPaint.setUnderlineText(false);
                    }
                  }));

      View view =
          getActivity().getLayoutInflater().inflate(R.layout.single_line_bottom_text_dialog, null);
      TextView summaryView = (TextView) view.findViewById(R.id.summary);
      summaryView.setText(messageWithLink);
      summaryView.setMovementMethod(LinkMovementMethod.getInstance());
      builder.setView(view);
    }

    mDialog = builder.create();
    mDialog
        .getListView()
        .setOnItemClickListener(
            new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // The present behaviour of AlertDialog is to dismiss after the onClick event.
                // Hence we are manually overriding this outside the builder.
                mAdapter.onClick(position);
              }
            });
    return mDialog;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PrivacyPreferencesManager privacyPrefManager =
        PrivacyPreferencesManager.getInstance(getActivity());
    privacyPrefManager.migrateNetworkPredictionPreferences();
    addPreferencesFromResource(R.xml.privacy_preferences);
    getActivity().setTitle(R.string.prefs_privacy);
    setHasOptionsMenu(true);

    mManagedPreferenceDelegate = createManagedPreferenceDelegate();

    NetworkPredictionPreference networkPredictionPref =
        (NetworkPredictionPreference) findPreference(PREF_NETWORK_PREDICTIONS);
    ChromeBaseCheckBoxPreference networkPredictionNoCellularPref =
        (ChromeBaseCheckBoxPreference) findPreference(PREF_NETWORK_PREDICTIONS_NO_CELLULAR);
    NetworkPredictionOptions networkPredictionOptions =
        PrefServiceBridge.getInstance().getNetworkPredictionOptions();

    PreferenceScreen preferenceScreen = getPreferenceScreen();
    boolean isMobileNetworkCapable = privacyPrefManager.isMobileNetworkCapable();
    if (isMobileNetworkCapable) {
      preferenceScreen.removePreference(networkPredictionNoCellularPref);
      networkPredictionPref.setValue(networkPredictionOptions.enumToString());
      networkPredictionPref.setOnPreferenceChangeListener(this);
      networkPredictionPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);
    } else {
      preferenceScreen.removePreference(networkPredictionPref);
      networkPredictionNoCellularPref.setChecked(
          networkPredictionOptions != NetworkPredictionOptions.NETWORK_PREDICTION_NEVER);
      networkPredictionNoCellularPref.setOnPreferenceChangeListener(this);
      networkPredictionNoCellularPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);
    }

    // Display the correct settings fragment according to the user experiment group and to type
    // of the device, by removing not applicable preference fragments.
    CrashDumpUploadPreference uploadCrashDumpPref =
        (CrashDumpUploadPreference) findPreference(PREF_CRASH_DUMP_UPLOAD);
    ChromeBaseCheckBoxPreference uploadCrashDumpNoCellularPref =
        (ChromeBaseCheckBoxPreference) findPreference(PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR);

    if (privacyPrefManager.isCellularExperimentEnabled()) {
      preferenceScreen.removePreference(uploadCrashDumpNoCellularPref);
      preferenceScreen.removePreference(uploadCrashDumpPref);
    } else {
      preferenceScreen.removePreference(findPreference(PREF_USAGE_AND_CRASH_REPORTING));
      if (isMobileNetworkCapable) {
        preferenceScreen.removePreference(uploadCrashDumpNoCellularPref);
        uploadCrashDumpPref.setOnPreferenceChangeListener(this);
        uploadCrashDumpPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);
      } else {
        preferenceScreen.removePreference(uploadCrashDumpPref);
        uploadCrashDumpNoCellularPref.setOnPreferenceChangeListener(this);
        uploadCrashDumpNoCellularPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);
      }
    }

    ChromeBaseCheckBoxPreference navigationErrorPref =
        (ChromeBaseCheckBoxPreference) findPreference(PREF_NAVIGATION_ERROR);
    navigationErrorPref.setOnPreferenceChangeListener(this);
    navigationErrorPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);

    ChromeBaseCheckBoxPreference searchSuggestionsPref =
        (ChromeBaseCheckBoxPreference) findPreference(PREF_SEARCH_SUGGESTIONS);
    searchSuggestionsPref.setOnPreferenceChangeListener(this);
    searchSuggestionsPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);

    if (!ContextualSearchFieldTrial.isEnabled()) {
      preferenceScreen.removePreference(findPreference(PREF_CONTEXTUAL_SEARCH));
    }

    ChromeBaseCheckBoxPreference safeBrowsingExtendedReportingPref =
        (ChromeBaseCheckBoxPreference) findPreference(PREF_SAFE_BROWSING_EXTENDED_REPORTING);
    safeBrowsingExtendedReportingPref.setOnPreferenceChangeListener(this);
    safeBrowsingExtendedReportingPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);

    ChromeBaseCheckBoxPreference safeBrowsingPref =
        (ChromeBaseCheckBoxPreference) findPreference(PREF_SAFE_BROWSING);
    safeBrowsingPref.setOnPreferenceChangeListener(this);
    safeBrowsingPref.setManagedPreferenceDelegate(mManagedPreferenceDelegate);

    if (!SafeBrowsingFieldTrial.isEnabled()) {
      preferenceScreen.removePreference(findPreference(PREF_SAFE_BROWSING_EXTENDED_REPORTING));
      preferenceScreen.removePreference(findPreference(PREF_SAFE_BROWSING));
    }

    ButtonPreference clearBrowsingData =
        (ButtonPreference) findPreference(PREF_CLEAR_BROWSING_DATA);
    clearBrowsingData.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          @Override
          public boolean onPreferenceClick(Preference preference) {
            showClearBrowsingDialog();
            return true;
          }
        });

    if (getArguments() != null) {
      boolean showClearBrowsingData =
          getArguments().getBoolean(SHOW_CLEAR_BROWSING_DATA_EXTRA, false);
      if (showClearBrowsingData) showClearBrowsingDialog();
    }
    updateSummaries();
  }
 @VisibleForTesting
 protected boolean isFirstRunEulaAccepted() {
   return PrefServiceBridge.getInstance().isFirstRunEulaAccepted();
 }
 @Override
 public boolean isIncognitoSupported() {
   return PrefServiceBridge.getInstance().isIncognitoModeEnabled();
 }