]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blobdiff - app/src/main/java/com/stoutner/privacybrowser/dialogs/PinnedMismatchDialog.java
Fix a rare crash in `onBackPresses()`. https://redmine.stoutner.com/issues/651
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / PinnedMismatchDialog.java
index c8a0a78844ebe4e9427fe3641a15f82171cce8f5..9036f9cdf4ac1f0f42c40275ba908575f012169c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2017-2019 Soren Stoutner <soren@stoutner.com>.
+ * Copyright © 2017-2020 Soren Stoutner <soren@stoutner.com>.
  *
  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
  *
 package com.stoutner.privacybrowser.dialogs;
 
 import android.annotation.SuppressLint;
-import android.app.AlertDialog;
 import android.app.Dialog;
 import android.content.Context;
 import android.content.DialogInterface;
+import android.content.SharedPreferences;
+import android.content.res.Configuration;
+import android.graphics.Bitmap;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
 import android.net.http.SslCertificate;
 import android.os.Bundle;
+import android.preference.PreferenceManager;
 import android.text.SpannableStringBuilder;
 import android.text.Spanned;
 import android.text.style.ForegroundColorSpan;
@@ -51,10 +54,17 @@ import java.util.ArrayList;
 import java.util.Date;
 
 import androidx.annotation.NonNull;
