]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blobdiff - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
Implement find on page. https://redmine.stoutner.com/issues/9
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / MainWebViewActivity.java
index ff63632a9f26e8a40d6a7de4d1db5b67807b3aea..7928c944a52df874a6aa95f9aad48b39e687b41d 100644 (file)
@@ -20,7 +20,6 @@
 package com.stoutner.privacybrowser;
 
 import android.annotation.SuppressLint;
-import android.app.Activity;
 import android.app.DialogFragment;
 import android.app.DownloadManager;
 import android.content.Context;
@@ -51,6 +50,8 @@ import android.support.v7.app.ActionBarDrawerToggle;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.app.AppCompatDialogFragment;
 import android.support.v7.widget.Toolbar;
+import android.text.Editable;
+import android.text.TextWatcher;
 import android.util.Patterns;
 import android.view.KeyEvent;
 import android.view.Menu;
@@ -68,7 +69,10 @@ import android.webkit.WebViewDatabase;
 import android.widget.EditText;
 import android.widget.FrameLayout;
 import android.widget.ImageView;
+import android.widget.LinearLayout;
 import android.widget.ProgressBar;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
 
 import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
@@ -82,7 +86,7 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
         SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener {
 
     // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
-    // It is also used in `onCreate()` and `onOptionsItemSelected()`.
+    // It is also used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
     public static ActionBar appBar;
 
     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
@@ -97,7 +101,7 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
     public static SslCertificate sslCertificate;
 
 
-    // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `loadUrlFromTextBox()`.
+    // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage`, and `loadUrlFromTextBox()`.
     private WebView mainWebView;
 
     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
@@ -155,7 +159,11 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
     private SslErrorHandler sslErrorHandler;
 
-    private MenuItem toggleJavaScript;
+    // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
+    private EditText findOnPageEditText;
+
+    // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
+    private InputMethodManager inputMethodManager;
 
     @Override
     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.  The whole premise of Privacy Browser is built around an understanding of these dangers.
@@ -164,6 +172,9 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main_coordinatorlayout);
 
+        // Get a handle for `inputMethodManager`.
+        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+
         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
         Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
         setSupportActionBar(supportAppBar);
@@ -179,8 +190,9 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
         // Set the "go" button on the keyboard to load the URL in urlTextBox.
         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
+            @Override
             public boolean onKey(View v, int keyCode, KeyEvent event) {
-                // If the event is a key-down event on the "enter" button, load the URL.
+                // If the event is a key-down event on the `enter` button, load the URL.
                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                     // Load the URL into the mainWebView and consume the event.
                     try {
@@ -197,7 +209,66 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
             }
         });
 
+        // Get handles for `fullScreenVideoFrameLayout`, `mainWebView`, and `find_on_page_edittext`.
         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
+        mainWebView = (WebView) findViewById(R.id.mainWebView);
+        findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
+
+        // Update `findOnPageCountTextView`.
+        mainWebView.setFindListener(new WebView.FindListener() {
+            // Get a handle for `findOnPageCountTextView`.
+            TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
+
+            @Override
+            public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
+                if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
+                    // Set `findOnPageCountTextView` to `0/0`.
+                    findOnPageCountTextView.setText(R.string.zero_of_zero);
+                } else if (isDoneCounting) {  // There are matches.
+                    // `activeMatchOrdinal` is zero-based.
+                    int activeMatch = activeMatchOrdinal + 1;
+
+                    // Set `findOnPageCountTextView`.
+                    findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
+                }
+            }
+        });
+
+        // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
+        findOnPageEditText.addTextChangedListener(new TextWatcher() {
+            @Override
+            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+                // Do nothing.
+            }
+
+            @Override
+            public void onTextChanged(CharSequence s, int start, int before, int count) {
+                // Do nothing.
+            }
+
+            @Override
+            public void afterTextChanged(Editable s) {
+                // Search for the text in `mainWebView`.
+                mainWebView.findAllAsync(findOnPageEditText.getText().toString());
+            }
+        });
+
+        // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
+        findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
+            @Override
+            public boolean onKey(View v, int keyCode, KeyEvent event) {
+                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
+                    // Hide the soft keyboard.  `0` indicates no additional flags.
+                    inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
+
+                    // Consume the event.
+                    return true;
+                } else {  // A different key was pressed.
+                    // Do not consume the event.
+                    return false;
+                }
+            }
+        });
 
         // Implement swipe to refresh
         swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
