/*
- * Copyright 2016-2017 Soren Stoutner <soren@stoutner.com>.
+ * Copyright © 2016-2019 Soren Stoutner <soren@stoutner.com>.
*
* This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
*
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
+import android.content.SharedPreferences;
import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
-import android.support.annotation.NonNull;
-import android.support.v4.content.ContextCompat;
-// We have to use `AppCompatDialogFragment` instead of `DialogFragment` or an error is produced on API <= 22. `android.support.v7.app.AlertDialog` also uses more of the horizontal screen real estate versus `android.app.AlertDialog's` smaller width.
-import android.support.v7.app.AppCompatDialogFragment;
-import android.util.Base64;
+import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
+import android.view.WindowManager;
import android.webkit.WebBackForwardList;
import android.widget.AdapterView;
import android.widget.ListView;
+import android.widget.TextView;
+
+import androidx.annotation.NonNull;
+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 com.stoutner.privacybrowser.R;
+import com.stoutner.privacybrowser.activities.MainWebViewActivity;
import com.stoutner.privacybrowser.adapters.HistoryArrayAdapter;
import com.stoutner.privacybrowser.definitions.History;
+import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
+import com.stoutner.privacybrowser.views.NestedScrollWebView;
-import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
-public class UrlHistoryDialog extends AppCompatDialogFragment{
+public class UrlHistoryDialog extends DialogFragment{
+ // The public interface is used to send information back to the parent activity.
+ public interface NavigateHistoryListener {
+ void navigateHistory(String url, int steps);
+ }
+
+ // The navigate history listener is used in `onAttach()` and `onCreateDialog()`.
+ private NavigateHistoryListener navigateHistoryListener;
+
+ @Override
+ public void onAttach(@NonNull Context context) {
+ // Run the default commands.
+ super.onAttach(context);
- // `historyArrayList` and `currentPageId` pass information from `onCreate()` to `onCreateDialog()`.
- private ArrayList<History> historyArrayList = new ArrayList<>();
- private int currentPageId;
+ // Get a handle for the listener from the launching context.
+ navigateHistoryListener = (NavigateHistoryListener) context;
+ }
- public static UrlHistoryDialog loadBackForwardList(Context context, WebBackForwardList webBackForwardList) {
- // Create `argumentsBundle`.
+ public static UrlHistoryDialog loadBackForwardList(long webViewFragmentId) {
+ // Create an arguments bundle.
Bundle argumentsBundle = new Bundle();
- // Store `currentPageIndex`.
- int currentPageIndex = webBackForwardList.getCurrentIndex();
+ // Store the WebView fragment ID in the bundle.
+ argumentsBundle.putLong("webview_fragment_id", webViewFragmentId);
- // Setup `urlArrayList` and `iconArrayList`.
- ArrayList<String> urlArrayList = new ArrayList<>();
- ArrayList<String> iconBase64StringArrayList = new ArrayList<>();
+ // Create a new instance of the URL history dialog.
+ UrlHistoryDialog urlHistoryDialog = new UrlHistoryDialog();
- // Get the default favorite icon `Drawable`.
- Drawable defaultFavoriteIconDrawable = ContextCompat.getDrawable(context, R.drawable.world);
+ // Add the arguments bundle to this instance.
+ urlHistoryDialog.setArguments(argumentsBundle);
- // Convert `defaultFavoriteIconDrawable` to a `BitmapDrawable`.
- BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
+ // Return the new URL history dialog.
+ return urlHistoryDialog;
+ }
- // Extract a `Bitmap` from `defaultFavoriteIconBitmapDrawable`.
- Bitmap defaultFavoriteIcon = defaultFavoriteIconBitmapDrawable.getBitmap();
+ @Override
+ @NonNull
+ // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
+ @SuppressLint("InflateParams")
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ // Remove the incorrect lint warning that `getActivity()` might be null.
+ assert getActivity() != null;
- // Populate `urlArrayList` and `iconArrayList` from `webBackForwardList`.
- for (int i=0; i < webBackForwardList.getSize(); i++) {
- // Store the URL.
- urlArrayList.add(webBackForwardList.getItemAtIndex(i).getUrl());
+ // Get the activity's layout inflater.
+ LayoutInflater layoutInflater = getActivity().getLayoutInflater();
- // Create a variable to store the icon `Bitmap`.
- Bitmap iconBitmap;
+ // Get the arguments.
+ Bundle arguments = getArguments();
- // Store the icon `Bitmap`.
- if (webBackForwardList.getItemAtIndex(i).getFavicon() == null) {
- // If `webBackForwardList` does not have a favorite icon, use Privacy Browser's default world icon.
- iconBitmap = defaultFavoriteIcon;
- } else { // Get the icon from `webBackForwardList`.
- iconBitmap = webBackForwardList.getItemAtIndex(i).getFavicon();
- }
+ // Remove the incorrect lint error that arguments might be null.
+ assert arguments != null;
- // Create a `ByteArrayOutputStream`.
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ // Get the WebView fragment ID from the arguments.
+ long webViewFragmentId = arguments.getLong("webview_fragment_id");
- // Convert the favorite icon `Bitmap` to a `ByteArrayOutputStream`. `100` is the compression quality, which is ignored by `PNG`.
- iconBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
+ // Get the current position of this WebView fragment.
+ int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(webViewFragmentId);
- // Convert the favorite icon `ByteArrayOutputStream` to a `byte[]`.
- byte[] byteArray = byteArrayOutputStream.toByteArray();
+ // Get the WebView tab fragment.
+ WebViewTabFragment webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition);
- // Encode the favorite icon `byte[]` as a Base64 `String`.
- String iconBase64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
+ // Get the fragment view.
+ View fragmentView = webViewTabFragment.getView();
- // Store the favorite icon Base64 `String` in `iconBase64StringArrayList`.
- iconBase64StringArrayList.add(iconBase64String);
- }
+ // Remove the incorrect lint warning below that the fragment view might be null.
+ assert fragmentView != null;
- // Store the variables in the `Bundle`.
- argumentsBundle.putInt("Current_Page", currentPageIndex);
- argumentsBundle.putStringArrayList("URL_History", urlArrayList);
- argumentsBundle.putStringArrayList("Favorite_Icons", iconBase64StringArrayList);
+ // Get a handle for the current WebView.
+ NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
- // Add `argumentsBundle` to this instance of `UrlHistoryDialog`.
- UrlHistoryDialog thisUrlHistoryDialog = new UrlHistoryDialog();
- thisUrlHistoryDialog.setArguments(argumentsBundle);
- return thisUrlHistoryDialog;
- }
+ // Get the web back forward list from the WebView.
+ WebBackForwardList webBackForwardList = nestedScrollWebView.copyBackForwardList();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
+ // Store the current page index.
+ int currentPageIndex = webBackForwardList.getCurrentIndex();
- // Get the `ArrayLists` from the `Arguments`.
- ArrayList<String> urlStringArrayList = getArguments().getStringArrayList("URL_History");
- ArrayList<String> favoriteIconBase64StringArrayList = getArguments().getStringArrayList("Favorite_Icons");
+ // Remove the lint warning below that `getContext()` might be null.
+ assert getContext() != null;
- // Remove the lint warning below that the `ArrayLists` might be `null`.
- assert urlStringArrayList != null;
- assert favoriteIconBase64StringArrayList != null;
+ // Get the default favorite icon drawable. `ContextCompat` must be used until the minimum API >= 21.
+ Drawable defaultFavoriteIconDrawable = ContextCompat.getDrawable(getContext(), R.drawable.world);
- // Populate `historyArrayList`. We go down from `urlStringArrayList.size()` so that the newest entries are at the top. `-1` is needed because `historyArrayList` is zero-based.
- for (int i=urlStringArrayList.size() -1; i >= 0; i--) {
- // Decode the favorite icon Base64 `String` to a `byte[]`.
- byte[] favoriteIconByteArray = Base64.decode(favoriteIconBase64StringArrayList.get(i), Base64.DEFAULT);
+ // Convert the default favorite icon drawable to a `BitmapDrawable`.
+ BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
- // Convert the favorite icon `byte[]` to a `Bitmap`. `0` is the starting offset.
- Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
+ // Remove the incorrect lint error that `getBitmap()` might be null.
+ assert defaultFavoriteIconBitmapDrawable != null;
- // Store the favorite icon and the URL in `historyEntry`.
- History historyEntry = new History(favoriteIconBitmap, urlStringArrayList.get(i));
+ // Extract a bitmap from the default favorite icon bitmap drawable.
+ Bitmap defaultFavoriteIcon = defaultFavoriteIconBitmapDrawable.getBitmap();
- // Add this history entry to `historyArrayList`.
- historyArrayList.add(historyEntry);
- }
+ // Create a history array list.
+ ArrayList<History> historyArrayList = new ArrayList<>();
- // Get the original current page ID.
- int originalCurrentPageId = getArguments().getInt("Current_Page");
+ // Populate the history array list, descending from the end of the list so that the newest entries are at the top. `-1` is needed because the history array list is zero-based.
+ for (int i=webBackForwardList.getSize() -1; i >= 0; i--) {
+ // Create a variable to store the favorite icon bitmap.
+ Bitmap favoriteIconBitmap;
- // Subtract `originalCurrentPageId` from the array size because we reversed the order of the array so that the newest entries are at the top. `-1` is needed because the array is zero-based.
- currentPageId = urlStringArrayList.size() - 1 - originalCurrentPageId;
- }
+ // Determine the favorite icon bitmap
+ if (webBackForwardList.getItemAtIndex(i).getFavicon() == null) {
+ // If the web back forward list does not have a favorite icon, use Privacy Browser's default world icon.
+ favoriteIconBitmap = defaultFavoriteIcon;
+ } else { // Use the icon from the web back forward list.
+ favoriteIconBitmap = webBackForwardList.getItemAtIndex(i).getFavicon();
+ }
- // The public interface is used to send information back to the parent activity.
- public interface UrlHistoryListener {
- // Send back the number of steps to move forward or back.
- void onUrlHistoryEntrySelected(int moveBackOrForwardSteps);
+ // Store the favorite icon and the URL in history entry.
+ History historyEntry = new History(favoriteIconBitmap, webBackForwardList.getItemAtIndex(i).getUrl());
- // Clear the history.
- void onClearHistory();
- }
+ // Add this history entry to the history array list.
+ historyArrayList.add(historyEntry);
+ }
- // `urlHistoryListener` is used in `onAttach()` and `onCreateDialog()`.
- private UrlHistoryListener urlHistoryListener;
+ // Subtract the original current page ID from the array size because the order of the array is reversed so that the newest entries are at the top. `-1` is needed because the array is zero-based.
+ int currentPageId = webBackForwardList.getSize() - 1 - currentPageIndex;
- @Override
- public void onAttach(Context context) {
- super.onAttach(context);
+ // Use an alert dialog builder to create the alert dialog.
+ AlertDialog.Builder dialogBuilder;
- // Check to make sure tha the parent activity implements the listener.
- try {
- urlHistoryListener = (UrlHistoryListener) context;
- } catch (ClassCastException exception) {
- throw new ClassCastException(context.toString() + " must implement UrlHistoryListener.");
- }
- }
+ // Get a handle for the shared preferences.
+ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
- @Override
- @NonNull
- // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
- @SuppressLint("InflateParams")
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- // Get the activity's layout inflater.
- LayoutInflater layoutInflater = getActivity().getLayoutInflater();
+ // Get the screenshot and theme preferences.
+ boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
+ boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
- // Use `AlertDialog.Builder` to create the `AlertDialog`. `R.style.lightAlertDialog` formats the color of the button text.
- AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.LightAlertDialog);
+ // Set the style according to the theme.
+ if (darkTheme) {
+ dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
+ } else {
+ dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
+ }
// Set the title.
dialogBuilder.setTitle(R.string.history);
// Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
dialogBuilder.setView(layoutInflater.inflate(R.layout.url_history_dialog, null));
- // Set an `onClick()` listener on the negative button.
- dialogBuilder.setNegativeButton(R.string.clear_history, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // Clear the history.
- urlHistoryListener.onClearHistory();
- }
+ // Setup the clear history button.
+ dialogBuilder.setNegativeButton(R.string.clear_history, (DialogInterface dialog, int which) -> {
+ // Clear the history.
+ nestedScrollWebView.clearHistory();
});
// Set an `onClick()` listener on the positive button.
- dialogBuilder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // Do nothing if `Close` is clicked. The `Dialog` will automatically close.
- }
+ dialogBuilder.setPositiveButton(R.string.close, (DialogInterface dialog, int which) -> {
+ // Do nothing if `Close` is clicked. The `Dialog` will automatically close.
});
- // Create an `AlertDialog` from the `AlertDialog.Builder`.
+ // Create an alert dialog from the alert dialog builder.
final AlertDialog alertDialog = dialogBuilder.create();
- // We need to show `alertDialog` before we can modify the contents.
- alertDialog.show();
+ // Disable screenshots if not allowed.
+ if (!allowScreenshots) {
+ // Remove the warning below that `getWindow()` might be null.
+ assert alertDialog.getWindow() != null;
- // Instantiate a `HistoryArrayAdapter`.
- final HistoryArrayAdapter historyArrayAdapter = new HistoryArrayAdapter(getContext(), historyArrayList, currentPageId);
+ // Disable screenshots.
+ alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
+ }
+
+ //The alert dialog must be shown before the contents can be modified.
+ alertDialog.show();
- // Get a handle for `listView`.
- ListView listView = (ListView) alertDialog.findViewById(R.id.history_listview);
+ // Instantiate a history array adapter.
+ HistoryArrayAdapter historyArrayAdapter = new HistoryArrayAdapter(getContext(), historyArrayList, currentPageId);
- // Remove the warning below that `listView` might be `null`.
- assert listView != null;
+ // Get a handle for the list view.
+ ListView listView = alertDialog.findViewById(R.id.history_listview);
- // Set the adapter on `listView`.
+ // Set the list view adapter.
listView.setAdapter(historyArrayAdapter);
- // Listen for clicks on entries in `listView`.
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- // Convert the `long` `id` to an `int`.
- int itemId = (int) id;
+ // Listen for clicks on entries in the list view.
+ listView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
+ // Convert the long ID to an int.
+ int itemId = (int) id;
- // Only enable the click if it is not on the `currentPageId`.
- if (itemId != currentPageId) {
- // Get the history entry for this `itemId`.
- History historyEntry = historyArrayAdapter.getItem(itemId);
+ // Only consume the click if it is not on the `currentPageId`.
+ if (itemId != currentPageId) {
+ // Get a handle for the URL text view.
+ TextView urlTextView = view.findViewById(R.id.history_url_textview);
- // Remove the lint warning below that `historyEntry` might be `null`.
- assert historyEntry != null;
+ // Get the URL.
+ String url = urlTextView.getText().toString();
- // Send the history entry URL to be loaded in `mainWebView`.
- urlHistoryListener.onUrlHistoryEntrySelected(currentPageId - itemId);
+ // Invoke the navigate history listener in the calling activity. These commands cannot be run here because they need access to `applyDomainSettings()`.
+ navigateHistoryListener.navigateHistory(url, currentPageId - itemId);
- // Dismiss the `Dialog`.
- alertDialog.dismiss();
- }
+ // Dismiss the alert dialog.
+ alertDialog.dismiss();
}
});
- // `onCreateDialog` requires the return of an `AlertDialog`.
+ // Return the alert dialog.
return alertDialog;
}
}
\ No newline at end of file