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