Allow specifying any font size. https://redmine.stoutner.com/issues/504
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / DomainsActivity.java
1 /*
2  * Copyright © 2017-2019 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
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;
43
44 import androidx.annotation.NonNull;
45 import androidx.appcompat.app.ActionBar;
46 import androidx.appcompat.app.AppCompatActivity;
47 import androidx.appcompat.widget.Toolbar;  // The AndroidX toolbar must be used until the minimum API is >= 21.
48 import androidx.core.app.NavUtils;
49 import androidx.fragment.app.DialogFragment;
50 import androidx.fragment.app.FragmentManager;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
51
52 import com.google.android.material.floatingactionbutton.FloatingActionButton;
53 import com.google.android.material.snackbar.Snackbar;
54
55 import com.stoutner.privacybrowser.R;
56 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
57 import com.stoutner.privacybrowser.fragments.DomainSettingsFragment;
58 import com.stoutner.privacybrowser.fragments.DomainsListFragment;
59 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
60
61 import java.util.Objects;
62
63 public class DomainsActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, DomainsListFragment.DismissSnackbarInterface {
64     // `twoPanedMode` is public static so it can be accessed from `DomainsListFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `populateDomainsListView()`.
65     public static boolean twoPanedMode;
66
67     // `databaseId` is public static so it can be accessed from `DomainsListFragment`.  It is also used in `onCreateOptionsMenu()`, `saveDomainSettings()` and `populateDomainsListView()`.
68     public static int currentDomainDatabaseId;
69
70     // `deleteMenuItem` is public static so it can be accessed from `DomainsListFragment`.  It is also used in `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `onBackPressed()`.
71     public static MenuItem deleteMenuItem;
72
73     // `dismissingSnackbar` is public static so it can be accessed from `DomainsListFragment`.  It is also used in `onOptionsItemSelected()`.
74     public static boolean dismissingSnackbar;
75
76     // The SSL certificate and IP address information are accessed from `DomainSettingsFragment` and `saveDomainSettings()`.
77     public static String sslIssuedToCName;
78     public static String sslIssuedToOName;
79     public static String sslIssuedToUName;
80     public static String sslIssuedByCName;
81     public static String sslIssuedByOName;
82     public static String sslIssuedByUName;
83     public static long sslStartDateLong;
84     public static long sslEndDateLong;
85     public static String currentIpAddresses;
86
87
88     // `closeActivityAfterDismissingSnackbar` is used in `onOptionsItemSelected()`, and `onBackPressed()`.
89     private boolean closeActivityAfterDismissingSnackbar;
90
91     // The undelete snackbar is used in `onOptionsItemSelected()` and `onBackPressed()`.
92     private Snackbar undoDeleteSnackbar;
93
94     // `domainsDatabaseHelper` is used in `onCreate()`, `saveDomainSettings()`, and `onDestroy()`.
95     private static DomainsDatabaseHelper domainsDatabaseHelper;
96
97     // `domainsListView` is used in `onCreate()` and `populateDomainsList()`.
98     private ListView domainsListView;
99
100     // `addDomainFAB` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `onBackPressed()`.
101     private FloatingActionButton addDomainFAB;
102
103     // `deletedDomainPosition` is used in an inner and outer class in `onOptionsItemSelected()`.
104     private int deletedDomainPosition;
105
106     // `restartAfterRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
107     private boolean restartAfterRotate;
108
109     // `domainSettingsDisplayedBeforeRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
110     private boolean domainSettingsDisplayedBeforeRotate;
111
112     // `domainSettingsDatabaseIdBeforeRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
113     private int domainSettingsDatabaseIdBeforeRotate;
114
115     // `goDirectlyToDatabaseId` is used in `onCreate()` and `onCreateOptionsMenu()`.
116     private int goDirectlyToDatabaseId;
117
118     // `closeOnBack` is used in `onCreate()`, `onOptionsItemSelected()` and `onBackPressed()`.
119     private boolean closeOnBack;
120
121     // `coordinatorLayout` is use in `onCreate()`, `onOptionsItemSelected()`, and `onSaveInstanceState()`.
122     private View coordinatorLayout;
123
124     // `resources` is used in `onCreate()`, `onOptionsItemSelected()`, and `onSaveInstanceState()`.
125     private Resources resources;
126
127     @Override
128     protected void onCreate(Bundle savedInstanceState) {
129         // Get a handle for the shared preferences.
130         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
131
132         // Get the theme and screenshot preferences.
133         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
134         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
135
136         // Disable screenshots if not allowed.
137         if (!allowScreenshots) {
138             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
139         }
140
141         // Set the activity theme.
142         if (darkTheme) {
143             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
144         } else {
145             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
146         }
147
148         // Run the default commands.
149         super.onCreate(savedInstanceState);
150
151         // Extract the values from `savedInstanceState` if it is not `null`.
152         if (savedInstanceState != null) {
153             restartAfterRotate = true;
154             domainSettingsDisplayedBeforeRotate = savedInstanceState.getBoolean("domain_settings_displayed");
155             domainSettingsDatabaseIdBeforeRotate = savedInstanceState.getInt("domain_settings_database_id");
156         }
157
158         // Get the launching intent
159         Intent intent = getIntent();
160
161         // Extract the domain to load if there is one.  `-1` is the default value.
162         goDirectlyToDatabaseId = intent.getIntExtra("load_domain", -1);
163
164         // Get the status of close-on-back, which is true when the domains activity is called from the options menu.
165         closeOnBack = intent.getBooleanExtra("close_on_back", false);
166
167         // Get the current URL.
168         String currentUrl = intent.getStringExtra("current_url");
169
170         // Store the current SSL certificate information in class variables.
171         sslIssuedToCName = intent.getStringExtra("ssl_issued_to_cname");
172         sslIssuedToOName = intent.getStringExtra("ssl_issued_to_oname");
173         sslIssuedToUName = intent.getStringExtra("ssl_issued_to_uname");
174         sslIssuedByCName = intent.getStringExtra("ssl_issued_by_cname");
175         sslIssuedByOName = intent.getStringExtra("ssl_issued_by_oname");
176         sslIssuedByUName = intent.getStringExtra("ssl_issued_by_uname");
177         sslStartDateLong = intent.getLongExtra("ssl_start_date", 0);
178         sslEndDateLong = intent.getLongExtra("ssl_end_date", 0);
179         currentIpAddresses = intent.getStringExtra("current_ip_addresses");
180
181         // Set the content view.
182         setContentView(R.layout.domains_coordinatorlayout);
183
184         // Populate the class variables.
185         coordinatorLayout = findViewById(R.id.domains_coordinatorlayout);
186         resources = getResources();
187
188         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
189         final Toolbar toolbar = findViewById(R.id.domains_toolbar);
190         setSupportActionBar(toolbar);
191
192         // Get a handle for the action bar.
193         ActionBar actionBar = getSupportActionBar();
194
195         // Remove the incorrect lint warning that the action bar might be null.
196         assert actionBar != null;
197
198         // Set the back arrow on the action bar.
199         actionBar.setDisplayHomeAsUpEnabled(true);
200
201         // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
202         domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
203
204         // Determine if we are in two pane mode.  `domain_settings_fragment_container` does not exist on devices with a width less than 900dp.
205         twoPanedMode = (findViewById(R.id.domain_settings_fragment_container) != null);
206
207         // Get a handle for the add domain floating action button.
208         addDomainFAB = findViewById(R.id.add_domain_fab);
209
210         // Configure the add domain floating action button.
211         addDomainFAB.setOnClickListener((View view) -> {
212             // Create an add domain dialog.
213             DialogFragment addDomainDialog = AddDomainDialog.addDomain(currentUrl);
214
215             // Show the add domain dialog.
216             addDomainDialog.show(getSupportFragmentManager(), resources.getString(R.string.add_domain));
217         });
218     }
219
220     @Override
221     public boolean onCreateOptionsMenu(Menu menu) {
222         // Inflate the menu.
223         getMenuInflater().inflate(R.menu.domains_options_menu, menu);
224
225         // Store `deleteMenuItem` for future use.
226         deleteMenuItem = menu.findItem(R.id.delete_domain);
227
228         // Only display `deleteMenuItem` (initially) in two-paned mode.
229         deleteMenuItem.setVisible(twoPanedMode);
230
231         // Get a handle for the fragment manager.
232         FragmentManager fragmentManager = getSupportFragmentManager();
233
234         // Display the fragments.  This must be done from `onCreateOptionsMenu()` instead of `onCreate()` because `populateDomainsListView()` needs `deleteMenuItem` to be inflated.
235         if (restartAfterRotate && domainSettingsDisplayedBeforeRotate) {  // The device was rotated and domain settings were displayed previously.
236             if (twoPanedMode) {  // The device is in two-paned mode.
237                 // Reset `restartAfterRotate`.
238                 restartAfterRotate = false;
239
240                 // Display `DomainsListFragment`.
241                 DomainsListFragment domainsListFragment = new DomainsListFragment();
242                 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
243                 fragmentManager.executePendingTransactions();
244
245                 // Populate the list of domains.  `domainSettingsDatabaseId` highlights the domain that was highlighted before the rotation.
246                 populateDomainsListView(domainSettingsDatabaseIdBeforeRotate);
247             } else {  // The device is in single-paned mode.
248                 // Reset `restartAfterRotate`.
249                 restartAfterRotate = false;
250
251                 // Store the current domain database ID.
252                 currentDomainDatabaseId = domainSettingsDatabaseIdBeforeRotate;
253
254                 // Add `currentDomainDatabaseId` to `argumentsBundle`.
255                 Bundle argumentsBundle = new Bundle();
256                 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
257
258                 // Add `argumentsBundle` to `domainSettingsFragment`.
259                 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
260                 domainSettingsFragment.setArguments(argumentsBundle);
261
262                 // Show `deleteMenuItem`.
263                 deleteMenuItem.setVisible(true);
264
265                 // Hide the add domain floating action button.
266                 addDomainFAB.hide();
267
268                 // Display `domainSettingsFragment`.
269                 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
270             }
271         } else {  // The device was not rotated or, if it was, domain settings were not displayed previously.
272             if (goDirectlyToDatabaseId >=0) {  // Load the indicated domain settings.
273                 // Store the current domain database ID.
274                 currentDomainDatabaseId = goDirectlyToDatabaseId;
275
276                 if (twoPanedMode) {  // The device is in two-paned mode.
277                     // Display `DomainsListFragment`.
278                     DomainsListFragment domainsListFragment = new DomainsListFragment();
279                     fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
280                     fragmentManager.executePendingTransactions();
281
282                     // Populate the list of domains.  `domainSettingsDatabaseId` highlights the domain that was highlighted before the rotation.
283                     populateDomainsListView(goDirectlyToDatabaseId);
284                 } else {  // The device is in single-paned mode.
285                     // Add the domain ID to be loaded to `argumentsBundle`.
286                     Bundle argumentsBundle = new Bundle();
287                     argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, goDirectlyToDatabaseId);
288
289                     // Add `argumentsBundle` to `domainSettingsFragment`.
290                     DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
291                     domainSettingsFragment.setArguments(argumentsBundle);
292
293                     // Show `deleteMenuItem`.
294                     deleteMenuItem.setVisible(true);
295
296                     // Hide the add domain floating action button.
297                     addDomainFAB.hide();
298
299                     // Display `domainSettingsFragment`.
300                     fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
301                 }
302             } else {  // Highlight the first domain.
303                 // Display `DomainsListFragment`.
304                 DomainsListFragment domainsListFragment = new DomainsListFragment();
305                 fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
306                 fragmentManager.executePendingTransactions();
307
308                 // Populate the list of domains.  `-1` highlights the first domain.
309                 populateDomainsListView(-1);
310             }
311         }
312
313         // Success!
314         return true;
315     }
316
317     @Override
318     public boolean onOptionsItemSelected(MenuItem menuItem) {
319         // Get the ID of the menu item that was selected.
320         int menuItemID = menuItem.getItemId();
321
322         // Get a handle for the fragment manager.
323         FragmentManager fragmentManager = getSupportFragmentManager();
324
325         switch (menuItemID) {
326             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
327                 if (twoPanedMode) {  // The device is in two-paned mode.
328                     // Save the current domain settings if the domain settings fragment is displayed.
329                     if (findViewById(R.id.domain_settings_scrollview) != null) {
330                         saveDomainSettings(coordinatorLayout, resources);
331                     }
332
333                     // Dismiss the undo delete `SnackBar` if it is shown.
334                     if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
335                         // Set the close flag.
336                         closeActivityAfterDismissingSnackbar = true;
337
338                         // Dismiss the snackbar.
339                         undoDeleteSnackbar.dismiss();
340                     } else {
341                         // Go home.
342                         NavUtils.navigateUpFromSameTask(this);
343                     }
344                 } else if (closeOnBack) {  // Go directly back to the main WebView activity because the domains activity was launched from the options menu.
345                     // Save the current domain settings.
346                     saveDomainSettings(coordinatorLayout, resources);
347
348                     // Go home.
349                     NavUtils.navigateUpFromSameTask(this);
350                 } else if (findViewById(R.id.domain_settings_scrollview) != null) {  // The device is in single-paned mode and the domain settings fragment is displayed.
351                     // Save the current domain settings.
352                     saveDomainSettings(coordinatorLayout, resources);
353
354                     // Display the domains list fragment.
355                     DomainsListFragment domainsListFragment = new DomainsListFragment();
356                     fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
357                     fragmentManager.executePendingTransactions();
358
359                     // Populate the list of domains.  `-1` highlights the first domain if in two-paned mode.  It has no effect in single-paned mode.
360                     populateDomainsListView(-1);
361
362                     // Show the add domain floating action button.
363                     addDomainFAB.show();
364
365                     // Hide the delete menu item.
366                     deleteMenuItem.setVisible(false);
367                 } else {  // The device is in single-paned mode and `DomainsListFragment` is displayed.
368                     // Dismiss the undo delete `SnackBar` if it is shown.
369                     if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
370                         // Set the close flag.
371                         closeActivityAfterDismissingSnackbar = true;
372
373                         // Dismiss the snackbar.
374                         undoDeleteSnackbar.dismiss();
375                     } else {
376                         // Go home.
377                         NavUtils.navigateUpFromSameTask(this);
378                     }
379                 }
380                 break;
381
382             case R.id.delete_domain:
383                 // Reset close-on-back, which otherwise can cause errors if the system attempts to save settings for a domain that no longer exists.
384                 closeOnBack = false;
385
386                 // Store a copy of `currentDomainDatabaseId` because it could change while the `Snackbar` is displayed.
387                 final int databaseIdToDelete = currentDomainDatabaseId;
388
389                 // Update the fragments and menu items.
390                 if (twoPanedMode) {  // Two-paned mode.
391                     // Store the deleted domain position, which is needed if `Undo` is selected in the `Snackbar`.
392                     deletedDomainPosition = domainsListView.getCheckedItemPosition();
393
394                     // Disable the options `MenuItems`.
395                     deleteMenuItem.setEnabled(false);
396                     deleteMenuItem.setIcon(R.drawable.delete_blue);
397
398                     // Remove the domain settings fragment.
399                     fragmentManager.beginTransaction().remove(Objects.requireNonNull(fragmentManager.findFragmentById(R.id.domain_settings_fragment_container))).commit();
400                 } else {  // Single-paned mode.
401                     // Display `DomainsListFragment`.
402                     DomainsListFragment domainsListFragment = new DomainsListFragment();
403                     fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
404                     fragmentManager.executePendingTransactions();
405
406                     // Show the add domain floating action button.
407                     addDomainFAB.show();
408
409                     // Hide `deleteMenuItem`.
410                     deleteMenuItem.setVisible(false);
411                 }
412
413                 // Get a `Cursor` that does not show the domain to be deleted.
414                 Cursor domainsPendingDeleteCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomainExcept(databaseIdToDelete);
415
416                 // Setup `domainsPendingDeleteCursorAdapter` with `this` context.  `false` disables `autoRequery`.
417                 CursorAdapter domainsPendingDeleteCursorAdapter = new CursorAdapter(this, domainsPendingDeleteCursor, false) {
418                     @Override
419                     public View newView(Context context, Cursor cursor, ViewGroup parent) {
420                         // Inflate the individual item layout.  `false` does not attach it to the root.
421                         return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
422                     }
423
424                     @Override
425                     public void bindView(View view, Context context, Cursor cursor) {
426                         // Set the domain name.
427                         String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
428                         TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
429                         domainNameTextView.setText(domainNameString);
430                     }
431                 };
432
433                 // Update the handle for the current `domains_listview`.
434                 domainsListView = findViewById(R.id.domains_listview);
435
436                 // Update the `ListView`.
437                 domainsListView.setAdapter(domainsPendingDeleteCursorAdapter);
438
439                 // Get a handle for the activity.
440                 Activity activity = this;
441
442                 // Display a `Snackbar`.
443                 undoDeleteSnackbar = Snackbar.make(domainsListView, R.string.domain_deleted, Snackbar.LENGTH_LONG)
444                         .setAction(R.string.undo, (View v) -> {
445                             // Do nothing because everything will be handled by `onDismissed()` below.
446                         })
447                         .addCallback(new Snackbar.Callback() {
448                             @Override
449                             public void onDismissed(Snackbar snackbar, int event) {
450                                 // Run commands based on the event.
451                                 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The user pushed the `Undo` button.
452                                     // Store the database ID in arguments bundle.
453                                     Bundle argumentsBundle = new Bundle();
454                                     argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, databaseIdToDelete);
455
456                                     // Add the arguments bundle to the domain settings fragment.
457                                     DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
458                                     domainSettingsFragment.setArguments(argumentsBundle);
459
460                                     // Display the correct fragments.
461                                     if (twoPanedMode) {  // The device in in two-paned mode.
462                                         // Get a `Cursor` with the current contents of the domains database.
463                                         Cursor undoDeleteDomainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
464
465                                         // Setup `domainsCursorAdapter` with `this` context.  `false` disables `autoRequery`.
466                                         CursorAdapter undoDeleteDomainsCursorAdapter = new CursorAdapter(getApplicationContext(), undoDeleteDomainsCursor, false) {
467                                             @Override
468                                             public View newView(Context context, Cursor cursor, ViewGroup parent) {
469                                                 // Inflate the individual item layout.  `false` does not attach it to the root.
470                                                 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
471                                             }
472
473                                             @Override
474                                             public void bindView(View view, Context context, Cursor cursor) {
475                                                 // Set the domain name.
476                                                 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
477                                                 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
478                                                 domainNameTextView.setText(domainNameString);
479                                             }
480                                         };
481
482                                         // Update the `ListView`.
483                                         domainsListView.setAdapter(undoDeleteDomainsCursorAdapter);
484                                         // Select the previously deleted domain in `domainsListView`.
485                                         domainsListView.setItemChecked(deletedDomainPosition, true);
486
487                                         // Display `domainSettingsFragment`.
488                                         fragmentManager.beginTransaction().replace(R.id.domain_settings_fragment_container, domainSettingsFragment).commit();
489
490                                         // Enable the options `MenuItems`.
491                                         deleteMenuItem.setEnabled(true);
492                                         deleteMenuItem.setIcon(R.drawable.delete_light);
493                                     } else {  // The device in in one-paned mode.
494                                         // Display `domainSettingsFragment`.
495                                         fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
496
497                                         // Hide the add domain floating action button.
498                                         addDomainFAB.hide();
499
500                                         // Show and enable `deleteMenuItem`.
501                                         deleteMenuItem.setVisible(true);
502
503                                         // Display `domainSettingsFragment`.
504                                         fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
505                                     }
506                                 } else {  // The snackbar was dismissed without the undo button being pushed.
507                                     // Delete the selected domain.
508                                     domainsDatabaseHelper.deleteDomain(databaseIdToDelete);
509
510                                     // Enable the delete menu item if the system was waiting for a snackbar to be dismissed.
511                                     if (dismissingSnackbar) {
512                                         // Create a `Runnable` to enable the delete menu item.
513                                         Runnable enableDeleteMenuItemRunnable = () -> {
514                                             // Enable `deleteMenuItem` according to the display mode.
515                                             if (twoPanedMode) {  // Two-paned mode.
516                                                 // Enable the delete menu item.
517                                                 deleteMenuItem.setEnabled(true);
518
519                                                 // Get a handle for the shared preferences.
520                                                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
521
522                                                 // Get the theme preferences.
523                                                 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
524
525                                                 // Set the delete icon according to the theme.
526                                                 if (darkTheme) {
527                                                     deleteMenuItem.setIcon(R.drawable.delete_dark);
528                                                 } else {
529                                                     deleteMenuItem.setIcon(R.drawable.delete_light);
530                                                 }
531                                             } else {  // Single-paned mode.
532                                                 // Show `deleteMenuItem`.
533                                                 deleteMenuItem.setVisible(true);
534                                             }
535
536                                             // Reset `dismissingSnackbar`.
537                                             dismissingSnackbar = false;
538                                         };
539
540                                         // Enable the delete menu icon after 100 milliseconds to make sure that the previous domain has been deleted from the database.
541                                         Handler handler = new Handler();
542                                         handler.postDelayed(enableDeleteMenuItemRunnable, 100);
543                                     }
544
545                                     // Close the activity if back was pressed.
546                                     if (closeActivityAfterDismissingSnackbar) {
547                                         // Go home.
548                                         NavUtils.navigateUpFromSameTask(activity);
549                                     }
550                                 }
551                             }
552                         });
553
554                 // Show the Snackbar.
555                 undoDeleteSnackbar.show();
556                 break;
557         }
558
559         // Consume the event.
560         return true;
561     }
562
563     @Override
564     protected void onSaveInstanceState(@NonNull Bundle outState) {
565         // Store the current `DomainSettingsFragment` state in `outState`.
566         if (findViewById(R.id.domain_settings_scrollview) != null) {  // `DomainSettingsFragment` is displayed.
567             // Save any changes that have been made to the domain settings.
568             saveDomainSettings(coordinatorLayout, resources);
569
570             // Store `DomainSettingsDisplayed`.
571             outState.putBoolean("domain_settings_displayed", true);
572             outState.putInt("domain_settings_database_id", DomainSettingsFragment.databaseId);
573         } else {  // `DomainSettingsFragment` is not displayed.
574             outState.putBoolean("domain_settings_displayed", false);
575             outState.putInt("domain_settings_database_id", -1);
576         }
577
578         super.onSaveInstanceState(outState);
579     }
580
581     // Control what the navigation bar back button does.
582     @Override
583     public void onBackPressed() {
584         // Get a handle for the fragment manager.
585         FragmentManager fragmentManager = getSupportFragmentManager();
586
587         if (twoPanedMode) {  // The device is in two-paned mode.
588             // Save the current domain settings if the domain settings fragment is displayed.
589             if (findViewById(R.id.domain_settings_scrollview) != null) {
590                 saveDomainSettings(coordinatorLayout, resources);
591             }
592
593             // Dismiss the undo delete SnackBar if it is shown.
594             if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
595                 // Set the close flag.
596                 closeActivityAfterDismissingSnackbar = true;
597
598                 // Dismiss the snackbar.
599                 undoDeleteSnackbar.dismiss();
600             } else {
601                 // Pass `onBackPressed()` to the system.
602                 super.onBackPressed();
603             }
604         } else if (closeOnBack) {  // Go directly back to the main WebView activity because the domains activity was launched from the options menu.
605             // Save the current domain settings.
606             saveDomainSettings(coordinatorLayout, resources);
607
608             // Pass `onBackPressed()` to the system.
609             super.onBackPressed();
610         } else if (findViewById(R.id.domain_settings_scrollview) != null) {  // The device is in single-paned mode and domain settings fragment is displayed.
611             // Save the current domain settings.
612             saveDomainSettings(coordinatorLayout, resources);
613
614             // Display the domains list fragment.
615             DomainsListFragment domainsListFragment = new DomainsListFragment();
616             fragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
617             fragmentManager.executePendingTransactions();
618
619             // Populate the list of domains.  `-1` highlights the first domain if in two-paned mode.  It has no effect in single-paned mode.
620             populateDomainsListView(-1);
621
622             // Show the add domain floating action button.
623             addDomainFAB.show();
624
625             // Hide the delete menu item.
626             deleteMenuItem.setVisible(false);
627         } else {  // The device is in single-paned mode and the domain list fragment is displayed.
628             // Dismiss the undo delete SnackBar if it is shown.
629             if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
630                 // Set the close flag.
631                 closeActivityAfterDismissingSnackbar = true;
632
633                 // Dismiss the snackbar.
634                 undoDeleteSnackbar.dismiss();
635             } else {
636                 // Pass `onBackPressed()` to the system.
637                 super.onBackPressed();
638             }
639         }
640     }
641
642     @Override
643     public void onAddDomain(DialogFragment dialogFragment) {
644         // Dismiss the undo delete snackbar if it is currently displayed.
645         if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
646             undoDeleteSnackbar.dismiss();
647         }
648
649         // Remove the incorrect lint warning below that the dialog might be null.
650         assert dialogFragment.getDialog() != null;
651
652         // Get a handle for the domain name edit text.
653         EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
654
655         // Get the domain name string.
656         String domainNameString = domainNameEditText.getText().toString();
657
658         // Create the domain and store the database ID in `currentDomainDatabaseId`.
659         currentDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
660
661         // Display the newly created domain.
662         if (twoPanedMode) {  // The device in in two-paned mode.
663             populateDomainsListView(currentDomainDatabaseId);
664         } else {  // The device is in single-paned mode.
665             // Hide the add domain floating action button.
666             addDomainFAB.hide();
667
668             // Show and enable `deleteMenuItem`.
669             DomainsActivity.deleteMenuItem.setVisible(true);
670
671             // Add the current domain database ID to the arguments bundle.
672             Bundle argumentsBundle = new Bundle();
673             argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
674
675             // Add and arguments bundle to the domain setting fragment.
676             DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
677             domainSettingsFragment.setArguments(argumentsBundle);
678
679             // Display the domain settings fragment.
680             getSupportFragmentManager().beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
681         }
682     }
683
684     public void saveDomainSettings(View view, Resources resources) {
685         // Get handles for the domain settings.
686         EditText domainNameEditText = view.findViewById(R.id.domain_settings_name_edittext);
687         Switch javaScriptSwitch = view.findViewById(R.id.javascript_switch);
688         Switch firstPartyCookiesSwitch = view.findViewById(R.id.first_party_cookies_switch);
689         Switch thirdPartyCookiesSwitch = view.findViewById(R.id.third_party_cookies_switch);
690         Switch domStorageSwitch = view.findViewById(R.id.dom_storage_switch);
691         Switch formDataSwitch = view.findViewById(R.id.form_data_switch);  // Form data can be removed once the minimum API >= 26.
692         Switch easyListSwitch = view.findViewById(R.id.easylist_switch);
693         Switch easyPrivacySwitch = view.findViewById(R.id.easyprivacy_switch);
694         Switch fanboysAnnoyanceSwitch = view.findViewById(R.id.fanboys_annoyance_list_switch);
695         Switch fanboysSocialBlockingSwitch = view.findViewById(R.id.fanboys_social_blocking_list_switch);
696         Switch ultraListSwitch = view.findViewById(R.id.ultralist_switch);
697         Switch ultraPrivacySwitch = view.findViewById(R.id.ultraprivacy_switch);
698         Switch blockAllThirdPartyRequestsSwitch = view.findViewById(R.id.block_all_third_party_requests_switch);
699         Spinner userAgentSpinner = view.findViewById(R.id.user_agent_spinner);
700         EditText customUserAgentEditText = view.findViewById(R.id.custom_user_agent_edittext);
701         Spinner fontSizeSpinner = view.findViewById(R.id.font_size_spinner);
702         EditText customFontSizeEditText = view.findViewById(R.id.custom_font_size_edittext);
703         Spinner swipeToRefreshSpinner = view.findViewById(R.id.swipe_to_refresh_spinner);
704         Spinner nightModeSpinner = view.findViewById(R.id.night_mode_spinner);
705         Spinner wideViewportSpinner = view.findViewById(R.id.wide_viewport_spinner);
706         Spinner displayWebpageImagesSpinner = view.findViewById(R.id.display_webpage_images_spinner);
707         Switch pinnedSslCertificateSwitch = view.findViewById(R.id.pinned_ssl_certificate_switch);
708         RadioButton currentWebsiteCertificateRadioButton = view.findViewById(R.id.current_website_certificate_radiobutton);
709         Switch pinnedIpAddressesSwitch = view.findViewById(R.id.pinned_ip_addresses_switch);
710         RadioButton currentIpAddressesRadioButton = view.findViewById(R.id.current_ip_addresses_radiobutton);
711
712         // Extract the data for the domain settings.
713         String domainNameString = domainNameEditText.getText().toString();
714         boolean javaScript = javaScriptSwitch.isChecked();
715         boolean firstPartyCookies = firstPartyCookiesSwitch.isChecked();
716         boolean thirdPartyCookies = thirdPartyCookiesSwitch.isChecked();
717         boolean domStorage  = domStorageSwitch.isChecked();
718         boolean formData = formDataSwitch.isChecked();  // Form data can be removed once the minimum API >= 26.
719         boolean easyList = easyListSwitch.isChecked();
720         boolean easyPrivacy = easyPrivacySwitch.isChecked();
721         boolean fanboysAnnoyance = fanboysAnnoyanceSwitch.isChecked();
722         boolean fanboysSocialBlocking = fanboysSocialBlockingSwitch.isChecked();
723         boolean ultraList = ultraListSwitch.isChecked();
724         boolean ultraPrivacy = ultraPrivacySwitch.isChecked();
725         boolean blockAllThirdPartyRequests = blockAllThirdPartyRequestsSwitch.isChecked();
726         int userAgentSwitchPosition = userAgentSpinner.getSelectedItemPosition();
727         int fontSizeSwitchPosition = fontSizeSpinner.getSelectedItemPosition();
728         int swipeToRefreshInt = swipeToRefreshSpinner.getSelectedItemPosition();
729         int nightModeInt = nightModeSpinner.getSelectedItemPosition();
730         int wideViewportInt = wideViewportSpinner.getSelectedItemPosition();
731         int displayWebpageImagesInt = displayWebpageImagesSpinner.getSelectedItemPosition();
732         boolean pinnedSslCertificate = pinnedSslCertificateSwitch.isChecked();
733         boolean pinnedIpAddress = pinnedIpAddressesSwitch.isChecked();
734
735         // Initialize the user agent name string.
736         String userAgentName;
737
738         // Set the user agent name.
739         switch (userAgentSwitchPosition) {
740             case MainWebViewActivity.DOMAINS_SYSTEM_DEFAULT_USER_AGENT:
741                 // Set the user agent name to be `System default user agent`.
742                 userAgentName = resources.getString(R.string.system_default_user_agent);
743                 break;
744
745             case MainWebViewActivity.DOMAINS_CUSTOM_USER_AGENT:
746                 // Set the user agent name to be the custom user agent.
747                 userAgentName = customUserAgentEditText.getText().toString();
748                 break;
749
750             default:
751                 // Get the array of user agent names.
752                 String[] userAgentNameArray = resources.getStringArray(R.array.user_agent_names);
753
754                 // 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.
755                 userAgentName = userAgentNameArray[userAgentSwitchPosition - 1];
756         }
757
758         // Initialize the font size integer.  `0` indicates the system default font size.
759         int fontSizeInt = 0;
760
761         // Use a custom font size if it is selected.
762         if (fontSizeSwitchPosition == 1) {  // A custom font size is specified.
763             // Get the custom font size from the edit text.
764             fontSizeInt = Integer.parseInt(customFontSizeEditText.getText().toString());
765         }
766
767         // Save the domain settings.
768         domainsDatabaseHelper.updateDomain(DomainsActivity.currentDomainDatabaseId, domainNameString, javaScript, firstPartyCookies, thirdPartyCookies, domStorage, formData, easyList, easyPrivacy,
769                 fanboysAnnoyance, fanboysSocialBlocking, ultraList, ultraPrivacy, blockAllThirdPartyRequests, userAgentName, fontSizeInt, swipeToRefreshInt, nightModeInt, wideViewportInt,
770                 displayWebpageImagesInt, pinnedSslCertificate, pinnedIpAddress);
771
772         // Update the pinned SSL certificate if a new one is checked.
773         if (currentWebsiteCertificateRadioButton.isChecked()) {
774             // Update the database.
775             domainsDatabaseHelper.updatePinnedSslCertificate(currentDomainDatabaseId, sslIssuedToCName, sslIssuedToOName, sslIssuedToUName, sslIssuedByCName, sslIssuedByOName, sslIssuedByUName,
776                     sslStartDateLong, sslEndDateLong);
777         }
778
779         // Update the pinned IP addresses if new ones are checked.
780         if (currentIpAddressesRadioButton.isChecked()) {
781             // Update the database.
782             domainsDatabaseHelper.updatePinnedIpAddresses(currentDomainDatabaseId, currentIpAddresses);
783         }
784     }
785
786     private void populateDomainsListView(final int highlightedDomainDatabaseId) {
787         // get a handle for the current `domains_listview`.
788         domainsListView = findViewById(R.id.domains_listview);
789
790         // Get a `Cursor` with the current contents of the domains database.
791         Cursor domainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
792
793         // Setup `domainsCursorAdapter` with `this` context.  `false` disables `autoRequery`.
794         CursorAdapter domainsCursorAdapter = new CursorAdapter(getApplicationContext(), domainsCursor, false) {
795             @Override
796             public View newView(Context context, Cursor cursor, ViewGroup parent) {
797                 // Inflate the individual item layout.  `false` does not attach it to the root.
798                 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
799             }
800
801             @Override
802             public void bindView(View view, Context context, Cursor cursor) {
803                 // Set the domain name.
804                 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
805                 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
806                 domainNameTextView.setText(domainNameString);
807             }
808         };
809
810         // Update the list view.
811         domainsListView.setAdapter(domainsCursorAdapter);
812
813         // Display the domain settings in the second pane if operating in two pane mode and the database contains at least one domain.
814         if (DomainsActivity.twoPanedMode && (domainsCursor.getCount() > 0)) {  // Two-paned mode is enabled and there is at least one domain.
815             // Initialize `highlightedDomainPosition`.
816             int highlightedDomainPosition = 0;
817
818             // Get the cursor position for the highlighted domain.
819             for (int i = 0; i < domainsCursor.getCount(); i++) {
820                 // Move to position `i` in the cursor.
821                 domainsCursor.moveToPosition(i);
822
823                 // Get the database ID for this position.
824                 int currentDatabaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
825
826                 // Set `highlightedDomainPosition` if the database ID for this matches `highlightedDomainDatabaseId`.
827                 if (highlightedDomainDatabaseId == currentDatabaseId) {
828                     highlightedDomainPosition = i;
829                 }
830             }
831
832             // Select the highlighted domain.
833             domainsListView.setItemChecked(highlightedDomainPosition, true);
834
835             // Get the database ID for the highlighted domain.
836             domainsCursor.moveToPosition(highlightedDomainPosition);
837             currentDomainDatabaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
838
839             // Store the database ID in the arguments bundle.
840             Bundle argumentsBundle = new Bundle();
841             argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
842
843             // Add and arguments bundle to the domain settings fragment.
844             DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
845             domainSettingsFragment.setArguments(argumentsBundle);
846
847             // Display the domain settings fragment.
848             getSupportFragmentManager().beginTransaction().replace(R.id.domain_settings_fragment_container, domainSettingsFragment).commit();
849
850             // Enable the delete options menu items.
851             deleteMenuItem.setEnabled(true);
852
853             // Get a handle for the shared preferences.
854             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
855
856             // Get the theme and screenshot preferences.
857             boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
858
859             // Set the delete icon according to the theme.
860             if (darkTheme) {
861                 deleteMenuItem.setIcon(R.drawable.delete_dark);
862             } else {
863                 deleteMenuItem.setIcon(R.drawable.delete_light);
864             }
865         } else if (twoPanedMode) {  // Two-paned mode is enabled but there are no domains.
866             // Disable the options `MenuItems`.
867             deleteMenuItem.setEnabled(false);
868             deleteMenuItem.setIcon(R.drawable.delete_blue);
869         }
870     }
871
872     @Override
873     public void dismissSnackbar() {
874         // Dismiss the undo delete snackbar if it is shown.
875         if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
876             // Dismiss the snackbar.
877             undoDeleteSnackbar.dismiss();
878         }
879     }
880
881     @Override
882     public void onDestroy() {
883         // Close the domains database helper.
884         domainsDatabaseHelper.close();
885
886         // Run the default commands.
887         super.onDestroy();
888     }
889 }