]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/UrlHistoryDialog.java
Add a requests activity. https://redmine.stoutner.com/issues/170
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / UrlHistoryDialog.java
1 /*
2  * Copyright © 2016-2018 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.support.annotation.NonNull;
33 import android.support.v4.content.ContextCompat;
34 // `AppCompatDialogFragment` must be used instead of `DialogFragment` or an error is produced on API <= 22.
35 // `android.support.v7.app.AlertDialog` also uses more of the horizontal screen real estate versus `android.app.AlertDialog's` smaller width.
36 import android.support.v7.app.AppCompatDialogFragment;
37 import android.util.Base64;
38 import android.view.LayoutInflater;
39 import android.view.View;
40 import android.view.WindowManager;
41 import android.webkit.WebBackForwardList;
42 import android.widget.AdapterView;
43 import android.widget.ListView;
44
45 import com.stoutner.privacybrowser.R;
46 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
47 import com.stoutner.privacybrowser.adapters.HistoryArrayAdapter;
48 import com.stoutner.privacybrowser.definitions.History;
49
50 import java.io.ByteArrayOutputStream;
51 import java.util.ArrayList;
52
53 public class UrlHistoryDialog extends AppCompatDialogFragment{
54
55     // `historyArrayList`  and `currentPageId` pass information from `onCreate()` to `onCreateDialog()`.
56     private final ArrayList<History> historyArrayList = new ArrayList<>();
57     private int currentPageId;
58
59     public static UrlHistoryDialog loadBackForwardList(Context context, WebBackForwardList webBackForwardList) {
60         // Create `argumentsBundle`.
61         Bundle argumentsBundle = new Bundle();
62
63         // Store `currentPageIndex`.
64         int currentPageIndex = webBackForwardList.getCurrentIndex();
65
66         // Setup `urlArrayList` and `iconArrayList`.
67         ArrayList<String> urlArrayList = new ArrayList<>();
68         ArrayList<String> iconBase64StringArrayList = new ArrayList<>();
69
70         // Get the default favorite icon `Drawable`.
71         Drawable defaultFavoriteIconDrawable = ContextCompat.getDrawable(context, R.drawable.world);
72
73         // Convert `defaultFavoriteIconDrawable` to a `BitmapDrawable`.
74         BitmapDrawable defaultFavoriteIconBitmapDrawable = (BitmapDrawable) defaultFavoriteIconDrawable;
75
76         // Remove the incorrect lint error that `getBitmap()` might be null.
77         assert defaultFavoriteIconBitmapDrawable != null;
78
79         // Extract a `Bitmap` from `defaultFavoriteIconBitmapDrawable`.
80         Bitmap defaultFavoriteIcon = defaultFavoriteIconBitmapDrawable.getBitmap();
81
82         // Populate `urlArrayList` and `iconArrayList` from `webBackForwardList`.
83         for (int i=0; i < webBackForwardList.getSize(); i++) {
84             // Store the URL.
85             urlArrayList.add(webBackForwardList.getItemAtIndex(i).getUrl());
86
87             // Create a variable to store the icon `Bitmap`.
88             Bitmap iconBitmap;
89
90             // Store the icon `Bitmap`.
91             if (webBackForwardList.getItemAtIndex(i).getFavicon() == null) {
92                 // If `webBackForwardList` does not have a favorite icon, use Privacy Browser's default world icon.
93                 iconBitmap = defaultFavoriteIcon;
94             } else {  // Get the icon from `webBackForwardList`.
95                 iconBitmap = webBackForwardList.getItemAtIndex(i).getFavicon();
96             }
97
98             // Create a `ByteArrayOutputStream`.
99             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
100
101             // Remove the incorrect lint error that `compress()` might be null;
102             assert iconBitmap != null;
103
104             // Convert the favorite icon `Bitmap` to a `ByteArrayOutputStream`.  `100` is the compression quality, which is ignored by `PNG`.
105             iconBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
106
107             // Convert the favorite icon `ByteArrayOutputStream` to a `byte[]`.
108             byte[] byteArray = byteArrayOutputStream.toByteArray();
109
110             // Encode the favorite icon `byte[]` as a Base64 `String`.
111             String iconBase64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
112
113             // Store the favorite icon Base64 `String` in `iconBase64StringArrayList`.
114             iconBase64StringArrayList.add(iconBase64String);
115         }
116
117         // Store the variables in the `Bundle`.
118         argumentsBundle.putInt("Current_Page", currentPageIndex);
119         argumentsBundle.putStringArrayList("URL_History", urlArrayList);
120         argumentsBundle.putStringArrayList("Favorite_Icons", iconBase64StringArrayList);
121
122         // Add `argumentsBundle` to this instance of `UrlHistoryDialog`.
123         UrlHistoryDialog thisUrlHistoryDialog = new UrlHistoryDialog();
124         thisUrlHistoryDialog.setArguments(argumentsBundle);
125         return thisUrlHistoryDialog;
126     }
127
128     @Override
129     public void onCreate(Bundle savedInstanceState) {
130         super.onCreate(savedInstanceState);
131
132         // Remove the incorrect lint error that `getArguments()` might be null.
133         assert getArguments() != null;
134
135         // Get the `ArrayLists` from the `Arguments`.
136         ArrayList<String> urlStringArrayList = getArguments().getStringArrayList("URL_History");
137         ArrayList<String> favoriteIconBase64StringArrayList = getArguments().getStringArrayList("Favorite_Icons");
138
139         // Remove the lint warning below that the `ArrayLists` might be `null`.
140         assert urlStringArrayList != null;
141         assert favoriteIconBase64StringArrayList != null;
142
143         // 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.
144         for (int i=urlStringArrayList.size() -1; i >= 0; i--) {
145             // Decode the favorite icon Base64 `String` to a `byte[]`.
146             byte[] favoriteIconByteArray = Base64.decode(favoriteIconBase64StringArrayList.get(i), Base64.DEFAULT);
147
148             // Convert the favorite icon `byte[]` to a `Bitmap`.  `0` is the starting offset.
149             Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
150
151             // Store the favorite icon and the URL in `historyEntry`.
152             History historyEntry = new History(favoriteIconBitmap, urlStringArrayList.get(i));
153
154             // Add this history entry to `historyArrayList`.
155             historyArrayList.add(historyEntry);
156         }
157
158         // Get the original current page ID.
159         int originalCurrentPageId = getArguments().getInt("Current_Page");
160
161         // 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.
162         currentPageId = urlStringArrayList.size() - 1 - originalCurrentPageId;
163     }
164
165     // The public interface is used to send information back to the parent activity.
166     public interface UrlHistoryListener {
167         // Send back the number of steps to move forward or back.
168         void onUrlHistoryEntrySelected(int moveBackOrForwardSteps);
169
170         // Clear the history.
171         void onClearHistory();
172     }
173
174     // `urlHistoryListener` is used in `onAttach()` and `onCreateDialog()`.
175     private UrlHistoryListener urlHistoryListener;
176
177     @Override
178     public void onAttach(Context context) {
179         super.onAttach(context);
180
181         // Check to make sure tha the parent activity implements the listener.
182         try {
183             urlHistoryListener = (UrlHistoryListener) context;
184         } catch (ClassCastException exception) {
185             throw new ClassCastException(context.toString() + " must implement UrlHistoryListener.");
186         }
187     }
188
189     @Override
190     @NonNull
191     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
192     @SuppressLint("InflateParams")
193     public Dialog onCreateDialog(Bundle savedInstanceState) {
194         // Remove the incorrect lint warning that `getActivity()` might be null.
195         assert getActivity() != null;
196
197         // Get the activity's layout inflater.
198         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
199
200         // Use an alert dialog builder to create the alert dialog.
201         AlertDialog.Builder dialogBuilder;
202
203         // Set the style according to the theme.
204         if (MainWebViewActivity.darkTheme) {
205             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
206         } else {
207             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
208         }
209
210         // Set the title.
211         dialogBuilder.setTitle(R.string.history);
212
213         // Set the view.  The parent view is `null` because it will be assigned by `AlertDialog`.
214         dialogBuilder.setView(layoutInflater.inflate(R.layout.url_history_dialog, null));
215
216         // Set an `onClick()` listener on the negative button.
217         dialogBuilder.setNegativeButton(R.string.clear_history, (DialogInterface dialog, int which) -> {
218             // Clear the history.
219             urlHistoryListener.onClearHistory();
220         });
221
222         // Set an `onClick()` listener on the positive button.
223         dialogBuilder.setPositiveButton(R.string.close, (DialogInterface dialog, int which) -> {
224             // Do nothing if `Close` is clicked.  The `Dialog` will automatically close.
225         });
226
227         // Create an alert dialog from the alert dialog builder.
228         final AlertDialog alertDialog = dialogBuilder.create();
229
230         // Disable screenshots if not allowed.
231         if (!MainWebViewActivity.allowScreenshots) {
232             // Remove the warning below that `getWindow()` might be null.
233             assert alertDialog.getWindow() != null;
234
235             // Disable screenshots.
236             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
237         }
238
239         //The alert dialog must be shown before the contents can be modified.
240         alertDialog.show();
241
242         // Instantiate a `HistoryArrayAdapter`.
243         HistoryArrayAdapter historyArrayAdapter = new HistoryArrayAdapter(getContext(), historyArrayList, currentPageId);
244
245         // Get a handle for the list view.
246         ListView listView = alertDialog.findViewById(R.id.history_listview);
247
248         // Set the list view adapter.
249         listView.setAdapter(historyArrayAdapter);
250
251         // Listen for clicks on entries in the list view.
252         listView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
253             // Convert the long ID to an int.
254             int itemId = (int) id;
255
256             // Only consume the click if it is not on the `currentPageId`.
257             if (itemId != currentPageId) {
258                 // Go forward or back to `itemId`.
259                 urlHistoryListener.onUrlHistoryEntrySelected(currentPageId - itemId);
260
261                 // Dismiss the `Dialog`.
262                 alertDialog.dismiss();
263             }
264         });
265
266         // `onCreateDialog` requires the return of an `AlertDialog`.
267         return alertDialog;
268     }
269 }