]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/UrlHistoryDialog.java
0fe8afaa94e2e5d4078b1fae54e79d4896903204
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / UrlHistoryDialog.java
1 /*
2  * Copyright © 2016-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.dialogs;
21
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;
39
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.
43
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;
48
49 import java.io.ByteArrayOutputStream;
50 import java.util.ArrayList;
51
52 public class UrlHistoryDialog extends DialogFragment{
53
54     // `historyArrayList`  and `currentPageId` pass information from `onCreate()` to `onCreateDialog()`.
55     private final ArrayList<History> historyArrayList = new ArrayList<>();
56     private int currentPageId;
57
58     public static UrlHistoryDialog loadBackForwardList(Context context, WebBackForwardList webBackForwardList) {
59         // Create an arguments bundle.
60         Bundle argumentsBundle = new Bundle();
61
62         // Store the current page index.
63         int currentPageIndex = webBackForwardList.getCurrentIndex();
64
65         // Setup the URL array list and the icon array list.
66         ArrayList<String> urlArrayList = new ArrayList<>();
67         ArrayList<String> iconBase64StringArrayList = new ArrayList<>();
68
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);
71
72         // Convert the default favorite icon drawable to a `BitmapDrawable`.
73         BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
74
75         // Remove the incorrect lint error that `getBitmap()` might be null.
76         assert defaultFavoriteIconBitmapDrawable != null;
77
78         // Extract a `Bitmap` from the default favorite icon `BitmapDrawable`.
79         Bitmap defaultFavoriteIcon = defaultFavoriteIconBitmapDrawable.getBitmap();
80
81         // Populate the URL array list and the icon array list from `webBackForwardList`.
82         for (int i=0; i < webBackForwardList.getSize(); i++) {
83             // Store the URL.
84             urlArrayList.add(webBackForwardList.getItemAtIndex(i).getUrl());
85
86             // Create a variable to store the icon bitmap.
87             Bitmap iconBitmap;
88
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();
95             }
96
97             // Create a `ByteArrayOutputStream`.
98             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
99
100             // Remove the incorrect lint error that `compress()` might be null;
101             assert iconBitmap != null;
102
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);
105
106             // Convert the favorite icon `ByteArrayOutputStream` to a `byte[]`.
107             byte[] byteArray = byteArrayOutputStream.toByteArray();
108
109             // Encode the favorite icon `byte[]` as a Base64 `String`.
110             String iconBase64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
111
112             // Store the favorite icon Base64 `String` in `iconBase64StringArrayList`.
113             iconBase64StringArrayList.add(iconBase64String);
114         }
115
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);
120
121         // Add the arguments bundle to this instance of `UrlHistoryDialog`.
122         UrlHistoryDialog thisUrlHistoryDialog = new UrlHistoryDialog();
123         thisUrlHistoryDialog.setArguments(argumentsBundle);
124         return thisUrlHistoryDialog;
125     }
126
127     @Override
128     public void onCreate(Bundle savedInstanceState) {
129         super.onCreate(savedInstanceState);
130
131         // Remove the incorrect lint error that `getArguments()` might be null.
132         assert getArguments() != null;
133
134         // Get the `ArrayLists` from the `Arguments`.
135         ArrayList<String> urlStringArrayList = getArguments().getStringArrayList("URL_History");
136         ArrayList<String> favoriteIconBase64StringArrayList = getArguments().getStringArrayList("Favorite_Icons");
137
138         // Remove the lint warning below that the `ArrayLists` might be `null`.
139         assert urlStringArrayList != null;
140         assert favoriteIconBase64StringArrayList != null;
141
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);
146
147             // Convert the favorite icon `byte[]` to a `Bitmap`.  `0` is the starting offset.
148             Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
149
150             // Store the favorite icon and the URL in `historyEntry`.
151             History historyEntry = new History(favoriteIconBitmap, urlStringArrayList.get(i));
152
153             // Add this history entry to `historyArrayList`.
154             historyArrayList.add(historyEntry);
155         }
156
157         // Get the original current page ID.
158         int originalCurrentPageId = getArguments().getInt("Current_Page");
159
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;
162     }
163
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);
168
169         // Clear the history.
170         void onClearHistory();
171     }
172
173     // `urlHistoryListener` is used in `onAttach()` and `onCreateDialog()`.
174     private UrlHistoryListener urlHistoryListener;
175
176     @Override
177     public void onAttach(Context context) {
178         super.onAttach(context);
179
180         // Check to make sure tha the parent activity implements the listener.
181         try {
182             urlHistoryListener = (UrlHistoryListener) context;
183         } catch (ClassCastException exception) {
184             throw new ClassCastException(context.toString() + " must implement UrlHistoryListener.");
185         }
186     }
187
188     @Override
189     @NonNull
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;
195
196         // Get the activity's layout inflater.
197         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
198
199         // Use an alert dialog builder to create the alert dialog.
200         AlertDialog.Builder dialogBuilder;
201
202         // Set the style according to the theme.
203         if (MainWebViewActivity.darkTheme) {
204             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
205         } else {
206             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
207         }
208
209         // Set the title.
210         dialogBuilder.setTitle(R.string.history);
211
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));
214
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();
219         });
220
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.
224         });
225
226         // Create an alert dialog from the alert dialog builder.
227         final AlertDialog alertDialog = dialogBuilder.create();
228
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;
233
234             // Disable screenshots.
235             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
236         }
237
238         //The alert dialog must be shown before the contents can be modified.
239         alertDialog.show();
240
241         // Instantiate a `HistoryArrayAdapter`.
242         HistoryArrayAdapter historyArrayAdapter = new HistoryArrayAdapter(getContext(), historyArrayList, currentPageId);
243
244         // Get a handle for the list view.
245         ListView listView = alertDialog.findViewById(R.id.history_listview);
246
247         // Set the list view adapter.
248         listView.setAdapter(historyArrayAdapter);
249
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;
254
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);
259
260                 // Dismiss the `Dialog`.
261                 alertDialog.dismiss();
262             }
263         });
264
265         // `onCreateDialog` requires the return of an `AlertDialog`.
266         return alertDialog;
267     }
268 }