2 * Copyright © 2017-2018 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.app.Activity;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.res.Resources;
26 import android.database.Cursor;
27 import android.net.http.SslCertificate;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.support.design.widget.FloatingActionButton;
31 import android.support.design.widget.Snackbar;
32 import android.support.v4.app.FragmentManager;
33 import android.support.v4.app.NavUtils;
34 import android.support.v7.app.ActionBar;
35 import android.support.v7.app.AppCompatActivity;
36 // `AppCompatDialogFragment` is required instead of `DialogFragment` or an error is produced on API <=22.
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.support.v7.widget.Toolbar;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.view.WindowManager;
44 import android.widget.CursorAdapter;
45 import android.widget.EditText;
46 import android.widget.ListView;
47 import android.widget.RadioButton;
48 import android.widget.Spinner;
49 import android.widget.Switch;
50 import android.widget.TextView;
52 import com.stoutner.privacybrowser.R;
53 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
54 import com.stoutner.privacybrowser.fragments.DomainSettingsFragment;
55 import com.stoutner.privacybrowser.fragments.DomainsListFragment;
56 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
58 public class DomainsActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener {
59 // `twoPanedMode` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `populateDomainsListView()`.
60 public static boolean twoPanedMode;
62 // `databaseId` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onCreateOptionsMenu()`, `saveDomainSettings()` and `populateDomainsListView()`.
63 public static int currentDomainDatabaseId;
65 // `deleteMenuItem` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `onBackPressed()`.
66 public static MenuItem deleteMenuItem;
68 // `undoDeleteSnackbar` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onOptionsItemSelected()` and `onBackPressed()`.
69 public static Snackbar undoDeleteSnackbar;
71 // `dismissingSnackbar` is public static so it can be accessed from `DomainsListFragment`. It is also used in `onOptionsItemSelected()`.
72 public static boolean dismissingSnackbar;
74 // `closeActivityAfterDismissingSnackbar` is used in `onOptionsItemSelected()`, and `onBackPressed()`.
75 private boolean closeActivityAfterDismissingSnackbar;
77 // `context` is used in `onCreate()`, `onOptionsItemSelected()`, and `onAddDomain()`.
78 private Context context;
80 // `supportFragmentManager` is used in `onCreate()` and `onCreateOptionsMenu()`.
81 private FragmentManager supportFragmentManager;
83 // `domainsDatabaseHelper` is used in `onCreate()` and `saveDomainSettings()`.
84 private static DomainsDatabaseHelper domainsDatabaseHelper;
86 // `domainsListView` is used in `onCreate()` and `populateDomainsList()`.
87 private ListView domainsListView;
89 // `addDomainFAB` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `onBackPressed()`.
90 private FloatingActionButton addDomainFAB;
92 // `deletedDomainPosition` is used in an inner and outer class in `onOptionsItemSelected()`.
93 private int deletedDomainPosition;
95 // `restartAfterRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
96 private boolean restartAfterRotate;
98 // `domainSettingsDisplayedBeforeRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
99 private boolean domainSettingsDisplayedBeforeRotate;
101 // `domainSettingsDatabaseIdBeforeRotate` is used in `onCreate()` and `onCreateOptionsMenu()`.
102 private int domainSettingsDatabaseIdBeforeRotate;
104 // `goDirectlyToDatabaseId` is used in `onCreate()` and `onCreateOptionsMenu()`.
105 private int goDirectlyToDatabaseId;
107 // `closeOnBack` is used in `onCreate()`, `onOptionsItemSelected()` and `onBackPressed()`.
108 private boolean closeOnBack;
110 // `coordinatorLayout` is use in `onCreate()`, `onOptionsItemSelected()`, and `onSaveInstanceState()`.
111 private View coordinatorLayout;
113 // `resources` is used in `onCreate()`, `onOptionsItemSelected()`, and `onSaveInstanceState()`.
114 private Resources resources;
117 protected void onCreate(Bundle savedInstanceState) {
118 // Disable screenshots if not allowed.
119 if (!MainWebViewActivity.allowScreenshots) {
120 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
123 // Set the activity theme.
124 if (MainWebViewActivity.darkTheme) {
125 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
127 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
130 // Run the default commands.
131 super.onCreate(savedInstanceState);
133 // Extract the values from `savedInstanceState` if it is not `null`.
134 if (savedInstanceState != null) {
135 restartAfterRotate = true;
136 domainSettingsDisplayedBeforeRotate = savedInstanceState.getBoolean("domainSettingsDisplayed");
137 domainSettingsDatabaseIdBeforeRotate = savedInstanceState.getInt("domainSettingsDatabaseId");
140 // Get the launching intent
141 Intent intent = getIntent();
143 // Extract the domain to load if there is one. `-1` is the default value.
144 goDirectlyToDatabaseId = intent.getIntExtra("loadDomain", -1);
146 // Get the status of close-on-back, which is true when the domains activity is called from the options menu.
147 closeOnBack = intent.getBooleanExtra("closeOnBack", false);
149 // Set the content view.
150 setContentView(R.layout.domains_coordinatorlayout);
152 // Populate the class variables.
153 coordinatorLayout = findViewById(R.id.domains_coordinatorlayout);
154 resources = getResources();
156 supportFragmentManager = getSupportFragmentManager();
158 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
159 final Toolbar domainsAppBar = findViewById(R.id.domains_toolbar);
160 setSupportActionBar(domainsAppBar);
162 // Display the home arrow on `SupportActionBar`.
163 ActionBar appBar = getSupportActionBar();
164 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
165 appBar.setDisplayHomeAsUpEnabled(true);
167 // Initialize the database handler. The two `nulls` do not specify the database name or a `CursorFactory`. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
168 domainsDatabaseHelper = new DomainsDatabaseHelper(context, null, null, 0);
170 // Determine if we are in two pane mode. `domain_settings_fragment_container` does not exist on devices with a width less than 900dp.
171 twoPanedMode = (findViewById(R.id.domain_settings_fragment_container) != null);
173 // Configure `addDomainFAB`.
174 addDomainFAB = findViewById(R.id.add_domain_fab);
175 addDomainFAB.setOnClickListener((View view) -> {
176 // Show the add domain `AlertDialog`.
177 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
178 addDomainDialog.show(supportFragmentManager, resources.getString(R.string.add_domain));
183 public boolean onCreateOptionsMenu(Menu menu) {
185 getMenuInflater().inflate(R.menu.domains_options_menu, menu);
187 // Store `deleteMenuItem` for future use.
188 deleteMenuItem = menu.findItem(R.id.delete_domain);
190 // Only display `deleteMenuItem` (initially) in two-paned mode.
191 deleteMenuItem.setVisible(twoPanedMode);
193 // Display the fragments. This must be done from `onCreateOptionsMenu()` instead of `onCreate()` because `populateDomainsListView()` needs `deleteMenuItem` to be inflated.
194 if (restartAfterRotate && domainSettingsDisplayedBeforeRotate) { // The device was rotated and domain settings were displayed previously.
195 if (twoPanedMode) { // The device is in two-paned mode.
196 // Reset `restartAfterRotate`.
197 restartAfterRotate = false;
199 // Display `DomainsListFragment`.
200 DomainsListFragment domainsListFragment = new DomainsListFragment();
201 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
202 supportFragmentManager.executePendingTransactions();
204 // Populate the list of domains. `domainSettingsDatabaseId` highlights the domain that was highlighted before the rotation.
205 populateDomainsListView(domainSettingsDatabaseIdBeforeRotate);
206 } else { // The device is in single-paned mode.
207 // Reset `restartAfterRotate`.
208 restartAfterRotate = false;
210 // Store the current domain database ID.
211 currentDomainDatabaseId = domainSettingsDatabaseIdBeforeRotate;
213 // Add `currentDomainDatabaseId` to `argumentsBundle`.
214 Bundle argumentsBundle = new Bundle();
215 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
217 // Add `argumentsBundle` to `domainSettingsFragment`.
218 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
219 domainSettingsFragment.setArguments(argumentsBundle);
221 // Show `deleteMenuItem`.
222 deleteMenuItem.setVisible(true);
224 // Hide `add_domain_fab`.
225 addDomainFAB.setVisibility(View.GONE);
227 // Display `domainSettingsFragment`.
228 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
230 } else { // The device was not rotated or, if it was, domain settings were not displayed previously.
231 if (goDirectlyToDatabaseId >=0) { // Load the indicated domain settings.
232 // Store the current domain database ID.
233 currentDomainDatabaseId = goDirectlyToDatabaseId;
235 if (twoPanedMode) { // The device is in two-paned mode.
236 // Display `DomainsListFragment`.
237 DomainsListFragment domainsListFragment = new DomainsListFragment();
238 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
239 supportFragmentManager.executePendingTransactions();
241 // Populate the list of domains. `domainSettingsDatabaseId` highlights the domain that was highlighted before the rotation.
242 populateDomainsListView(goDirectlyToDatabaseId);
243 } else { // The device is in single-paned mode.
244 // Add the domain ID to be loaded to `argumentsBundle`.
245 Bundle argumentsBundle = new Bundle();
246 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, goDirectlyToDatabaseId);
248 // Add `argumentsBundle` to `domainSettingsFragment`.
249 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
250 domainSettingsFragment.setArguments(argumentsBundle);
252 // Show `deleteMenuItem`.
253 deleteMenuItem.setVisible(true);
255 // Hide `add_domain_fab`.
256 addDomainFAB.setVisibility(View.GONE);
258 // Display `domainSettingsFragment`.
259 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
261 } else { // Highlight the first domain.
262 // Display `DomainsListFragment`.
263 DomainsListFragment domainsListFragment = new DomainsListFragment();
264 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
265 supportFragmentManager.executePendingTransactions();
267 // Populate the list of domains. `-1` highlights the first domain.
268 populateDomainsListView(-1);
277 public boolean onOptionsItemSelected(MenuItem menuItem) {
278 // Get the ID of the `MenuItem` that was selected.
279 int menuItemID = menuItem.getItemId();
281 switch (menuItemID) {
282 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
283 if (twoPanedMode) { // The device is in two-paned mode.
284 // Save the current domain settings if the domain settings fragment is displayed.
285 if (findViewById(R.id.domain_settings_scrollview) != null) {
286 saveDomainSettings(coordinatorLayout, resources);
289 // Dismiss the undo delete `SnackBar` if it is shown.
290 if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
291 // Set the close flag.
292 closeActivityAfterDismissingSnackbar = true;
294 // Dismiss the snackbar.
295 undoDeleteSnackbar.dismiss();
298 NavUtils.navigateUpFromSameTask(this);
300 } else if (closeOnBack) { // Go directly back to the main WebView activity because the domains activity was launched from the options menu.
301 // Save the current domain settings.
302 saveDomainSettings(coordinatorLayout, resources);
305 NavUtils.navigateUpFromSameTask(this);
306 } else if (findViewById(R.id.domain_settings_scrollview) != null) { // The device is in single-paned mode and the domain settings fragment is displayed.
307 // Save the current domain settings.
308 saveDomainSettings(coordinatorLayout, resources);
310 // Display the domains list fragment.
311 DomainsListFragment domainsListFragment = new DomainsListFragment();
312 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
313 supportFragmentManager.executePendingTransactions();
315 // Populate the list of domains. `-1` highlights the first domain if in two-paned mode. It has no effect in single-paned mode.
316 populateDomainsListView(-1);
318 // Display the add domain FAB.
319 addDomainFAB.setVisibility(View.VISIBLE);
321 // Hide the delete menu item.
322 deleteMenuItem.setVisible(false);
323 } else { // The device is in single-paned mode and `DomainsListFragment` is displayed.
324 // Dismiss the undo delete `SnackBar` if it is shown.
325 if (undoDeleteSnackbar != null && undoDeleteSnackbar.isShown()) {
326 // Set the close flag.
327 closeActivityAfterDismissingSnackbar = true;
329 // Dismiss the snackbar.
330 undoDeleteSnackbar.dismiss();
333 NavUtils.navigateUpFromSameTask(this);
338 case R.id.delete_domain:
339 // Reset close-on-back, which otherwise can cause errors if the system attempts to save settings for a domain that no longer exists.
342 // Store a copy of `currentDomainDatabaseId` because it could change while the `Snackbar` is displayed.
343 final int databaseIdToDelete = currentDomainDatabaseId;
345 // Update the fragments and menu items.
346 if (twoPanedMode) { // Two-paned mode.
347 // Store the deleted domain position, which is needed if `Undo` is selected in the `Snackbar`.
348 deletedDomainPosition = domainsListView.getCheckedItemPosition();
350 // Disable the options `MenuItems`.
351 deleteMenuItem.setEnabled(false);
352 deleteMenuItem.setIcon(R.drawable.delete_blue);
354 // Remove the domain settings fragment.
355 supportFragmentManager.beginTransaction().remove(supportFragmentManager.findFragmentById(R.id.domain_settings_fragment_container)).commit();
356 } else { // Single-paned mode.
357 // Display `DomainsListFragment`.
358 DomainsListFragment domainsListFragment = new DomainsListFragment();
359 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
360 supportFragmentManager.executePendingTransactions();
362 // Display `addDomainFAB`.
363 addDomainFAB.setVisibility(View.VISIBLE);
365 // Hide `deleteMenuItem`.
366 deleteMenuItem.setVisible(false);
369 // Get a `Cursor` that does not show the domain to be deleted.
370 Cursor domainsPendingDeleteCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomainExcept(databaseIdToDelete);
372 // Setup `domainsPendingDeleteCursorAdapter` with `this` context. `false` disables `autoRequery`.
373 CursorAdapter domainsPendingDeleteCursorAdapter = new CursorAdapter(this, domainsPendingDeleteCursor, false) {
375 public View newView(Context context, Cursor cursor, ViewGroup parent) {
376 // Inflate the individual item layout. `false` does not attach it to the root.
377 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
381 public void bindView(View view, Context context, Cursor cursor) {
382 // Set the domain name.
383 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
384 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
385 domainNameTextView.setText(domainNameString);
389 // Update the handle for the current `domains_listview`.
390 domainsListView = findViewById(R.id.domains_listview);
392 // Update the `ListView`.
393 domainsListView.setAdapter(domainsPendingDeleteCursorAdapter);
395 // Get a handle for the activity.
396 Activity activity = this;
398 // Display a `Snackbar`.
399 undoDeleteSnackbar = Snackbar.make(domainsListView, R.string.domain_deleted, Snackbar.LENGTH_LONG)
400 .setAction(R.string.undo, (View v) -> {
401 // Do nothing because everything will be handled by `onDismissed()` below.
403 .addCallback(new Snackbar.Callback() {
405 public void onDismissed(Snackbar snackbar, int event) {
407 // The user pushed the `Undo` button.
408 case Snackbar.Callback.DISMISS_EVENT_ACTION:
409 // Store `databaseId` in `argumentsBundle`.
410 Bundle argumentsBundle = new Bundle();
411 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, databaseIdToDelete);
413 // Add `argumentsBundle` to `domainSettingsFragment`.
414 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
415 domainSettingsFragment.setArguments(argumentsBundle);
417 // Display the correct fragments.
418 if (twoPanedMode) { // The device in in two-paned mode.
419 // Get a `Cursor` with the current contents of the domains database.
420 Cursor undoDeleteDomainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
422 // Setup `domainsCursorAdapter` with `this` context. `false` disables `autoRequery`.
423 CursorAdapter undoDeleteDomainsCursorAdapter = new CursorAdapter(context, undoDeleteDomainsCursor, false) {
425 public View newView(Context context, Cursor cursor, ViewGroup parent) {
426 // Inflate the individual item layout. `false` does not attach it to the root.
427 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
431 public void bindView(View view, Context context, Cursor cursor) {
432 // Set the domain name.
433 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
434 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
435 domainNameTextView.setText(domainNameString);
439 // Update the `ListView`.
440 domainsListView.setAdapter(undoDeleteDomainsCursorAdapter);
441 // Select the previously deleted domain in `domainsListView`.
442 domainsListView.setItemChecked(deletedDomainPosition, true);
444 // Display `domainSettingsFragment`.
445 supportFragmentManager.beginTransaction().replace(R.id.domain_settings_fragment_container, domainSettingsFragment).commit();
447 // Enable the options `MenuItems`.
448 deleteMenuItem.setEnabled(true);
449 deleteMenuItem.setIcon(R.drawable.delete_light);
450 } else { // The device in in one-paned mode.
451 // Display `domainSettingsFragment`.
452 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
454 // Hide `add_domain_fab`.
455 FloatingActionButton addDomainFAB = findViewById(R.id.add_domain_fab);
456 addDomainFAB.setVisibility(View.GONE);
458 // Show and enable `deleteMenuItem`.
459 deleteMenuItem.setVisible(true);
461 // Display `domainSettingsFragment`.
462 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
466 // The `Snackbar` was dismissed without the `Undo` button being pushed.
468 // Delete the selected domain.
469 domainsDatabaseHelper.deleteDomain(databaseIdToDelete);
471 // Enable the delete menu item if the system was waiting for a snackbar to be dismissed.
472 if (dismissingSnackbar) {
473 // Create a `Runnable` to enable the delete menu item.
474 Runnable enableDeleteMenuItemRunnable = () -> {
475 // Enable `deleteMenuItem` according to the display mode.
476 if (twoPanedMode) { // Two-paned mode.
477 // Enable `deleteMenuItem`.
478 deleteMenuItem.setEnabled(true);
480 // Set the delete icon according to the theme.
481 if (MainWebViewActivity.darkTheme) {
482 deleteMenuItem.setIcon(R.drawable.delete_dark);
484 deleteMenuItem.setIcon(R.drawable.delete_light);
486 } else { // Single-paned mode.
487 // Show `deleteMenuItem`.
488 deleteMenuItem.setVisible(true);
491 // Reset `dismissingSnackbar`.
492 dismissingSnackbar = false;
495 // Enable the delete menu icon after 100 milliseconds to make sure that the previous domain has been deleted from the database.
496 Handler handler = new Handler();
497 handler.postDelayed(enableDeleteMenuItemRunnable, 100);
500 // Close the activity if back was pressed.
501 if (closeActivityAfterDismissingSnackbar) {
503 NavUtils.navigateUpFromSameTask(activity);
511 // Show the Snackbar.
512 undoDeleteSnackbar.show();
516 // Consume the event.
521 protected void onSaveInstanceState(Bundle outState) {
522 // Store the current `DomainSettingsFragment` state in `outState`.
523 if (findViewById(R.id.domain_settings_scrollview) != null) { // `DomainSettingsFragment` is displayed.
524 // Save any changes that have been made to the domain settings.
525 saveDomainSettings(coordinatorLayout, resources);
527 // Store `DomainSettingsDisplayed`.
528 outState.putBoolean("domainSettingsDisplayed", true);
529 outState.putInt("domainSettingsDatabaseId", DomainSettingsFragment.databaseId);
530 } else { // `DomainSettingsFragment` is not displayed.
531 outState.putBoolean("domainSettingsDisplayed", false);
532 outState.putInt("domainSettingsDatabaseId", -1);
535 super.onSaveInstanceState(outState);
538 // Control what the navigation bar back button does.
540 public void onBackPressed() {
541 if (twoPanedMode) { // The device is in two-paned mode.
542 // Save the current domain settings if the domain settings fragment is displayed.
543 if (findViewById(R.id.domain_settings_scrollview) != null) {
544 saveDomainSettings(coordinatorLayout, resources);
547 // Dismiss the undo delete SnackBar if it is shown.
548 if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
549 // Set the close flag.
550 closeActivityAfterDismissingSnackbar = true;
552 // Dismiss the snackbar.
553 undoDeleteSnackbar.dismiss();
555 // Pass `onBackPressed()` to the system.
556 super.onBackPressed();
558 } else if (closeOnBack) { // Go directly back to the main WebView activity because the domains activity was launched from the options menu.
559 // Save the current domain settings.
560 saveDomainSettings(coordinatorLayout, resources);
562 // Pass `onBackPressed()` to the system.
563 super.onBackPressed();
564 } else if (findViewById(R.id.domain_settings_scrollview) != null) { // The device is in single-paned mode and domain settings fragment is displayed.
565 // Save the current domain settings.
566 saveDomainSettings(coordinatorLayout, resources);
568 // Display the domains list fragment.
569 DomainsListFragment domainsListFragment = new DomainsListFragment();
570 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainsListFragment).commit();
571 supportFragmentManager.executePendingTransactions();
573 // Populate the list of domains. `-1` highlights the first domain if in two-paned mode. It has no effect in single-paned mode.
574 populateDomainsListView(-1);
576 // Display the add domain FAB.
577 addDomainFAB.setVisibility(View.VISIBLE);
579 // Hide the delete menu item.
580 deleteMenuItem.setVisible(false);
581 } else { // The device is in single-paned mode and the domain list fragment is displayed.
582 // Dismiss the undo delete SnackBar if it is shown.
583 if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
584 // Set the close flag.
585 closeActivityAfterDismissingSnackbar = true;
587 // Dismiss the snackbar.
588 undoDeleteSnackbar.dismiss();
590 // Pass `onBackPressed()` to the system.
591 super.onBackPressed();
597 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
598 // Dismiss the undo delete snackbar if it is currently displayed.
599 if ((undoDeleteSnackbar != null) && undoDeleteSnackbar.isShown()) {
600 undoDeleteSnackbar.dismiss();
603 // Get the new domain name String from the dialog fragment.
604 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
605 String domainNameString = domainNameEditText.getText().toString();
607 // Create the domain and store the database ID in `currentDomainDatabaseId`.
608 currentDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
610 // Display the newly created domain.
611 if (twoPanedMode) { // The device in in two-paned mode.
612 populateDomainsListView(currentDomainDatabaseId);
613 } else { // The device is in single-paned mode.
614 // Hide `add_domain_fab`.
615 addDomainFAB.setVisibility(View.GONE);
617 // Show and enable `deleteMenuItem`.
618 DomainsActivity.deleteMenuItem.setVisible(true);
620 // Add `currentDomainDatabaseId` to `argumentsBundle`.
621 Bundle argumentsBundle = new Bundle();
622 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
624 // Add `argumentsBundle` to `domainSettingsFragment`.
625 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
626 domainSettingsFragment.setArguments(argumentsBundle);
628 // Display `domainSettingsFragment`.
629 supportFragmentManager.beginTransaction().replace(R.id.domains_listview_fragment_container, domainSettingsFragment).commit();
633 public void saveDomainSettings(View view, Resources resources) {
634 // Get handles for the domain settings.
635 EditText domainNameEditText = view.findViewById(R.id.domain_settings_name_edittext);
636 Switch javaScriptSwitch = view.findViewById(R.id.domain_settings_javascript_switch);
637 Switch firstPartyCookiesSwitch = view.findViewById(R.id.domain_settings_first_party_cookies_switch);
638 Switch thirdPartyCookiesSwitch = view.findViewById(R.id.domain_settings_third_party_cookies_switch);
639 Switch domStorageSwitch = view.findViewById(R.id.domain_settings_dom_storage_switch);
640 Switch formDataSwitch = view.findViewById(R.id.domain_settings_form_data_switch); // Form data can be removed once the minimum API >= 26.
641 Switch easyListSwitch = view.findViewById(R.id.domain_settings_easylist_switch);
642 Switch easyPrivacySwitch = view.findViewById(R.id.domain_settings_easyprivacy_switch);
643 Switch fanboysAnnoyanceSwitch = view.findViewById(R.id.domain_settings_fanboys_annoyance_list_switch);
644 Switch fanboysSocialBlockingSwitch = view.findViewById(R.id.domain_settings_fanboys_social_blocking_list_switch);
645 Switch ultraPrivacySwitch = view.findViewById(R.id.domain_settings_ultraprivacy_switch);
646 Switch blockAllThirdPartyRequestsSwitch = view.findViewById(R.id.domain_settings_block_all_third_party_requests_switch);
647 Spinner userAgentSpinner = view.findViewById(R.id.domain_settings_user_agent_spinner);
648 EditText customUserAgentEditText = view.findViewById(R.id.domain_settings_custom_user_agent_edittext);
649 Spinner fontSizeSpinner = view.findViewById(R.id.domain_settings_font_size_spinner);
650 Spinner swipeToRefreshSpinner = view.findViewById(R.id.domain_settings_swipe_to_refresh_spinner);
651 Spinner displayWebpageImagesSpinner = view.findViewById(R.id.domain_settings_display_webpage_images_spinner);
652 Spinner nightModeSpinner = view.findViewById(R.id.domain_settings_night_mode_spinner);
653 Switch pinnedSslCertificateSwitch = view.findViewById(R.id.domain_settings_pinned_ssl_certificate_switch);
654 RadioButton savedSslCertificateRadioButton = view.findViewById(R.id.saved_ssl_certificate_radiobutton);
655 RadioButton currentWebsiteCertificateRadioButton = view.findViewById(R.id.current_website_certificate_radiobutton);
657 // Extract the data for the domain settings.
658 String domainNameString = domainNameEditText.getText().toString();
659 boolean javaScriptEnabled = javaScriptSwitch.isChecked();
660 boolean firstPartyCookiesEnabled = firstPartyCookiesSwitch.isChecked();
661 boolean thirdPartyCookiesEnabled = thirdPartyCookiesSwitch.isChecked();
662 boolean domStorageEnabled = domStorageSwitch.isChecked();
663 boolean formDataEnabled = formDataSwitch.isChecked(); // Form data can be removed once the minimum API >= 26.
664 boolean easyListEnabled = easyListSwitch.isChecked();
665 boolean easyPrivacyEnabled = easyPrivacySwitch.isChecked();
666 boolean fanboysAnnoyanceEnabled = fanboysAnnoyanceSwitch.isChecked();
667 boolean fanboysSocialBlockingEnabled = fanboysSocialBlockingSwitch.isChecked();
668 boolean ultraPrivacyEnabled = ultraPrivacySwitch.isChecked();
669 boolean blockAllThirdPartyRequests = blockAllThirdPartyRequestsSwitch.isChecked();
670 int userAgentPosition = userAgentSpinner.getSelectedItemPosition();
671 int fontSizePosition = fontSizeSpinner.getSelectedItemPosition();
672 int swipeToRefreshInt = swipeToRefreshSpinner.getSelectedItemPosition();
673 int displayWebpageImagesInt = displayWebpageImagesSpinner.getSelectedItemPosition();
674 int nightModeInt = nightModeSpinner.getSelectedItemPosition();
675 boolean pinnedSslCertificate = pinnedSslCertificateSwitch.isChecked();
677 // Initialize the user agent name string.
678 String userAgentName;
680 // Set the user agent name.
681 switch (userAgentPosition) {
682 case MainWebViewActivity.DOMAINS_SYSTEM_DEFAULT_USER_AGENT:
683 // Set the user agent name to be `System default user agent`.
684 userAgentName = resources.getString(R.string.system_default_user_agent);
687 case MainWebViewActivity.DOMAINS_CUSTOM_USER_AGENT:
688 // Set the user agent name to be the custom user agent.
689 userAgentName = customUserAgentEditText.getText().toString();
693 // Get the array of user agent names.
694 String[] userAgentNameArray = resources.getStringArray(R.array.user_agent_names);
696 // Set the user agent name from the array. The domain spinner has one more entry than the name array, so the position must be decremented.
697 userAgentName = userAgentNameArray[userAgentPosition - 1];
700 // Get the font size integer.
701 int fontSizeInt = Integer.parseInt(resources.getStringArray(R.array.domain_settings_font_size_entry_values)[fontSizePosition]);
703 // Save the domain settings.
704 if (savedSslCertificateRadioButton.isChecked()) { // The current certificate is being used.
705 // Update the database except for the certificate.
706 domainsDatabaseHelper.updateDomainExceptCertificate(DomainsActivity.currentDomainDatabaseId, domainNameString, javaScriptEnabled, firstPartyCookiesEnabled, thirdPartyCookiesEnabled,
707 domStorageEnabled, formDataEnabled, easyListEnabled, easyPrivacyEnabled, fanboysAnnoyanceEnabled, fanboysSocialBlockingEnabled, ultraPrivacyEnabled, blockAllThirdPartyRequests,
708 userAgentName, fontSizeInt, swipeToRefreshInt, nightModeInt, displayWebpageImagesInt, pinnedSslCertificate);
709 } else if (currentWebsiteCertificateRadioButton.isChecked()) { // The certificate is being updated with the current website certificate.
710 // Get the current website SSL certificate.
711 SslCertificate currentWebsiteSslCertificate = MainWebViewActivity.sslCertificate;
713 // Store the values from the SSL certificate.
714 String issuedToCommonName = currentWebsiteSslCertificate.getIssuedTo().getCName();
715 String issuedToOrganization = currentWebsiteSslCertificate.getIssuedTo().getOName();
716 String issuedToOrganizationalUnit = currentWebsiteSslCertificate.getIssuedTo().getUName();
717 String issuedByCommonName = currentWebsiteSslCertificate.getIssuedBy().getCName();
718 String issuedByOrganization = currentWebsiteSslCertificate.getIssuedBy().getOName();
719 String issuedByOrganizationalUnit = currentWebsiteSslCertificate.getIssuedBy().getUName();
720 long startDateLong = currentWebsiteSslCertificate.getValidNotBeforeDate().getTime();
721 long endDateLong = currentWebsiteSslCertificate.getValidNotAfterDate().getTime();
723 // Update the database.
724 domainsDatabaseHelper.updateDomainWithCertificate(currentDomainDatabaseId, domainNameString, javaScriptEnabled, firstPartyCookiesEnabled, thirdPartyCookiesEnabled, domStorageEnabled,
725 formDataEnabled, easyListEnabled, easyPrivacyEnabled, fanboysAnnoyanceEnabled, fanboysSocialBlockingEnabled, ultraPrivacyEnabled, blockAllThirdPartyRequests, userAgentName, fontSizeInt,
726 swipeToRefreshInt, nightModeInt, displayWebpageImagesInt, pinnedSslCertificate, issuedToCommonName, issuedToOrganization, issuedToOrganizationalUnit, issuedByCommonName,
727 issuedByOrganization, issuedByOrganizationalUnit, startDateLong, endDateLong);
729 } else { // No certificate is selected.
730 // Update the database, with PINNED_SSL_CERTIFICATE set to false.
731 domainsDatabaseHelper.updateDomainExceptCertificate(currentDomainDatabaseId, domainNameString, javaScriptEnabled, firstPartyCookiesEnabled, thirdPartyCookiesEnabled, domStorageEnabled,
732 formDataEnabled, easyListEnabled, easyPrivacyEnabled, fanboysAnnoyanceEnabled, fanboysSocialBlockingEnabled, ultraPrivacyEnabled, blockAllThirdPartyRequests, userAgentName, fontSizeInt,
733 swipeToRefreshInt, nightModeInt, displayWebpageImagesInt,false);
737 private void populateDomainsListView(final int highlightedDomainDatabaseId) {
738 // get a handle for the current `domains_listview`.
739 domainsListView = findViewById(R.id.domains_listview);
741 // Get a `Cursor` with the current contents of the domains database.
742 Cursor domainsCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
744 // Setup `domainsCursorAdapter` with `this` context. `false` disables `autoRequery`.
745 CursorAdapter domainsCursorAdapter = new CursorAdapter(context, domainsCursor, false) {
747 public View newView(Context context, Cursor cursor, ViewGroup parent) {
748 // Inflate the individual item layout. `false` does not attach it to the root.
749 return getLayoutInflater().inflate(R.layout.domain_name_linearlayout, parent, false);
753 public void bindView(View view, Context context, Cursor cursor) {
754 // Set the domain name.
755 String domainNameString = cursor.getString(cursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME));
756 TextView domainNameTextView = view.findViewById(R.id.domain_name_textview);
757 domainNameTextView.setText(domainNameString);
761 // Update the `ListView`.
762 domainsListView.setAdapter(domainsCursorAdapter);
764 // Display the domain settings in the second pane if operating in two pane mode and the database contains at least one domain.
765 if (DomainsActivity.twoPanedMode && (domainsCursor.getCount() > 0)) { // Two-paned mode is enabled and there is at least one domain.
766 // Initialize `highlightedDomainPosition`.
767 int highlightedDomainPosition = 0;
769 // Get the cursor position for the highlighted domain.
770 for (int i = 0; i < domainsCursor.getCount(); i++) {
771 // Move to position `i` in the cursor.
772 domainsCursor.moveToPosition(i);
774 // Get the database ID for this position.
775 int currentDatabaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
777 // Set `highlightedDomainPosition` if the database ID for this matches `highlightedDomainDatabaseId`.
778 if (highlightedDomainDatabaseId == currentDatabaseId) {
779 highlightedDomainPosition = i;
783 // Select the highlighted domain.
784 domainsListView.setItemChecked(highlightedDomainPosition, true);
786 // Get the `databaseId` for the highlighted domain.
787 domainsCursor.moveToPosition(highlightedDomainPosition);
788 currentDomainDatabaseId = domainsCursor.getInt(domainsCursor.getColumnIndex(DomainsDatabaseHelper._ID));
790 // Store `databaseId` in `argumentsBundle`.
791 Bundle argumentsBundle = new Bundle();
792 argumentsBundle.putInt(DomainSettingsFragment.DATABASE_ID, currentDomainDatabaseId);
794 // Add `argumentsBundle` to `domainSettingsFragment`.
795 DomainSettingsFragment domainSettingsFragment = new DomainSettingsFragment();
796 domainSettingsFragment.setArguments(argumentsBundle);
798 // Display `domainSettingsFragment`.
799 supportFragmentManager.beginTransaction().replace(R.id.domain_settings_fragment_container, domainSettingsFragment).commit();
801 // Enable the options `MenuItems`.
802 deleteMenuItem.setEnabled(true);
804 // Set the delete icon according to the theme.
805 if (MainWebViewActivity.darkTheme) {
806 deleteMenuItem.setIcon(R.drawable.delete_dark);
808 deleteMenuItem.setIcon(R.drawable.delete_light);
810 } else if (twoPanedMode) { // Two-paned mode is enabled but there are no domains.
811 // Disable the options `MenuItems`.
812 deleteMenuItem.setEnabled(false);
813 deleteMenuItem.setIcon(R.drawable.delete_blue);