@@ -209,8 +280,6 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
             }
         });
 
-        mainWebView = (WebView) findViewById(R.id.mainWebView);
-
         // Create the navigation drawer.
         drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
         // The DrawerTitle identifies the drawer in accessibility mode.
@@ -280,8 +349,8 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
                 sslErrorHandler = handler;
 
                 // Display the SSL error `AlertDialog`.
-                DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
-                sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
+                AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
+                sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
             }
         });
 
@@ -444,7 +513,6 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
         updatePrivacyIcons(false);
 
         // Get handles for the menu items.
-        toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
@@ -743,9 +811,28 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
                 return true;
 
             case R.id.find_on_page:
-                appBar.setCustomView(R.layout.find_on_page_app_bar);
-                toggleJavaScript.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-                appBar.invalidateOptionsMenu();
+                // Hide the URL app bar.
+                Toolbar appBarToolbar = (Toolbar) findViewById(R.id.appBar);
+                appBarToolbar.setVisibility(View.GONE);
+
+                // Show the Find on Page `RelativeLayout`.
+                LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
+                findOnPageLinearLayout.setVisibility(View.VISIBLE);
+
+                // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
+                // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
+                findOnPageEditText.postDelayed(new Runnable()
+                {
+                    @Override
+                    public void run()
+                    {
+                        // Set the focus on `findOnPageEditText`.
+                        findOnPageEditText.requestFocus();
+
+                        // Display the keyboard.
+                        inputMethodManager.showSoftInput(findOnPageEditText, 0);
+                    }
+                }, 200);
                 return true;
 
             case R.id.share:
@@ -873,15 +960,22 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
                 // Clear `customHeaders`.
                 customHeaders.clear();
 
-                // Destroy the internal state of the webview.
+                // Detach all views from `mainWebViewRelativeLayout`.
+                RelativeLayout mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.mainWebViewRelativeLayout);
+                mainWebViewRelativeLayout.removeAllViews();
+
+                // Destroy the internal state of `mainWebView`.
                 mainWebView.destroy();
 
-                // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
+                // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
                 if (Build.VERSION.SDK_INT >= 21) {
                     finishAndRemoveTask();
                 } else {
                     finish();
                 }
+
+                // Remove the terminated program from RAM.  The status code is `0`.
+                System.exit(0);
                 break;
 
             default:
@@ -1070,8 +1164,36 @@ public class MainWebViewActivity extends AppCompatActivity implements Navigation
 
         mainWebView.loadUrl(formattedUrlString, customHeaders);
 
-        // Hides the keyboard so we can see the webpage.
-        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
+        // Hides the keyboard so we can see the webpage.  `0` indicates no additional flags.
+        inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
+    }
+
+    public void findPreviousOnPage(View view) {
+        // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
+        mainWebView.findNext(false);
+    }
+
+    public void findNextOnPage(View view) {
+        // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
+        mainWebView.findNext(true);
+    }
+
+    public void closeFindOnPage(View view) {
+        // Delete the contents of `find_on_page_edittext`.
+        findOnPageEditText.setText(null);
+
+        // Clear the highlighted phrases.
+        mainWebView.clearMatches();
+
+        // Hide the Find on Page `RelativeLayout`.
+        LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
+        findOnPageLinearLayout.setVisibility(View.GONE);
+
+        // Show the URL app bar.
+        Toolbar appBarToolbar = (Toolbar) findViewById(R.id.appBar);
+        appBarToolbar.setVisibility(View.VISIBLE);
+
+        // Hides the keyboard so we can see the webpage.  `0` indicates no additional flags.
         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
     }