]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/DomainsActivity.java
Add controls for displaying webpage images. Implements https://redmine.stoutner...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / DomainsActivity.java
1 /*
2  * Copyright © 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.activities;
21
22 import android.content.Context;
23 import android.content.Intent;
24 import android.database.Cursor;
25 import android.os.Bundle;
26 import android.support.design.widget.FloatingActionButton;
27 import android.support.design.widget.Snackbar;
28 import android.support.v4.app.NavUtils;
29 import android.support.v7.app.ActionBar;
30 import android.support.v7.app.AppCompatActivity;
31 import android.support.v7.app.AppCompatDialogFragment;
32 import android.support.v7.widget.Toolbar;
33 import android.view.Menu;
34 import android.view.MenuItem;
35 import android.view.View;
36 import android.view.ViewGroup;
37 import android.widget.AdapterView;
38 import android.widget.CursorAdapter;
39 import android.widget.EditText;
40 import android.widget.ListView;
41 import android.widget.Spinner;
42 import android.widget.Switch;
43 import android.widget.TextView;
44
45 import com.stoutner.privacybrowser.R;
46 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
47 import com.stoutner.privacybrowser.fragments.DomainSettingsFragment;
48 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
49
50 public class DomainsActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener {
51     // `context` is used in `onCreate()` and `onOptionsItemSelected()`.
52     private Context context;
53
54     // `domainsDatabaseHelper` is used in `onCreate()`, `onOptionsItemSelected()`, `onAddDomain()`, and `updateDomainsRecyclerView()`.
55     private static DomainsDatabaseHelper domainsDatabaseHelper;
56
57     // `twoPaneMode` is used in `onCreate()` and `updateDomainsListView()`.
58     private boolean twoPaneMode;
59
60     // `domainsListView` is used in `onCreate()`, `onOptionsItemSelected()`, and `updateDomainsListView()`.
61     private ListView domainsListView;
62
63     // `databaseId` is used in `onCreate()` and `onOptionsItemSelected()`.
64     private int databaseId;
65
66     // `saveMenuItem` is used in `onCreate()`, `onOptionsItemSelected()`, and `onCreateOptionsMenu()`.
67     private MenuItem saveMenuItem;
68
69     // `deleteMenuItem` is used in `onCreate()`, `onOptionsItemSelected()`, and `onCreateOptionsMenu()`.
70     private MenuItem deleteMenuItem;
71
72     @Override
73     protected void onCreate(Bundle savedInstanceState) {
74         super.onCreate(savedInstanceState);
75         setContentView(R.layout.domains_coordinatorlayout);
76
77         // Get a handle for the context.
78         context = this;
79
80         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
81         final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.domains_toolbar);
82         setSupportActionBar(bookmarksAppBar);
83
84         // Display the home arrow on `SupportActionBar`.
85         ActionBar appBar = getSupportActionBar();
86         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
87         appBar.setDisplayHomeAsUpEnabled(true);
88
89         // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
90         // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
91         domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
92
93         // Determine if we are in two pane mode.  `domains_settings_linearlayout` is only populated if two panes are present.
94         twoPaneMode = ((findViewById(R.id.domain_settings_scrollview)) != null);
95
96         // Initialize `domainsListView`.
97         domainsListView = (ListView) findViewById(R.id.domains_listview);
98
99         domainsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
100             @Override
101             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
102                 // Convert the id from `long` to `int` to match the format of the domains database.
103                 databaseId = (int) id;
104
105                 // Display the Domain Settings.
106                 if (twoPaneMode) {  // Display a fragment in two paned mode.
107                     // Enable the options `MenuItems`.
108                     saveMenuItem.setEnabled(true);
109                     deleteMenuItem.setEnabled(true);
110
111                     // Store `databaseId` in `argumentsBundle`.
112                     Bundle argumentsBundle = new Bundle();
113                     argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, databaseId);
114
115                     // Add `argumentsBundle` to `domainSettingsFragment`.
116                     DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
117                     domainSettingsFragment.setArguments(argumentsBundle);
118
119                     // Display `domainSettingsFragment`.
120                     getSupportFragmentManager().beginTransaction().replace(R.id.domain_settings_scrollview, domainSettingsFragment).commit();
121
122                     // Enable the options `MenuItems`.
123                     deleteMenuItem.setEnabled(true);
124                     deleteMenuItem.setIcon(R.drawable.delete);
125                     saveMenuItem.setEnabled(true);
126                 } else { // Load the second activity on smaller screens.
127                     // Create `domainSettingsActivityIntent` with the `databaseId`.
128                     Intent domainSettingsActivityIntent = new Intent(context, DomainSettingsActivity.class);
129                     domainSettingsActivityIntent.putExtra(DomainSettingsFragment.DATABASE_ID, databaseId);
130
131                     // Start `DomainSettingsActivity`.
132                     context.startActivity(domainSettingsActivityIntent);
133                 }
134             }
135         });
136
137         FloatingActionButton addDomainFAB = (FloatingActionButton) findViewById(R.id.add_domain_fab);
138         addDomainFAB.setOnClickListener(new View.OnClickListener() {
139             @Override
140             public void onClick(View view) {
141                 // Show the `AddDomainDialog` `AlertDialog` and name the instance `@string/add_domain`.
142                 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
143                 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
144             }
145         });
146     }
147
148     @Override
149     public boolean onCreateOptionsMenu(Menu menu) {
150         // Inflate the menu.
151         getMenuInflater().inflate(R.menu.domains_options_menu, menu);
152
153         // Store the `MenuItems` for future use.
154         deleteMenuItem = menu.findItem(R.id.delete_domain);
155         saveMenuItem = menu.findItem(R.id.save_domain);
156
157         // Only display the options `MenuItems` in two pane mode.
158         deleteMenuItem.setVisible(twoPaneMode);
159         saveMenuItem.setVisible(twoPaneMode);
160
161         // Load the `ListView`.  We have to do this from `onCreateOptionsMenu()` instead of `onCreate()` because `updateDomainsListView()` needs the `MenuItems` to be inflated.
162         updateDomainsListView();
163
164         // Success!
165         return true;
166     }
167
168     @Override
169     public boolean onOptionsItemSelected(MenuItem menuItem) {
170         // Get the ID of the `MenuItem` that was selected.
171         int menuItemID = menuItem.getItemId();
172
173         switch (menuItemID) {
174             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
175                 // Go home.
176                 NavUtils.navigateUpFromSameTask(this);
177                 break;
178
179             case R.id.save_domain:
180                 // Get handles for the domain settings.
181                 EditText domainNameEditText = (EditText) findViewById(R.id.domain_settings_name_edittext);
182                 Switch javaScriptEnabledSwitch = (Switch) findViewById(R.id.domain_settings_javascript_switch);
183                 Switch firstPartyCookiesEnabledSwitch = (Switch) findViewById(R.id.domain_settings_first_party_cookies_switch);
184                 Switch thirdPartyCookiesEnabledSwitch = (Switch) findViewById(R.id.domain_settings_third_party_cookies_switch);
185                 Switch domStorageEnabledSwitch = (Switch) findViewById(R.id.domain_settings_dom_storage_switch);
186                 Switch formDataEnabledSwitch = (Switch) findViewById(R.id.domain_settings_form_data_switch);
187                 Spinner userAgentSpinner = (Spinner) findViewById(R.id.domain_settings_user_agent_spinner);
188                 EditText customUserAgentEditText = (EditText) findViewById(R.id.domain_settings_custom_user_agent_edittext);
189                 Spinner fontSizeSpinner = (Spinner) findViewById(R.id.domain_settings_font_size_spinner);
190                 Spinner displayWebpageImagesSpinner = (Spinner) findViewById(R.id.domain_settings_display_webpage_images_spinner);
191
192                 // Extract the data for the domain settings.
193                 String domainNameString = domainNameEditText.getText().toString();
194                 boolean javaScriptEnabledBoolean = javaScriptEnabledSwitch.isChecked();
195                 boolean firstPartyCookiesEnabledBoolean = firstPartyCookiesEnabledSwitch.isChecked();
196                 boolean thirdPartyCookiesEnabledBoolean = thirdPartyCookiesEnabledSwitch.isChecked();
197                 boolean domStorageEnabledEnabledBoolean  = domStorageEnabledSwitch.isChecked();
198                 boolean formDataEnabledBoolean = formDataEnabledSwitch.isChecked();
199                 int userAgentPositionInt = userAgentSpinner.getSelectedItemPosition();
200                 int fontSizePositionInt = fontSizeSpinner.getSelectedItemPosition();
201                 int displayWebpageImagesInt = displayWebpageImagesSpinner.getSelectedItemPosition();
202
203                 // Get the data for the `Spinners` from the entry values string arrays.
204                 String userAgentString = getResources().getStringArray(R.array.user_agent_entry_values)[userAgentPositionInt];
205                 int fontSizeInt = Integer.parseInt(getResources().getStringArray(R.array.default_font_size_entry_values)[fontSizePositionInt]);
206
207                 // Check to see if we are using a custom user agent.
208                 if (userAgentString.equals("Custom user agent")) {
209                     // Set `userAgentString` to the custom user agent string.
210                     userAgentString = customUserAgentEditText.getText().toString();
211                 }
212
213                 // Save the domain settings.
214                 domainsDatabaseHelper.saveDomain(databaseId, domainNameString, javaScriptEnabledBoolean, firstPartyCookiesEnabledBoolean, thirdPartyCookiesEnabledBoolean, domStorageEnabledEnabledBoolean, formDataEnabledBoolean, userAgentString, fontSizeInt,
215                         displayWebpageImagesInt);
216
217                 // Display a `Snackbar`.
218                 Snackbar.make(domainsListView, R.string.domain_settings_saved, Snackbar.LENGTH_SHORT).show();
219
220                 // update the domains `ListView`.
221                 updateDomainsListView();
222                 break;
223
224             case R.id.delete_domain:
225                 // Save the `ListView` `currentPosition`.
226                 final int currentPosition = domainsListView.getCheckedItemPosition();
227
228                 // Get a `Cursor` that does not show the domain to be deleted.
229                 Cursor domainsPendingDeleteCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomainExcept(databaseId);
230
231                 // Setup `domainsPendingDeleteCursorAdapter` with `this` context.  `false` disables `autoRequery`.
232                 CursorAdapter domainsPendingDeleteCursorAdapter = new CursorAdapter(this, domainsPendingDeleteCursor, false) {
233                     @Override
234                     public View newView(Context context, Cursor cursor, ViewGroup parent) {
235                         // Inflate the individual item layout.  `false` does not attach it to the root.
236                         return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
237                     }
238
239                     @Override
240                     public void bindView(View view, Context context, Cursor cursor) {
241                         // Set the domain name.
242                         String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
243                         TextView domainNameTextView = (TextView) view.findViewById(R.id.domain_name_textview);
244                         domainNameTextView.setText(domainNameString);
245                     }
246                 };
247
248                 // Update the `ListView`.
249                 domainsListView.setAdapter(domainsPendingDeleteCursorAdapter);
250
251                 // Detach the domain settings `Fragment`.
252                 getSupportFragmentManager().beginTransaction().detach(getSupportFragmentManager().findFragmentById(R.id.domain_settings_scrollview)).commit();
253
254                 // Disable the options `MenuItems`.
255                 deleteMenuItem.setEnabled(false);
256                 deleteMenuItem.setIcon(R.drawable.delete_blue);
257                 saveMenuItem.setEnabled(false);
258
259                 // Display a `Snackbar`.
260                 Snackbar.make(domainsListView, R.string.domain_deleted, Snackbar.LENGTH_LONG)
261                         .setAction(R.string.undo, new View.OnClickListener() {
262                             @Override
263                             public void onClick(View v) {
264                                 // Do nothing because everything will be handled by `onDismissed()` below.
265                             }
266                         })
267                         .addCallback(new Snackbar.Callback() {
268                             @Override
269                             public void onDismissed(Snackbar snackbar, int event) {
270                                 switch (event) {
271                                     // The user pushed the `Undo` button.
272                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
273                                         // Get a `Cursor` with the current contents of the domains database.
274                                         Cursor undoDeleteDomainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
275
276                                         // Setup `domainsCursorAdapter` with `this` context.  `false` disables `autoRequery`.
277                                         CursorAdapter undoDeleteDomainsCursorAdapter = new CursorAdapter(context, undoDeleteDomainsCursor, false) {
278                                             @Override
279                                             public View newView(Context context, Cursor cursor, ViewGroup parent) {
280                                                 // Inflate the individual item layout.  `false` does not attach it to the root.
281                                                 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
282                                             }
283
284                                             @Override
285                                             public void bindView(View view, Context context, Cursor cursor) {
286                                                 // Set the domain name.
287                                                 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
288                                                 TextView domainNameTextView = (TextView) view.findViewById(R.id.domain_name_textview);
289                                                 domainNameTextView.setText(domainNameString);
290                                             }
291                                         };
292
293                                         // Update the `ListView`.
294                                         domainsListView.setAdapter(undoDeleteDomainsCursorAdapter);
295
296                                         // Select the entry in the domain list at `currentPosition`.
297                                         domainsListView.setItemChecked(currentPosition, true);
298
299                                         // Store `databaseId` in `argumentsBundle`.
300                                         Bundle argumentsBundle = new Bundle();
301                                         argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, databaseId);
302
303                                         // Add `argumentsBundle` to `domainSettingsFragment`.
304                                         DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
305                                         domainSettingsFragment.setArguments(argumentsBundle);
306
307                                         // Display `domainSettingsFragment`.
308                                         getSupportFragmentManager().beginTransaction().replace(R.id.domain_settings_scrollview, domainSettingsFragment).commit();
309
310                                         // Enable the options `MenuItems`.
311                                         deleteMenuItem.setEnabled(true);
312                                         deleteMenuItem.setIcon(R.drawable.delete);
313                                         saveMenuItem.setEnabled(true);
314                                         break;
315
316                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
317                                     default:
318                                         // Delete the selected domain.
319                                         domainsDatabaseHelper.deleteDomain(databaseId);
320                                         break;
321                                 }
322                             }
323                         })
324                         .show();
325                 break;
326         }
327
328         // Consume the event.
329         return true;
330     }
331
332     @Override
333     public void onAddDomain(AppCompatDialogFragment dialogFragment) {
334         // Get the `domainNameEditText` from `dialogFragment` and extract the string.
335         EditText domainNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
336         String domainNameString = domainNameEditText.getText().toString();
337
338         // Create the domain.
339         domainsDatabaseHelper.addDomain(domainNameString);
340
341         // Refresh the `ListView`.
342         updateDomainsListView();
343     }
344
345     private void updateDomainsListView() {
346         // Initialize `currentPosition`.
347         int currentPosition;
348
349         // Store the current position of `domainsListView` if it is already populated.
350         if (domainsListView.getCount() > 0){
351             currentPosition = domainsListView.getCheckedItemPosition();
352         } else {
353             // Set `currentPosition` to 0;
354             currentPosition = 0;
355         }
356
357         // Get a `Cursor` with the current contents of the domains database.
358         Cursor domainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
359
360         // Setup `domainsCursorAdapter` with `this` context.  `false` disables `autoRequery`.
361         CursorAdapter domainsCursorAdapter = new CursorAdapter(this, domainsCursor, false) {
362             @Override
363             public View newView(Context context, Cursor cursor, ViewGroup parent) {
364                 // Inflate the individual item layout.  `false` does not attach it to the root.
365                 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
366             }
367
368             @Override
369             public void bindView(View view, Context context, Cursor cursor) {
370                 // Set the domain name.
371                 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
372                 TextView domainNameTextView = (TextView) view.findViewById(R.id.domain_name_textview);
373                 domainNameTextView.setText(domainNameString);
374             }
375         };
376
377         // Update the `ListView`.
378         domainsListView.setAdapter(domainsCursorAdapter);
379
380         // Display the domain settings in the second pane if operating in two pane mode and the database contains at least one domain.
381         if (twoPaneMode && (domainsCursor.getCount() > 0)) {
382             // Select the entry in the domain list at `currentPosition`.
383             domainsListView.setItemChecked(currentPosition, true);
384
385             // Get the `databaseId` for `currentPosition`.
386             domainsCursor.moveToPosition(currentPosition);
387             databaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
388
389             // Store `databaseId` in `argumentsBundle`.
390             Bundle argumentsBundle = new Bundle();
391             argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, databaseId);
392
393             // Add `argumentsBundle` to `domainSettingsFragment`.
394             DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
395             domainSettingsFragment.setArguments(argumentsBundle);
396
397             // Display `domainSettingsFragment`.
398             getSupportFragmentManager().beginTransaction().replace(R.id.domain_settings_scrollview, domainSettingsFragment).commit();
399
400             // Enable the options `MenuItems`.
401             deleteMenuItem.setEnabled(true);
402             deleteMenuItem.setIcon(R.drawable.delete);
403             saveMenuItem.setEnabled(true);
404         } else {
405             // Disable the options `MenuItems`.
406             deleteMenuItem.setEnabled(false);
407             deleteMenuItem.setIcon(R.drawable.delete_blue);
408             saveMenuItem.setEnabled(false);
409         }
410     }
411 }