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