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