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.content.SharedPreferences;
28 import android.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.os.Bundle;
33 import android.preference.PreferenceManager;
34 import android.util.Base64;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.webkit.WebBackForwardList;
39 import android.widget.AdapterView;
40 import android.widget.ListView;
42 import androidx.annotation.NonNull;
43 import androidx.core.content.ContextCompat;
44 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
46 import com.stoutner.privacybrowser.R;
47 import com.stoutner.privacybrowser.adapters.HistoryArrayAdapter;
48 import com.stoutner.privacybrowser.definitions.History;
50 import java.io.ByteArrayOutputStream;
51 import java.util.ArrayList;
53 public class UrlHistoryDialog extends DialogFragment{
54 // Declare the class variables.
55 private final ArrayList<History> historyArrayList = new ArrayList<>();
56 private int currentPageId;
58 // Create a URL history listener.
59 private UrlHistoryListener urlHistoryListener;
62 // The public interface is used to send information back to the parent activity.
63 public interface UrlHistoryListener {
64 // Send back the number of steps to move forward or back.
65 void onUrlHistoryEntrySelected(int moveBackOrForwardSteps);
68 void onClearHistory();
72 public void onAttach(Context context) {
73 super.onAttach(context);
75 // Check to make sure tha the parent activity implements the listener.
77 urlHistoryListener = (UrlHistoryListener) context;
78 } catch (ClassCastException exception) {
79 throw new ClassCastException(context.toString() + " must implement UrlHistoryListener.");
84 public static UrlHistoryDialog loadBackForwardList(Context context, WebBackForwardList webBackForwardList) {
85 // Create an arguments bundle.
86 Bundle argumentsBundle = new Bundle();
88 // Store the current page index.
89 int currentPageIndex = webBackForwardList.getCurrentIndex();
91 // Setup the URL array list and the icon array list.
92 ArrayList<String> urlArrayList = new ArrayList<>();
93 ArrayList<String> iconBase64StringArrayList = new ArrayList<>();
95 // Get the default favorite icon drawable. `ContextCompat` must be used until the minimum API >= 21.
96 Drawable defaultFavoriteIconDrawable = ContextCompat.getDrawable(context, R.drawable.world);
98 // Convert the default favorite icon drawable to a `BitmapDrawable`.
99 BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
101 // Remove the incorrect lint error that `getBitmap()` might be null.
102 assert defaultFavoriteIconBitmapDrawable != null;
104 // Extract a `Bitmap` from the default favorite icon `BitmapDrawable`.
105 Bitmap defaultFavoriteIcon = defaultFavoriteIconBitmapDrawable.getBitmap();
107 // Populate the URL array list and the icon array list from `webBackForwardList`.
108 for (int i=0; i < webBackForwardList.getSize(); i++) {
110 urlArrayList.add(webBackForwardList.getItemAtIndex(i).getUrl());
112 // Create a variable to store the icon bitmap.
115 // Store the icon bitmap.
116 if (webBackForwardList.getItemAtIndex(i).getFavicon() == null) {
117 // If `webBackForwardList` does not have a favorite icon, use Privacy Browser's default world icon.
118 iconBitmap = defaultFavoriteIcon;
119 } else { // Get the icon from `webBackForwardList`.
120 iconBitmap = webBackForwardList.getItemAtIndex(i).getFavicon();
123 // Create a `ByteArrayOutputStream`.
124 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
126 // Remove the incorrect lint error that `compress()` might be null;
127 assert iconBitmap != null;
129 // Convert the favorite icon `Bitmap` to a `ByteArrayOutputStream`. `100` is the compression quality, which is ignored by `PNG`.
130 iconBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
132 // Convert the favorite icon `ByteArrayOutputStream` to a `byte[]`.
133 byte[] byteArray = byteArrayOutputStream.toByteArray();
135 // Encode the favorite icon `byte[]` as a Base64 `String`.
136 String iconBase64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
138 // Store the favorite icon Base64 `String` in `iconBase64StringArrayList`.
139 iconBase64StringArrayList.add(iconBase64String);
142 // Store the variables in the `Bundle`.
143 argumentsBundle.putInt("Current_Page", currentPageIndex);
144 argumentsBundle.putStringArrayList("URL_History", urlArrayList);
145 argumentsBundle.putStringArrayList("Favorite_Icons", iconBase64StringArrayList);
147 // Add the arguments bundle to this instance of `UrlHistoryDialog`.
148 UrlHistoryDialog thisUrlHistoryDialog = new UrlHistoryDialog();
149 thisUrlHistoryDialog.setArguments(argumentsBundle);
150 return thisUrlHistoryDialog;
154 public void onCreate(Bundle savedInstanceState) {
155 super.onCreate(savedInstanceState);
157 // Remove the incorrect lint error that `getArguments()` might be null.
158 assert getArguments() != null;
160 // Get the `ArrayLists` from the `Arguments`.
161 ArrayList<String> urlStringArrayList = getArguments().getStringArrayList("URL_History");
162 ArrayList<String> favoriteIconBase64StringArrayList = getArguments().getStringArrayList("Favorite_Icons");
164 // Remove the lint warning below that the `ArrayLists` might be `null`.
165 assert urlStringArrayList != null;
166 assert favoriteIconBase64StringArrayList != null;
168 // 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.
169 for (int i=urlStringArrayList.size() -1; i >= 0; i--) {
170 // Decode the favorite icon Base64 `String` to a `byte[]`.
171 byte[] favoriteIconByteArray = Base64.decode(favoriteIconBase64StringArrayList.get(i), Base64.DEFAULT);
173 // Convert the favorite icon `byte[]` to a `Bitmap`. `0` is the starting offset.
174 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
176 // Store the favorite icon and the URL in `historyEntry`.
177 History historyEntry = new History(favoriteIconBitmap, urlStringArrayList.get(i));
179 // Add this history entry to `historyArrayList`.
180 historyArrayList.add(historyEntry);
183 // Get the original current page ID.
184 int originalCurrentPageId = getArguments().getInt("Current_Page");
186 // 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.
187 currentPageId = urlStringArrayList.size() - 1 - originalCurrentPageId;
192 // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
193 @SuppressLint("InflateParams")
194 public Dialog onCreateDialog(Bundle savedInstanceState) {
195 // Remove the incorrect lint warning that `getActivity()` might be null.
196 assert getActivity() != null;
198 // Get the activity's layout inflater.
199 LayoutInflater layoutInflater = getActivity().getLayoutInflater();
201 // Use an alert dialog builder to create the alert dialog.
202 AlertDialog.Builder dialogBuilder;
204 // Get a handle for the shared preferences.
205 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
207 // Get the screenshot and theme preferences.
208 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
209 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
211 // Set the style according to the theme.
213 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
215 dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
219 dialogBuilder.setTitle(R.string.history);
221 // Set the view. The parent view is `null` because it will be assigned by `AlertDialog`.
222 dialogBuilder.setView(layoutInflater.inflate(R.layout.url_history_dialog, null));
224 // Set an `onClick()` listener on the negative button.
225 dialogBuilder.setNegativeButton(R.string.clear_history, (DialogInterface dialog, int which) -> {
226 // Clear the history.
227 urlHistoryListener.onClearHistory();
230 // Set an `onClick()` listener on the positive button.
231 dialogBuilder.setPositiveButton(R.string.close, (DialogInterface dialog, int which) -> {
232 // Do nothing if `Close` is clicked. The `Dialog` will automatically close.
235 // Create an alert dialog from the alert dialog builder.
236 final AlertDialog alertDialog = dialogBuilder.create();
238 // Disable screenshots if not allowed.
239 if (!allowScreenshots) {
240 // Remove the warning below that `getWindow()` might be null.
241 assert alertDialog.getWindow() != null;
243 // Disable screenshots.
244 alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
247 //The alert dialog must be shown before the contents can be modified.
250 // Instantiate a `HistoryArrayAdapter`.
251 HistoryArrayAdapter historyArrayAdapter = new HistoryArrayAdapter(getContext(), historyArrayList, currentPageId);
253 // Get a handle for the list view.
254 ListView listView = alertDialog.findViewById(R.id.history_listview);
256 // Set the list view adapter.
257 listView.setAdapter(historyArrayAdapter);
259 // Listen for clicks on entries in the list view.
260 listView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
261 // Convert the long ID to an int.
262 int itemId = (int) id;
264 // Only consume the click if it is not on the `currentPageId`.
265 if (itemId != currentPageId) {
266 // Go forward or back to `itemId`.
267 urlHistoryListener.onUrlHistoryEntrySelected(currentPageId - itemId);
269 // Dismiss the `Dialog`.
270 alertDialog.dismiss();
274 // `onCreateDialog` requires the return of an `AlertDialog`.