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