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