2 * Copyright © 2017-2019 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.app.Activity;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.res.Resources;
27 import android.database.Cursor;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.preference.PreferenceManager;
31 import android.view.Menu;
32 import android.view.MenuItem;
33 import android.view.View;
34 import android.view.ViewGroup;
35 import android.view.WindowManager;
36 import android.widget.CursorAdapter;
37 import android.widget.EditText;
38 import android.widget.ListView;
39 import android.widget.RadioButton;
40 import android.widget.Spinner;
41 import android.widget.Switch;
42 import android.widget.TextView;
44 import androidx.appcompat.app.ActionBar;
45 import androidx.appcompat.app.AppCompatActivity;
46 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
47 import androidx.core.app.NavUtils;
48 import androidx.fragment.app.DialogFragment;
49 import androidx.fragment.app.FragmentManager; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
51 import com.google.android.material.floatingactionbutton.FloatingActionButton;
52 import com.google.android.material.snackbar.Snackbar;
54 import com.stoutner.privacybrowser.R;
55 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
56 import com.stoutner.privacybrowser.fragments.DomainSettingsFragment;
57 import com.stoutner.privacybrowser.fragments.DomainsListFragment;
58 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
60 import java.util.Objects;
62 public class DomainsActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, DomainsListFragment.DismissSnackbarInterface {
63 // `twoPanedMode` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `populateDomainsListView()`.
64 public static boolean twoPanedMode;
66 // `databaseId` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onCreateOptionsMenu()`, `saveDomainSettings()` and `populateDomainsListView()`.
67 public static int currentDomainDatabaseId;
69 // `deleteMenuItem` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `onBackPressed()`.
70 public static MenuItem deleteMenuItem;
72 // `dismissingSnackbar` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onOptionsItemSelected()`.
73 public static boolean dismissingSnackbar;
75 // The SSL certificate and IP address information are accessed from `DomainSettingsFragment` and `saveDomainSettings()`.
76 public static String sslIssuedToCName;
77 public static String sslIssuedToOName;
78 public static String sslIssuedToUName;
79 public static String sslIssuedByCName;
80 public static String sslIssuedByOName;
81 public static String sslIssuedByUName;
82 public static long sslStartDateLong;
83 public static long sslEndDateLong;
84 public static String currentIpAddresses;
87 // `closeActivityAfterDismissingSnackbar` is used in `onOptionsItemSelected()`, and `onBackPressed()`.
88 private boolean closeActivityAfterDismissingSnackbar;
90 // The undelete snackbar is used in `onOptionsItemSelected()` and `onBackPressed()`.
91 private Snackbar undoDeleteSnackbar;
93 // `domainsDatabaseHelper` is used in `onCreate()`, `saveDomainSettings()`, and `onDestroy()`.
94 private static DomainsDatabaseHelper domainsDatabaseHelper;
96 // `domainsListView` is used in `onCreate()` and `populateDomainsList()`.
97 private ListView domainsListView;
99 // `addDomainFAB` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `onBackPressed()`.
100 private FloatingActionButton addDomainFAB;
102 // `deletedDomainPosition` is used in an inner and outer class in `onOptionsItemSelected()`.
103 private int deletedDomainPosition;
105 // `restartAfterRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
106 private boolean restartAfterRotate;
108 // `domainSettingsDisplayedBeforeRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
109 private boolean domainSettingsDisplayedBeforeRotate;
111 // `domainSettingsDatabaseIdBeforeRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
112 private int domainSettingsDatabaseIdBeforeRotate;
114 // `goDirectlyToDatabaseId` is used in `onCreate()` and `onCreateOptionsMenu()`.
115 private int goDirectlyToDatabaseId;
117 // `closeOnBack` is used in `onCreate()`, `onOptionsItemSelected()` and `onBackPressed()`.
118 private boolean closeOnBack;
120 // `coordinatorLayout` is use in `onCreate()`, `onOptionsItemSelected()`, and `onSaveInstanceState()`.
121 private View coordinatorLayout;
123 // `resources` is used in `onCreate()`, `onOptionsItemSelected()`, and `onSaveInstanceState()`.
124 private Resources resources;
127 protected void onCreate(Bundle savedInstanceState) {
128 // Get a handle for the shared preferences.
129 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
131 // Get the theme and screenshot preferences.
132 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
133 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
135 // Disable screenshots if not allowed.
136 if (!allowScreenshots) {
137 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
140 // Set the activity theme.
142 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
144 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
147 // Run the default commands.
148 super.onCreate(savedInstanceState);
150 // Extract the values from `savedInstanceState` if it is not `null`.
151 if (savedInstanceState != null) {
152 restartAfterRotate = true;
153 domainSettingsDisplayedBeforeRotate = savedInstanceState.getBoolean("domain_settings_displayed");
154 domainSettingsDatabaseIdBeforeRotate = savedInstanceState.getInt("domain_settings_database_id");
157 // Get the launching intent
158 Intent intent = getIntent();
160 // Extract the domain to load if there is one. `-1` is the default value.
161 goDirectlyToDatabaseId = intent.getIntExtra("load_domain", -1);
163 // Get the status of close-on-back, which is true when the domains activity is called from the options menu.
164 closeOnBack = intent.getBooleanExtra("close_on_back", false);
166 // Get the current URL.
167 String currentUrl = intent.getStringExtra("current_url");
169 // Store the current SSL certificate information in class variables.
170 sslIssuedToCName = intent.getStringExtra("ssl_issued_to_cname");
171 sslIssuedToOName = intent.getStringExtra("ssl_issued_to_oname");
172 sslIssuedToUName = intent.getStringExtra("ssl_issued_to_uname");
173 sslIssuedByCName = intent.getStringExtra("ssl_issued_by_cname");
174 sslIssuedByOName = intent.getStringExtra("ssl_issued_by_oname");
175 sslIssuedByUName = intent.getStringExtra("ssl_issued_by_uname");
176 sslStartDateLong = intent.getLongExtra("ssl_start_date", 0);
177 sslEndDateLong = intent.getLongExtra("ssl_end_date", 0);
178 currentIpAddresses = intent.getStringExtra("current_ip_addresses");
180 // Set the content view.
181 setContentView(R.layout.domains_coordinatorlayout);
183 // Populate the class variables.
184 coordinatorLayout = findViewById(R.id.domains_coordinatorlayout);
185 resources = getResources();
187 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
188 final Toolbar toolbar = findViewById(R.id.domains_toolbar);
189 setSupportActionBar(toolbar);
191 // Get a handle for the action bar.
192 ActionBar actionBar = getSupportActionBar();
194 // Remove the incorrect lint warning that the action bar might be null.
195 assert actionBar != null;
197 // Set the back arrow on the action bar.
198 actionBar.setDisplayHomeAsUpEnabled(true);
200 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
201 domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
203 // Determine if we are in two pane mode. `domain_settings_fragment_container` does not exist on devices with a width less than 900dp.
204 twoPanedMode = (findViewById(R.id.domain_settings_fragment_container) != null);
206 // Get a handle for the add domain floating action button.
207 addDomainFAB = findViewById(R.id.add_domain_fab);
209 // Configure the add domain floating action button.
210 addDomainFAB.setOnClickListener((View view) -> {
211 // Create an add domain dialog.
212 DialogFragment addDomainDialog = AddDomainDialog.addDomain(currentUrl);
214 // Show the add domain dialog.
215 addDomainDialog.show(getSupportFragmentManager(), resources.getString(R.string.add_domain));
220 public boolean onCreateOptionsMenu(Menu menu) {
222 getMenuInflater().inflate(R.menu.domains_options_menu, menu);
224 // Store `deleteMenuItem` for future use.
225 deleteMenuItem = menu.findItem(R.id.delete_domain);
227 // Only display `deleteMenuItem` (initially) in two-paned mode.
228 deleteMenuItem.setVisible(twoPanedMode);
230 // Get a handle for the fragment manager.
231 FragmentManager fragmentManager = getSupportFragmentManager();
233 // Display the fragments. This must be done from `onCreateOptionsMenu()` instead of `onCreate()` because `populateDomainsListView()` needs `deleteMenuItem` to be inflated.
234 if (restartAfterRotate && domainSettingsDisplayedBeforeRotate) { // The device was rotated and domain settings were displayed previously.
235 if (twoPanedMode) { // The device is in two-paned mode.
236 // Reset `restartAfterRotate`.
237 restartAfterRotate = false;
239 // Display `DomainsListFragment`.
240 DomainsListFragment domainsListFragment = new DomainsListFragment();
241 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
242 fragmentManager.executePendingTransactions();
244 // Populate the list of domains. `domainSettingsDatabaseId` highlights the domain that was highlighted before the rotation.
245 populateDomainsListView(domainSettingsDatabaseIdBeforeRotate);
246 } else { // The device is in single-paned mode.
247 // Reset `restartAfterRotate`.
248 restartAfterRotate = false;
250 // Store the current domain database ID.
251 currentDomainDatabaseId = domainSettingsDatabaseIdBeforeRotate;
253 // Add `currentDomainDatabaseId` to `argumentsBundle`.
254 Bundle argumentsBundle = new Bundle();
255 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
257 // Add `argumentsBundle` to `domainSettingsFragment`.
258 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
259 domainSettingsFragment.setArguments(argumentsBundle);
261 // Show `deleteMenuItem`.
262 deleteMenuItem.setVisible(true);
264 // Hide the add domain floating action button.
267 // Display `domainSettingsFragment`.
268 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
270 } else { // The device was not rotated or, if it was, domain settings were not displayed previously.
271 if (goDirectlyToDatabaseId >=0) { // Load the indicated domain settings.
272 // Store the current domain database ID.
273 currentDomainDatabaseId = goDirectlyToDatabaseId;
275 if (twoPanedMode) { // The device is in two-paned mode.
276 // Display `DomainsListFragment`.
277 DomainsListFragment domainsListFragment = new DomainsListFragment();
278 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
279 fragmentManager.executePendingTransactions();
281 // Populate the list of domains. `domainSettingsDatabaseId` highlights the domain that was highlighted before the rotation.
282 populateDomainsListView(goDirectlyToDatabaseId);
283 } else { // The device is in single-paned mode.
284 // Add the domain ID to be loaded to `argumentsBundle`.
285 Bundle argumentsBundle = new Bundle();
286 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, goDirectlyToDatabaseId);
288 // Add `argumentsBundle` to `domainSettingsFragment`.
289 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
290 domainSettingsFragment.setArguments(argumentsBundle);
292 // Show `deleteMenuItem`.
293 deleteMenuItem.setVisible(true);
295 // Hide the add domain floating action button.
298 // Display `domainSettingsFragment`.
299 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
301 } else { // Highlight the first domain.
302 // Display `DomainsListFragment`.
303 DomainsListFragment domainsListFragment = new DomainsListFragment();
304 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
305 fragmentManager.executePendingTransactions();
307 // Populate the list of domains. `-1` highlights the first domain.
308 populateDomainsListView(-1);
317 public boolean onOptionsItemSelected(MenuItem menuItem) {
318 // Get the ID of the menu item that was selected.
319 int menuItemID = menuItem.getItemId();
321 // Get a handle for the fragment manager.
322 FragmentManager fragmentManager = getSupportFragmentManager();
324 switch (menuItemID) {
325 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
326 if (twoPanedMode) { // The device is in two-paned mode.
327 // Save the current domain settings if the domain settings fragment is displayed.
328 if (findViewById(R.id.domain_settings_scrollview) != null) {
329 saveDomainSettings(coordinatorLayout, resources);
332 // Dismiss the undo delete `SnackBar` if it is shown.
333 if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
334 // Set the close flag.
335 closeActivityAfterDismissingSnackbar = true;
337 // Dismiss the snackbar.
338 undoDeleteSnackbar.dismiss();
341 NavUtils.navigateUpFromSameTask(this);
343 } else if (closeOnBack) { // Go directly back to the main WebView activity because the domains activity was launched from the options menu.
344 // Save the current domain settings.
345 saveDomainSettings(coordinatorLayout, resources);
348 NavUtils.navigateUpFromSameTask(this);
349 } else if (findViewById(R.id.domain_settings_scrollview) != null) { // The device is in single-paned mode and the domain settings fragment is displayed.
350 // Save the current domain settings.
351 saveDomainSettings(coordinatorLayout, resources);
353 // Display the domains list fragment.
354 DomainsListFragment domainsListFragment = new DomainsListFragment();
355 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
356 fragmentManager.executePendingTransactions();
358 // Populate the list of domains. `-1` highlights the first domain if in two-paned mode. It has no effect in single-paned mode.
359 populateDomainsListView(-1);
361 // Show the add domain floating action button.
364 // Hide the delete menu item.
365 deleteMenuItem.setVisible(false);
366 } else { // The device is in single-paned mode and `DomainsListFragment` is displayed.
367 // Dismiss the undo delete `SnackBar` if it is shown.
368 if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
369 // Set the close flag.
370 closeActivityAfterDismissingSnackbar = true;
372 // Dismiss the snackbar.
373 undoDeleteSnackbar.dismiss();
376 NavUtils.navigateUpFromSameTask(this);
381 case R.id.delete_domain:
382 // Reset close-on-back, which otherwise can cause errors if the system attempts to save settings for a domain that no longer exists.
385 // Store a copy of `currentDomainDatabaseId` because it could change while the `Snackbar` is displayed.
386 final int databaseIdToDelete = currentDomainDatabaseId;
388 // Update the fragments and menu items.
389 if (twoPanedMode) { // Two-paned mode.
390 // Store the deleted domain position, which is needed if `Undo` is selected in the `Snackbar`.
391 deletedDomainPosition = domainsListView.getCheckedItemPosition();
393 // Disable the options `MenuItems`.
394 deleteMenuItem.setEnabled(false);
395 deleteMenuItem.setIcon(R.drawable.delete_blue);
397 // Remove the domain settings fragment.
398 fragmentManager.beginTransaction().remove(Objects.requireNonNull(fragmentManager.findFragmentById(R.id.domain_settings_fragment_container))).commit();
399 } else { // Single-paned mode.
400 // Display `DomainsListFragment`.
401 DomainsListFragment domainsListFragment = new DomainsListFragment();
402 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
403 fragmentManager.executePendingTransactions();
405 // Show the add domain floating action button.
408 // Hide `deleteMenuItem`.
409 deleteMenuItem.setVisible(false);
412 // Get a `Cursor` that does not show the domain to be deleted.
413 Cursor domainsPendingDeleteCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomainExcept(databaseIdToDelete);
415 // Setup `domainsPendingDeleteCursorAdapter` with `this` context. `false` disables `autoRequery`.
416 CursorAdapter domainsPendingDeleteCursorAdapter = new CursorAdapter(this, domainsPendingDeleteCursor, false) {
418 public View newView(Context context, Cursor cursor, ViewGroup parent) {
419 // Inflate the individual item layout. `false` does not attach it to the root.
420 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
424 public void bindView(View view, Context context, Cursor cursor) {
425 // Set the domain name.
426 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
427 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
428 domainNameTextView.setText(domainNameString);
432 // Update the handle for the current `domains_listview`.
433 domainsListView = findViewById(R.id.domains_listview);
435 // Update the `ListView`.
436 domainsListView.setAdapter(domainsPendingDeleteCursorAdapter);
438 // Get a handle for the activity.
439 Activity activity = this;
441 // Display a `Snackbar`.
442 undoDeleteSnackbar = Snackbar.make(domainsListView, R.string.domain_deleted, Snackbar.LENGTH_LONG)
443 .setAction(R.string.undo, (View v) -> {
444 // Do nothing because everything will be handled by `onDismissed()` below.
446 .addCallback(new Snackbar.Callback() {
448 public void onDismissed(Snackbar snackbar, int event) {
449 // Run commands based on the event.
450 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) { // The user pushed the `Undo` button.
451 // Store the database ID in arguments bundle.
452 Bundle argumentsBundle = new Bundle();
453 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, databaseIdToDelete);
455 // Add the arguments bundle to the domain settings fragment.
456 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
457 domainSettingsFragment.setArguments(argumentsBundle);
459 // Display the correct fragments.
460 if (twoPanedMode) { // The device in in two-paned mode.
461 // Get a `Cursor` with the current contents of the domains database.
462 Cursor undoDeleteDomainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
464 // Setup `domainsCursorAdapter` with `this` context. `false` disables `autoRequery`.
465 CursorAdapter undoDeleteDomainsCursorAdapter = new CursorAdapter(getApplicationContext(), undoDeleteDomainsCursor, false) {
467 public View newView(Context context, Cursor cursor, ViewGroup parent) {
468 // Inflate the individual item layout. `false` does not attach it to the root.
469 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
473 public void bindView(View view, Context context, Cursor cursor) {
474 // Set the domain name.
475 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
476 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
477 domainNameTextView.setText(domainNameString);
481 // Update the `ListView`.
482 domainsListView.setAdapter(undoDeleteDomainsCursorAdapter);
483 // Select the previously deleted domain in `domainsListView`.
484 domainsListView.setItemChecked(deletedDomainPosition, true);
486 // Display `domainSettingsFragment`.
487 fragmentManager.beginTransaction().replace(R.id.domain_settings_fragment_container, domainSettingsFragment).commit();
489 // Enable the options `MenuItems`.
490 deleteMenuItem.setEnabled(true);
491 deleteMenuItem.setIcon(R.drawable.delete_light);
492 } else { // The device in in one-paned mode.
493 // Display `domainSettingsFragment`.
494 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
496 // Hide the add domain floating action button.
499 // Show and enable `deleteMenuItem`.
500 deleteMenuItem.setVisible(true);
502 // Display `domainSettingsFragment`.
503 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
505 } else { // The snackbar was dismissed without the undo button being pushed.
506 // Delete the selected domain.
507 domainsDatabaseHelper.deleteDomain(databaseIdToDelete);
509 // Enable the delete menu item if the system was waiting for a snackbar to be dismissed.
510 if (dismissingSnackbar) {
511 // Create a `Runnable` to enable the delete menu item.
512 Runnable enableDeleteMenuItemRunnable = () -> {
513 // Enable `deleteMenuItem` according to the display mode.
514 if (twoPanedMode) { // Two-paned mode.
515 // Enable the delete menu item.
516 deleteMenuItem.setEnabled(true);
518 // Get a handle for the shared preferences.
519 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
521 // Get the theme preferences.
522 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
524 // Set the delete icon according to the theme.
526 deleteMenuItem.setIcon(R.drawable.delete_dark);
528 deleteMenuItem.setIcon(R.drawable.delete_light);
530 } else { // Single-paned mode.
531 // Show `deleteMenuItem`.
532 deleteMenuItem.setVisible(true);
535 // Reset `dismissingSnackbar`.
536 dismissingSnackbar = false;
539 // Enable the delete menu icon after 100 milliseconds to make sure that the previous domain has been deleted from the database.
540 Handler handler = new Handler();
541 handler.postDelayed(enableDeleteMenuItemRunnable, 100);
544 // Close the activity if back was pressed.
545 if (closeActivityAfterDismissingSnackbar) {
547 NavUtils.navigateUpFromSameTask(activity);
553 // Show the Snackbar.
554 undoDeleteSnackbar.show();
558 // Consume the event.
563 protected void onSaveInstanceState(Bundle outState) {
564 // Store the current `DomainSettingsFragment` state in `outState`.
565 if (findViewById(R.id.domain_settings_scrollview) != null) { // `DomainSettingsFragment` is displayed.
566 // Save any changes that have been made to the domain settings.
567 saveDomainSettings(coordinatorLayout, resources);
569 // Store `DomainSettingsDisplayed`.
570 outState.putBoolean("domain_settings_displayed", true);
571 outState.putInt("domain_settings_database_id", DomainSettingsFragment.databaseId);
572 } else { // `DomainSettingsFragment` is not displayed.
573 outState.putBoolean("domain_settings_displayed", false);
574 outState.putInt("domain_settings_database_id", -1);
577 super.onSaveInstanceState(outState);
580 // Control what the navigation bar back button does.
582 public void onBackPressed() {
583 // Get a handle for the fragment manager.
584 FragmentManager fragmentManager = getSupportFragmentManager();
586 if (twoPanedMode) { // The device is in two-paned mode.
587 // Save the current domain settings if the domain settings fragment is displayed.
588 if (findViewById(R.id.domain_settings_scrollview) != null) {
589 saveDomainSettings(coordinatorLayout, resources);
592 // Dismiss the undo delete SnackBar if it is shown.
593 if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
594 // Set the close flag.
595 closeActivityAfterDismissingSnackbar = true;
597 // Dismiss the snackbar.
598 undoDeleteSnackbar.dismiss();
600 // Pass `onBackPressed()` to the system.
601 super.onBackPressed();
603 } else if (closeOnBack) { // Go directly back to the main WebView activity because the domains activity was launched from the options menu.
604 // Save the current domain settings.
605 saveDomainSettings(coordinatorLayout, resources);
607 // Pass `onBackPressed()` to the system.
608 super.onBackPressed();
609 } else if (findViewById(R.id.domain_settings_scrollview) != null) { // The device is in single-paned mode and domain settings fragment is displayed.
610 // Save the current domain settings.
611 saveDomainSettings(coordinatorLayout, resources);
613 // Display the domains list fragment.
614 DomainsListFragment domainsListFragment = new DomainsListFragment();
615 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
616 fragmentManager.executePendingTransactions();
618 // Populate the list of domains. `-1` highlights the first domain if in two-paned mode. It has no effect in single-paned mode.
619 populateDomainsListView(-1);
621 // Show the add domain floating action button.
624 // Hide the delete menu item.
625 deleteMenuItem.setVisible(false);
626 } else { // The device is in single-paned mode and the domain list fragment is displayed.
627 // Dismiss the undo delete SnackBar if it is shown.
628 if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
629 // Set the close flag.
630 closeActivityAfterDismissingSnackbar = true;
632 // Dismiss the snackbar.
633 undoDeleteSnackbar.dismiss();
635 // Pass `onBackPressed()` to the system.
636 super.onBackPressed();
642 public void onAddDomain(DialogFragment dialogFragment) {
643 // Dismiss the undo delete snackbar if it is currently displayed.
644 if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
645 undoDeleteSnackbar.dismiss();
648 // Get the new domain name String from the dialog fragment.
649 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
650 String domainNameString = domainNameEditText.getText().toString();
652 // Create the domain and store the database ID in `currentDomainDatabaseId`.
653 currentDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
655 // Display the newly created domain.
656 if (twoPanedMode) { // The device in in two-paned mode.
657 populateDomainsListView(currentDomainDatabaseId);
658 } else { // The device is in single-paned mode.
659 // Hide the add domain floating action button.
662 // Show and enable `deleteMenuItem`.
663 DomainsActivity.deleteMenuItem.setVisible(true);
665 // Add the current domain database ID to the arguments bundle.
666 Bundle argumentsBundle = new Bundle();
667 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
669 // Add and arguments bundle to the domain setting fragment.
670 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
671 domainSettingsFragment.setArguments(argumentsBundle);
673 // Display the domain settings fragment.
674 getSupportFragmentManager().beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
678 public void saveDomainSettings(View view, Resources resources) {
679 // Get handles for the domain settings.
680 EditText domainNameEditText = view.findViewById(R.id.domain_settings_name_edittext);
681 Switch javaScriptSwitch = view.findViewById(R.id.javascript_switch);
682 Switch firstPartyCookiesSwitch = view.findViewById(R.id.first_party_cookies_switch);
683 Switch thirdPartyCookiesSwitch = view.findViewById(R.id.third_party_cookies_switch);
684 Switch domStorageSwitch = view.findViewById(R.id.dom_storage_switch);
685 Switch formDataSwitch = view.findViewById(R.id.form_data_switch); // Form data can be removed once the minimum API >= 26.
686 Switch easyListSwitch = view.findViewById(R.id.easylist_switch);
687 Switch easyPrivacySwitch = view.findViewById(R.id.easyprivacy_switch);
688 Switch fanboysAnnoyanceSwitch = view.findViewById(R.id.fanboys_annoyance_list_switch);
689 Switch fanboysSocialBlockingSwitch = view.findViewById(R.id.fanboys_social_blocking_list_switch);
690 Switch ultraPrivacySwitch = view.findViewById(R.id.ultraprivacy_switch);
691 Switch blockAllThirdPartyRequestsSwitch = view.findViewById(R.id.block_all_third_party_requests_switch);
692 Spinner userAgentSpinner = view.findViewById(R.id.user_agent_spinner);
693 EditText customUserAgentEditText = view.findViewById(R.id.custom_user_agent_edittext);
694 Spinner fontSizeSpinner = view.findViewById(R.id.font_size_spinner);
695 Spinner swipeToRefreshSpinner = view.findViewById(R.id.swipe_to_refresh_spinner);
696 Spinner nightModeSpinner = view.findViewById(R.id.night_mode_spinner);
697 Spinner wideViewportSpinner = view.findViewById(R.id.wide_viewport_spinner);
698 Spinner displayWebpageImagesSpinner = view.findViewById(R.id.display_webpage_images_spinner);
699 Switch pinnedSslCertificateSwitch = view.findViewById(R.id.pinned_ssl_certificate_switch);
700 RadioButton currentWebsiteCertificateRadioButton = view.findViewById(R.id.current_website_certificate_radiobutton);
701 Switch pinnedIpAddressesSwitch = view.findViewById(R.id.pinned_ip_addresses_switch);
702 RadioButton currentIpAddressesRadioButton = view.findViewById(R.id.current_ip_addresses_radiobutton);
704 // Extract the data for the domain settings.
705 String domainNameString = domainNameEditText.getText().toString();
706 boolean javaScriptEnabled = javaScriptSwitch.isChecked();
707 boolean firstPartyCookiesEnabled = firstPartyCookiesSwitch.isChecked();
708 boolean thirdPartyCookiesEnabled = thirdPartyCookiesSwitch.isChecked();
709 boolean domStorageEnabled = domStorageSwitch.isChecked();
710 boolean formDataEnabled = formDataSwitch.isChecked(); // Form data can be removed once the minimum API >= 26.
711 boolean easyListEnabled = easyListSwitch.isChecked();
712 boolean easyPrivacyEnabled = easyPrivacySwitch.isChecked();
713 boolean fanboysAnnoyanceEnabled = fanboysAnnoyanceSwitch.isChecked();
714 boolean fanboysSocialBlockingEnabled = fanboysSocialBlockingSwitch.isChecked();
715 boolean ultraPrivacyEnabled = ultraPrivacySwitch.isChecked();
716 boolean blockAllThirdPartyRequests = blockAllThirdPartyRequestsSwitch.isChecked();
717 int userAgentPosition = userAgentSpinner.getSelectedItemPosition();
718 int fontSizePosition = fontSizeSpinner.getSelectedItemPosition();
719 int swipeToRefreshInt = swipeToRefreshSpinner.getSelectedItemPosition();
720 int nightModeInt = nightModeSpinner.getSelectedItemPosition();
721 int wideViewportInt = wideViewportSpinner.getSelectedItemPosition();
722 int displayWebpageImagesInt = displayWebpageImagesSpinner.getSelectedItemPosition();
723 boolean pinnedSslCertificate = pinnedSslCertificateSwitch.isChecked();
724 boolean pinnedIpAddress = pinnedIpAddressesSwitch.isChecked();
726 // Initialize the user agent name string.
727 String userAgentName;
729 // Set the user agent name.
730 switch (userAgentPosition) {
731 case MainWebViewActivity.DOMAINS_SYSTEM_DEFAULT_USER_AGENT:
732 // Set the user agent name to be `System default user agent`.
733 userAgentName = resources.getString(R.string.system_default_user_agent);
736 case MainWebViewActivity.DOMAINS_CUSTOM_USER_AGENT:
737 // Set the user agent name to be the custom user agent.
738 userAgentName = customUserAgentEditText.getText().toString();
742 // Get the array of user agent names.
743 String[] userAgentNameArray = resources.getStringArray(R.array.user_agent_names);
745 // Set the user agent name from the array. The domain spinner has one more entry than the name array, so the position must be decremented.
746 userAgentName = userAgentNameArray[userAgentPosition - 1];
749 // Get the font size integer.
750 int fontSizeInt = Integer.parseInt(resources.getStringArray(R.array.domain_settings_font_size_entry_values)[fontSizePosition]);
752 // Save the domain settings.
753 domainsDatabaseHelper.updateDomain(DomainsActivity.currentDomainDatabaseId, domainNameString, javaScriptEnabled, firstPartyCookiesEnabled, thirdPartyCookiesEnabled,
754 domStorageEnabled, formDataEnabled, easyListEnabled, easyPrivacyEnabled, fanboysAnnoyanceEnabled, fanboysSocialBlockingEnabled, ultraPrivacyEnabled, blockAllThirdPartyRequests,
755 userAgentName, fontSizeInt, swipeToRefreshInt, nightModeInt, wideViewportInt, displayWebpageImagesInt, pinnedSslCertificate, pinnedIpAddress);
757 // Update the pinned SSL certificate if a new one is checked.
758 if (currentWebsiteCertificateRadioButton.isChecked()) {
759 // Update the database.
760 domainsDatabaseHelper.updatePinnedSslCertificate(currentDomainDatabaseId, sslIssuedToCName, sslIssuedToOName, sslIssuedToUName, sslIssuedByCName, sslIssuedByOName, sslIssuedByUName,
761 sslStartDateLong, sslEndDateLong);
764 // Update the pinned IP addresses if new ones are checked.
765 if (currentIpAddressesRadioButton.isChecked()) {
766 // Update the database.
767 domainsDatabaseHelper.updatePinnedIpAddresses(currentDomainDatabaseId, currentIpAddresses);
771 private void populateDomainsListView(final int highlightedDomainDatabaseId) {
772 // get a handle for the current `domains_listview`.
773 domainsListView = findViewById(R.id.domains_listview);
775 // Get a `Cursor` with the current contents of the domains database.
776 Cursor domainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
778 // Setup `domainsCursorAdapter` with `this` context. `false` disables `autoRequery`.
779 CursorAdapter domainsCursorAdapter = new CursorAdapter(getApplicationContext(), domainsCursor, false) {
781 public View newView(Context context, Cursor cursor, ViewGroup parent) {
782 // Inflate the individual item layout. `false` does not attach it to the root.
783 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
787 public void bindView(View view, Context context, Cursor cursor) {
788 // Set the domain name.
789 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
790 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
791 domainNameTextView.setText(domainNameString);
795 // Update the `ListView`.
796 domainsListView.setAdapter(domainsCursorAdapter);
798 // Display the domain settings in the second pane if operating in two pane mode and the database contains at least one domain.
799 if (DomainsActivity.twoPanedMode && (domainsCursor.getCount() > 0)) { // Two-paned mode is enabled and there is at least one domain.
800 // Initialize `highlightedDomainPosition`.
801 int highlightedDomainPosition = 0;
803 // Get the cursor position for the highlighted domain.
804 for (int i = 0; i < domainsCursor.getCount(); i++) {
805 // Move to position `i` in the cursor.
806 domainsCursor.moveToPosition(i);
808 // Get the database ID for this position.
809 int currentDatabaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
811 // Set `highlightedDomainPosition` if the database ID for this matches `highlightedDomainDatabaseId`.
812 if (highlightedDomainDatabaseId == currentDatabaseId) {
813 highlightedDomainPosition = i;
817 // Select the highlighted domain.
818 domainsListView.setItemChecked(highlightedDomainPosition, true);
820 // Get the database ID for the highlighted domain.
821 domainsCursor.moveToPosition(highlightedDomainPosition);
822 currentDomainDatabaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
824 // Store the database ID in the arguments bundle.
825 Bundle argumentsBundle = new Bundle();
826 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
828 // Add and arguments bundle to the domain settings fragment.
829 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
830 domainSettingsFragment.setArguments(argumentsBundle);
832 // Display the domain settings fragment.
833 getSupportFragmentManager().beginTransaction().replace(R.id.domain_settings_fragment_container, domainSettingsFragment).commit();
835 // Enable the delete options menu items.
836 deleteMenuItem.setEnabled(true);
838 // Get a handle for the shared preferences.
839 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
841 // Get the theme and screenshot preferences.
842 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
844 // Set the delete icon according to the theme.
846 deleteMenuItem.setIcon(R.drawable.delete_dark);
848 deleteMenuItem.setIcon(R.drawable.delete_light);
850 } else if (twoPanedMode) { // Two-paned mode is enabled but there are no domains.
851 // Disable the options `MenuItems`.
852 deleteMenuItem.setEnabled(false);
853 deleteMenuItem.setIcon(R.drawable.delete_blue);
858 public void dismissSnackbar() {
859 // Dismiss the undo delete snackbar if it is shown.
860 if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
861 // Dismiss the snackbar.
862 undoDeleteSnackbar.dismiss();
867 public void onDestroy() {
868 // Close the domains database helper.
869 domainsDatabaseHelper.close();
871 // Run the default commands.