2 * Copyright © 2016-2019 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.dialogs;
22 import android.annotation.SuppressLint;
23 import android.app.AlertDialog;
24 import android.app.Dialog;
25 import android.content.Context;
26 import android.content.DialogInterface;
27 import android.graphics.Bitmap;
28 import android.graphics.BitmapFactory;
29 import android.graphics.drawable.BitmapDrawable;
30 import android.graphics.drawable.Drawable;
31 import android.os.Bundle;
32 import android.util.Base64;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.webkit.WebBackForwardList;
37 import android.widget.AdapterView;
38 import android.widget.ListView;
40 import androidx.annotation.NonNull;
41 import androidx.core.content.ContextCompat;
42 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
44 import com.stoutner.privacybrowser.R;
45 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
46 import com.stoutner.privacybrowser.adapters.HistoryArrayAdapter;
47 import com.stoutner.privacybrowser.definitions.History;
49 import java.io.ByteArrayOutputStream;
50 import java.util.ArrayList;
52 public class UrlHistoryDialog extends DialogFragment{
54 // `historyArrayList` and `currentPageId` pass information from `onCreate()` to `onCreateDialog()`.
55 private final ArrayList<History> historyArrayList = new ArrayList<>();
56 private int currentPageId;
58 public static UrlHistoryDialog loadBackForwardList(Context context, WebBackForwardList webBackForwardList) {
59 // Create an arguments bundle.
60 Bundle argumentsBundle = new Bundle();
62 // Store the current page index.
63 int currentPageIndex = webBackForwardList.getCurrentIndex();
65 // Setup the URL array list and the icon array list.
66 ArrayList<String> urlArrayList = new ArrayList<>();
67 ArrayList<String> iconBase64StringArrayList = new ArrayList<>();
69 // Get the default favorite icon drawable. `ContextCompat` must be used until the minimum API >= 21.
70 Drawable defaultFavoriteIconDrawable = ContextCompat.getDrawable(context, R.drawable.world);
72 // Convert the default favorite icon drawable to a `BitmapDrawable`.
73 BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
75 // Remove the incorrect lint error that `getBitmap()` might be null.
76 assert defaultFavoriteIconBitmapDrawable != null;
78 // Extract a `Bitmap` from the default favorite icon `BitmapDrawable`.
79 Bitmap defaultFavoriteIcon = defaultFavoriteIconBitmapDrawable.getBitmap();
81 // Populate the URL array list and the icon array list from `webBackForwardList`.
82 for (int i=0; i < webBackForwardList.getSize(); i++) {
84 urlArrayList.add(webBackForwardList.getItemAtIndex(i).getUrl());
86 // Create a variable to store the icon bitmap.
89 // Store the icon bitmap.
90 if (webBackForwardList.getItemAtIndex(i).getFavicon() == null) {
91 // If `webBackForwardList` does not have a favorite icon, use Privacy Browser's default world icon.
92 iconBitmap = defaultFavoriteIcon;
93 } else { // Get the icon from `webBackForwardList`.
94 iconBitmap = webBackForwardList.getItemAtIndex(i).getFavicon();
97 // Create a `ByteArrayOutputStream`.
98 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
100 // Remove the incorrect lint error that `compress()` might be null;
101 assert iconBitmap != null;
103 // Convert the favorite icon `Bitmap` to a `ByteArrayOutputStream`. `100` is the compression quality, which is ignored by `PNG`.
104 iconBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
106 // Convert the favorite icon `ByteArrayOutputStream` to a `byte[]`.
107 byte[] byteArray = byteArrayOutputStream.toByteArray();
109 // Encode the favorite icon `byte[]` as a Base64 `String`.
110 String iconBase64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
112 // Store the favorite icon Base64 `String` in `iconBase64StringArrayList`.
113 iconBase64StringArrayList.add(iconBase64String);
116 // Store the variables in the `Bundle`.
117 argumentsBundle.putInt("Current_Page", currentPageIndex);
118 argumentsBundle.putStringArrayList("URL_History", urlArrayList);
119 argumentsBundle.putStringArrayList("Favorite_Icons", iconBase64StringArrayList);
121 // Add the arguments bundle to this instance of `UrlHistoryDialog`.
122 UrlHistoryDialog thisUrlHistoryDialog = new UrlHistoryDialog();
123 thisUrlHistoryDialog.setArguments(argumentsBundle);
124 return thisUrlHistoryDialog;
128 public void onCreate(Bundle savedInstanceState) {
129 super.onCreate(savedInstanceState);
131 // Remove the incorrect lint error that `getArguments()` might be null.
132 assert getArguments() != null;
134 // Get the `ArrayLists` from the `Arguments`.
135 ArrayList<String> urlStringArrayList = getArguments().getStringArrayList("URL_History");
136 ArrayList<String> favoriteIconBase64StringArrayList = getArguments().getStringArrayList("Favorite_Icons");
138 // Remove the lint warning below that the `ArrayLists` might be `null`.
139 assert urlStringArrayList != null;
140 assert favoriteIconBase64StringArrayList != null;
142 // 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.
143 for (int i=urlStringArrayList.size() -1; i >= 0; i--) {
144 // Decode the favorite icon Base64 `String` to a `byte[]`.
145 byte[] favoriteIconByteArray = Base64.decode(favoriteIconBase64StringArrayList.get(i), Base64.DEFAULT);
147 // Convert the favorite icon `byte[]` to a `Bitmap`. `0` is the starting offset.
148 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
150 // Store the favorite icon and the URL in `historyEntry`.
151 History historyEntry = new History(favoriteIconBitmap, urlStringArrayList.get(i));
153 // Add this history entry to `historyArrayList`.
154 historyArrayList.add(historyEntry);
157 // Get the original current page ID.
158 int originalCurrentPageId = getArguments().getInt("Current_Page");
160 // 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.
161 currentPageId = urlStringArrayList.size() - 1 - originalCurrentPageId;
164 // The public interface is used to send information back to the parent activity.
165 public interface UrlHistoryListener {
166 // Send back the number of steps to move forward or back.
167 void onUrlHistoryEntrySelected(int moveBackOrForwardSteps);
169 // Clear the history.
170 void onClearHistory();
173 // `urlHistoryListener` is used in `onAttach()` and `onCreateDialog()`.
174 private UrlHistoryListener urlHistoryListener;
177 public void onAttach(Context context) {
178 super.onAttach(context);
180 // Check to make sure tha the parent activity implements the listener.
182 urlHistoryListener = (UrlHistoryListener) context;
183 } catch (ClassCastException exception) {
184 throw new ClassCastException(context.toString() + " must implement UrlHistoryListener.");
190 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
191 @SuppressLint("InflateParams")
192 public Dialog onCreateDialog(Bundle savedInstanceState) {
193 // Remove the incorrect lint warning that `getActivity()` might be null.
194 assert getActivity() != null;
196 // Get the activity's layout inflater.
197 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
199 // Use an alert dialog builder to create the alert dialog.
200 AlertDialog.Builder dialogBuilder;
202 // Set the style according to the theme.
203 if (MainWebViewActivity.darkTheme) {
204 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
206 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
210 dialogBuilder.setTitle(R.string.history);
212 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
213 dialogBuilder.setView(layoutInflater.inflate(R.layout.url_history_dialog, null));
215 // Set an `onClick()` listener on the negative button.
216 dialogBuilder.setNegativeButton(R.string.clear_history, (DialogInterface dialog, int which) -> {
217 // Clear the history.
218 urlHistoryListener.onClearHistory();
221 // Set an `onClick()` listener on the positive button.
222 dialogBuilder.setPositiveButton(R.string.close, (DialogInterface dialog, int which) -> {
223 // Do nothing if `Close` is clicked. The `Dialog` will automatically close.
226 // Create an alert dialog from the alert dialog builder.
227 final AlertDialog alertDialog = dialogBuilder.create();
229 // Disable screenshots if not allowed.
230 if (!MainWebViewActivity.allowScreenshots) {
231 // Remove the warning below that `getWindow()` might be null.
232 assert alertDialog.getWindow() != null;
234 // Disable screenshots.
235 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
238 //The alert dialog must be shown before the contents can be modified.
241 // Instantiate a `HistoryArrayAdapter`.
242 HistoryArrayAdapter historyArrayAdapter = new HistoryArrayAdapter(getContext(), historyArrayList, currentPageId);
244 // Get a handle for the list view.
245 ListView listView = alertDialog.findViewById(R.id.history_listview);
247 // Set the list view adapter.
248 listView.setAdapter(historyArrayAdapter);
250 // Listen for clicks on entries in the list view.
251 listView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
252 // Convert the long ID to an int.
253 int itemId = (int) id;
255 // Only consume the click if it is not on the `currentPageId`.
256 if (itemId != currentPageId) {
257 // Go forward or back to `itemId`.
258 urlHistoryListener.onUrlHistoryEntrySelected(currentPageId - itemId);
260 // Dismiss the `Dialog`.
261 alertDialog.dismiss();
265 // `onCreateDialog` requires the return of an `AlertDialog`.