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