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