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