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