+import androidx.appcompat.app.AlertDialog;
+import androidx.core.content.ContextCompat;
 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
 import androidx.viewpager.widget.PagerAdapter;
 
 public class PinnedMismatchDialog extends DialogFragment {
+    // The public interface is used to send information back to the parent activity.
+    public interface PinnedMismatchListener {
+        void pinnedErrorGoBack();
+    }
+
     // Declare the class variables.
     private PinnedMismatchListener pinnedMismatchListener;
     private NestedScrollWebView nestedScrollWebView;
@@ -67,19 +77,12 @@ public class PinnedMismatchDialog extends DialogFragment {
     private Date currentSslStartDate;
     private Date currentSslEndDate;
 
-    // The public interface is used to send information back to the parent activity.
-    public interface PinnedMismatchListener {
-        void onPinnedMismatchBack();
-
-        void onPinnedMismatchProceed();
-    }
-
-    // Check to make sure that the parent activity implements the listener.
-    public void onAttach(Context context) {
+    @Override
+    public void onAttach(@NonNull Context context) {
         // Run the default commands.
         super.onAttach(context);
 
-        // Get a handle for `PinnedSslCertificateMismatchListener` from the launching context.
+        // Get a handle for the listener from the launching context.
         pinnedMismatchListener = (PinnedMismatchListener) context;
     }
 
@@ -87,7 +90,7 @@ public class PinnedMismatchDialog extends DialogFragment {
         // Create an arguments bundle.
         Bundle argumentsBundle = new Bundle();
 
-        // Store the WebView position in the bundle.
+        // Store the WebView fragment ID in the bundle.
         argumentsBundle.putLong("webview_fragment_id", webViewFragmentId);
 
         // Create a new instance of the pinned mismatch dialog.
@@ -100,16 +103,19 @@ public class PinnedMismatchDialog extends DialogFragment {
         return pinnedMismatchDialog;
     }
 
-    // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
+    // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
     @SuppressLint("InflateParams")
     @Override
     @NonNull
     public Dialog onCreateDialog(Bundle savedInstanceState) {
+        // Get the arguments.
+        Bundle arguments = getArguments();
+
         // Remove the incorrect lint warning below that `.getArguments().getInt()` might be null.
-        assert getArguments() != null;
+        assert arguments != null;
 
         // Get the current position of this WebView fragment.
-        int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(getArguments().getLong("webview_fragment_id"));
+        int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(arguments.getLong("webview_fragment_id"));
 
         // Get the WebView tab fragment.
         WebViewTabFragment webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition);
@@ -124,28 +130,43 @@ public class PinnedMismatchDialog extends DialogFragment {
         nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
 
         // Use an alert dialog builder to create the alert dialog.
-        AlertDialog.Builder dialogBuilder;
-
-        // Set the style according to the theme.
-        if (MainWebViewActivity.darkTheme) {
-            // Set the dialog theme.
-            dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
-        } else {
-            // Set the dialog theme.
-            dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
-        }
+        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog);
+
+        // Get the context.
+        Context context = getContext();
+
+        // Remove the incorrect lint warning below that the context might be null.
+        assert context != null;
+
+        // Get the favorite icon.
+        Bitmap favoriteIconBitmap = nestedScrollWebView.getFavoriteOrDefaultIcon();
+
+        // Get the default favorite icon drawable.  `ContextCompat` must be used until API >= 21.
+        Drawable defaultFavoriteIconDrawable = ContextCompat.getDrawable(context, R.drawable.world);
+
+        // Cast the favorite icon drawable to a bitmap drawable.
+        BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
+
+        // Remove the incorrect warning below that the favorite icon bitmap drawable might be null.
+        assert defaultFavoriteIconBitmapDrawable != null;
+
+        // Store the default icon bitmap.
+        Bitmap defaultFavoriteIconBitmap = defaultFavoriteIconBitmapDrawable.getBitmap();
 
         // Set the favorite icon as the dialog icon if it exists.
-        if (MainWebViewActivity.favoriteIconBitmap.equals(MainWebViewActivity.favoriteIconDefaultBitmap)) {  // There is no favorite icon.
+        if (favoriteIconBitmap.sameAs(defaultFavoriteIconBitmap)) {  // There is no website favorite icon.
+            // Get the current theme status.
+            int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
+
             // Set the icon according to the theme.
-            if (MainWebViewActivity.darkTheme) {
-                dialogBuilder.setIcon(R.drawable.ssl_certificate_enabled_dark);
+            if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
+                dialogBuilder.setIcon(R.drawable.ssl_certificate_enabled_night);
             } else {
-                dialogBuilder.setIcon(R.drawable.ssl_certificate_enabled_light);
+                dialogBuilder.setIcon(R.drawable.ssl_certificate_enabled_day);
             }
         } else {  // There is a favorite icon.
             // Create a drawable version of the favorite icon.
-            Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), MainWebViewActivity.favoriteIconBitmap);
+            Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), favoriteIconBitmap);
 
             // Set the icon.
             dialogBuilder.setIcon(favoriteIconDrawable);
@@ -167,7 +188,7 @@ public class PinnedMismatchDialog extends DialogFragment {
             }
 
             // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
-            DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(getContext(), null, null, 0);
+            DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(context, null, null, 0);
 
             // Update the SSL certificate if it is pinned.
             if (nestedScrollWebView.hasPinnedSslCertificate()) {
@@ -190,16 +211,21 @@ public class PinnedMismatchDialog extends DialogFragment {
             }
         });
 
-        // Setup the negative button.
+        // Setup the back button.
         dialogBuilder.setNegativeButton(R.string.back, (DialogInterface dialog, int which) -> {
-            // Call the `onSslMismatchBack` public interface to send the `WebView` back one page.
-            pinnedMismatchListener.onPinnedMismatchBack();
+            if (nestedScrollWebView.canGoBack()) {  // There is a back page in the history.
+                // Invoke the navigate history listener in the calling activity.  These commands cannot be run here because they need access to `applyDomainSettings()`.
+                pinnedMismatchListener.pinnedErrorGoBack();
+            } else {  // There are no pages to go back to.
+                // Load a blank page
+                nestedScrollWebView.loadUrl("");
+            }
         });
 
-        // Setup the positive button.
+        // Setup the proceed button.
         dialogBuilder.setPositiveButton(R.string.proceed, (DialogInterface dialog, int which) -> {
-            // Call the `onSslMismatchProceed` public interface.
-            pinnedMismatchListener.onPinnedMismatchProceed();
+            // Do not check the pinned information for this domain again until the domain changes.
+            nestedScrollWebView.setIgnorePinnedDomainInformation(true);
         });
 
         // Set the title.
@@ -215,8 +241,14 @@ public class PinnedMismatchDialog extends DialogFragment {
         // Create an alert dialog from the alert dialog builder.
         final AlertDialog alertDialog = dialogBuilder.create();
 
+        // Get a handle for the shared preferences.
+        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
+
+        // Get the screenshot preference.
+        boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
+
         // Disable screenshots if not allowed.
-        if (!MainWebViewActivity.allowScreenshots) {
+        if (!allowScreenshots) {
             // Remove the warning below that `getWindow()` might be null.
             assert alertDialog.getWindow() != null;
 
@@ -227,15 +259,21 @@ public class PinnedMismatchDialog extends DialogFragment {
         // Show the alert dialog so the items in the layout can be modified.
         alertDialog.show();
 
-        //  Setup the view pager.
+        //  Get a handle for the views.
         WrapVerticalContentViewPager wrapVerticalContentViewPager = alertDialog.findViewById(R.id.pinned_ssl_certificate_mismatch_viewpager);
+        TabLayout tabLayout = alertDialog.findViewById(R.id.pinned_ssl_certificate_mismatch_tablayout);
+
+        // Remove the incorrect lint warning below that the views might be null.
+        assert wrapVerticalContentViewPager != null;
+        assert tabLayout != null;
+
+        // Set the view pager adapter.
         wrapVerticalContentViewPager.setAdapter(new pagerAdapter());
 
-        // Setup the tab layout and connect it to the view pager.
-        TabLayout tabLayout = alertDialog.findViewById(R.id.pinned_ssl_certificate_mismatch_tablayout);
+        // Connect the tab layout to the view pager.
         tabLayout.setupWithViewPager(wrapVerticalContentViewPager);
 
-        // `onCreateDialog()` requires the return of an `AlertDialog`.
+        // Return the alert dialog.
         return alertDialog;
     }
 
@@ -289,8 +327,8 @@ public class PinnedMismatchDialog extends DialogFragment {
             String startDateLabel = getString(R.string.start_date) + "  ";
             String endDateLabel = getString(R.string.end_date) + "  ";
 
-            // Get a URI for the URL.
-            Uri currentUri = Uri.parse(MainWebViewActivity.formattedUrlString);
+            // Convert the URL to a URI.
+            Uri currentUri = Uri.parse(nestedScrollWebView.getUrl());
 
             // Get the current host from the URI.
             String domainName = currentUri.getHost();
@@ -386,19 +424,20 @@ public class PinnedMismatchDialog extends DialogFragment {
                 }
             }
 
-            // Create a red foreground color span.  The deprecated `getResources().getColor` must be used until the minimum API >= 23.
-            @SuppressWarnings("deprecation") ForegroundColorSpan redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
-
-            // Create a blue foreground color span.
+            // Define the color spans.
             ForegroundColorSpan blueColorSpan;
+            ForegroundColorSpan redColorSpan;
 
-            // Set the blue color span according to the theme.  The deprecated `getResources().getColor` must be used until the minimum API >= 23.
-            if (MainWebViewActivity.darkTheme) {
-                //noinspection deprecation
-                blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
-            } else {
-                //noinspection deprecation
+            // Get the current theme status.
+            int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
+
+            // Set the color spans according to the theme.  The deprecated `getResources()` must be used until the minimum API >= 23.
+            if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
                 blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
+                redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
+            } else {
+                blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.violet_700));
+                redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
             }
 
             // Set the domain name to be blue.