import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
+import android.app.Dialog;
import android.app.DownloadManager;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
+import android.os.Message;
import android.preference.PreferenceManager;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
+import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
+import com.stoutner.privacybrowser.dialogs.SaveWebpageImageDialog;
import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
+import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
+import com.stoutner.privacybrowser.helpers.FileNameHelper;
import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
import com.stoutner.privacybrowser.views.NestedScrollWebView;
// AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
- EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, PopulateBlocklists.PopulateBlocklistsListener, WebViewTabFragment.NewTabListener {
+ EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageImageDialog.SaveWebpageImageListener,
+ StoragePermissionDialog.StoragePermissionDialogListener, WebViewTabFragment.NewTabListener {
// `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
public static String orbotStatus;
public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
+ // Start activity for result request codes.
+ private final int FILE_UPLOAD_REQUEST_CODE = 0;
+ public final static int BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 1;
// The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
// `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
private String downloadImageUrl;
- // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
+ // The save website image file path string is used in `onSaveWebpageImage()` and `onRequestPermissionResult()`
+ private String saveWebsiteImageFilePath;
+
+ // The permission result request codes are used in `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, `onSaveWebpageImage()`,
+ // `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
+ private final int SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 3;
@Override
// Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
@SuppressLint("ClickableViewAccessibility")
protected void onCreate(Bundle savedInstanceState) {
+ if (Build.VERSION.SDK_INT >= 21) {
+ WebView.enableSlowWholeDocumentDraw();
+ }
+
// Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.add_or_edit_domain:
// Make it so.
startActivity(domainsIntent);
}
+
+ // Consume the event.
return true;
case R.id.toggle_first_party_cookies:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.toggle_third_party_cookies:
// Reload the current WebView.
currentWebView.reload();
} // Else do nothing because SDK < 21.
+
+ // Consume the event.
return true;
case R.id.toggle_dom_storage:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
// Form data can be removed once the minimum API >= 26.
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.clear_cookies:
}
})
.show();
+
+ // Consume the event.
return true;
case R.id.clear_dom_storage:
}
})
.show();
+
+ // Consume the event.
return true;
// Form data can be remove once the minimum API >= 26.
}
})
.show();
+
+ // Consume the event.
return true;
case R.id.easylist:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.easyprivacy:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.fanboys_annoyance_list:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.fanboys_social_blocking_list:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.ultraprivacy:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.block_all_third_party_requests:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_privacy_browser:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_webview_default:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_firefox_on_android:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_chrome_on_android:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_safari_on_ios:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_firefox_on_linux:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_chromium_on_linux:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_firefox_on_windows:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_chrome_on_windows:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_edge_on_windows:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_internet_explorer_on_windows:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_safari_on_macos:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.user_agent_custom:
// Reload the current WebView.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.font_size_twenty_five_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(25);
+
+ // Consume the event.
return true;
case R.id.font_size_fifty_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(50);
+
+ // Consume the event.
return true;
case R.id.font_size_seventy_five_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(75);
+
+ // Consume the event.
return true;
case R.id.font_size_one_hundred_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(100);
+
+ // Consume the event.
return true;
case R.id.font_size_one_hundred_twenty_five_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(125);
+
+ // Consume the event.
return true;
case R.id.font_size_one_hundred_fifty_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(150);
+
+ // Consume the event.
return true;
case R.id.font_size_one_hundred_seventy_five_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(175);
+
+ // Consume the event.
return true;
case R.id.font_size_two_hundred_percent:
+ // Set the font size.
currentWebView.getSettings().setTextZoom(200);
+
+ // Consume the event.
return true;
case R.id.swipe_to_refresh:
// Disable the swipe refresh layout.
swipeRefreshLayout.setEnabled(false);
}
+
+ // Consume the event.
return true;
case R.id.wide_viewport:
// Toggle the viewport.
currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
+
+ // Consume the event.
return true;
case R.id.display_images:
// Enable loading of images. Missing images will be loaded without the need for a reload.
currentWebView.getSettings().setLoadsImagesAutomatically(true);
}
+
+ // Consume the event.
return true;
case R.id.night_mode:
// Reload the website.
currentWebView.reload();
+
+ // Consume the event.
return true;
case R.id.find_on_page:
// Display the keyboard. `0` sets no input flags.
inputMethodManager.showSoftInput(findOnPageEditText, 0);
}, 200);
+
+ // Consume the event.
return true;
case R.id.print:
// Print the document.
printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
+
+ // Consume the event.
+ return true;
+
+ case R.id.save_as_image:
+ // Instantiate the save webpage image dialog.
+ DialogFragment saveWebpageImageDialogFragment = new SaveWebpageImageDialog();
+
+ // Show the save webpage image dialog.
+ saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_as_image));
+
+ // Consume the event.
return true;
case R.id.add_to_homescreen:
// Show the create home screen shortcut dialog.
createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
+
+ // Consume the event.
return true;
case R.id.view_source:
// Make it so.
startActivity(viewSourceIntent);
+
+ // Consume the event.
return true;
case R.id.share_url:
// Make it so.
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
+
+ // Consume the event.
return true;
case R.id.open_with_app:
+ // Open the URL with an outside app.
openWithApp(currentWebView.getUrl());
+
+ // Consume the event.
return true;
case R.id.open_with_browser:
+ // Open the URL with an outside browser.
openWithBrowser(currentWebView.getUrl());
+
+ // Consume the event.
return true;
case R.id.proxy_through_orbot:
// Apply the proxy through Orbot settings.
applyProxyThroughOrbot(true);
+
+ // Consume the event.
return true;
case R.id.refresh:
// Stop the loading of the WebView.
currentWebView.stopLoading();
}
+
+ // Consume the event.
return true;
case R.id.ad_consent:
- // Display the ad consent dialog.
+ // Instantiate the ad consent dialog.
DialogFragment adConsentDialogFragment = new AdConsentDialog();
+
+ // Display the ad consent dialog.
adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
+
+ // Consume the event.
return true;
default:
// Store the hit test result.
final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
- // Create the URL strings.
+ // Define the URL strings.
final String imageUrl;
final String linkUrl;
menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
// Load the link URL in a new tab.
addNewTab(linkUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add an Open with App entry.
menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
openWithApp(linkUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add an Open with Browser entry.
menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
openWithBrowser(linkUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add a Copy URL entry.
// Set the `ClipData` as the clipboard's primary clip.
clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add a Download URL entry.
downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
}
}
- return false;
+
+ // Consume the event.
+ return true;
});
// Add a Cancel entry, which by default closes the context menu.
// Make it so.
startActivity(emailIntent);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add a Copy Email Address entry.
// Set the `ClipData` as the clipboard's primary clip.
clipboardManager.setPrimaryClip(srcEmailTypeClipData);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add a `Cancel` entry, which by default closes the `ContextMenu`.
menu.add(R.string.cancel);
break;
- // `IMAGE_TYPE` is an image. `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link. Privacy Browser processes them the same.
+ // `IMAGE_TYPE` is an image.
case WebView.HitTestResult.IMAGE_TYPE:
- case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
// Get the image URL.
imageUrl = hitTestResult.getExtra();
menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
// Load the image URL in a new tab.
addNewTab(imageUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add a View Image entry.
menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
+ // Load the image in the current tab.
loadUrl(imageUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
- // Add a `Download Image` entry.
+ // Add a Download Image entry.
menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
// Check if the download should be processed by an external app.
if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
// Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
} else { // Show the permission request directly.
- // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
+ // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
}
} else { // The storage permission has already been granted.
downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
}
}
- return false;
+
+ // Consume the event.
+ return true;
});
- // Add a `Copy URL` entry.
- menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
- // Save the image URL in a `ClipData`.
- ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
+ // Add a Copy URL entry.
+ menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Save the image URL in a clip data.
+ ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
- // Set the `ClipData` as the clipboard's primary clip.
- clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
- return false;
+ // Set the clip data as the clipboard's primary clip.
+ clipboardManager.setPrimaryClip(imageTypeClipData);
+
+ // Consume the event.
+ return true;
});
// Add an Open with App entry.
menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the image URL with an external app.
openWithApp(imageUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
// Add an Open with Browser entry.
menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the image URL with an external browser.
openWithBrowser(imageUrl);
- return false;
+
+ // Consume the event.
+ return true;
});
- // Add a `Cancel` entry, which by default closes the `ContextMenu`.
+ // Add a Cancel entry, which by default closes the context menu.
+ menu.add(R.string.cancel);
+ break;
+
+ // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
+ case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
+ // Get the image URL.
+ imageUrl = hitTestResult.getExtra();
+
+ // Instantiate a handler.
+ Handler handler = new Handler();
+
+ // Get a message from the handler.
+ Message message = handler.obtainMessage();
+
+ // Request the image details from the last touched node be returned in the message.
+ currentWebView.requestFocusNodeHref(message);
+
+ // Get the link URL from the message data.
+ linkUrl = message.getData().getString("url");
+
+ // Set the link URL as the title of the context menu.
+ menu.setHeaderTitle(linkUrl);
+
+ // Add an Open in New Tab entry.
+ menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
+ // Load the link URL in a new tab.
+ addNewTab(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a View Image entry.
+ menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
+ // View the image in the current tab.
+ loadUrl(imageUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Download Image entry.
+ menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
+ // Check if the download should be processed by an external app.
+ if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
+ openUrlWithExternalApp(imageUrl);
+ } else { // Download with Android's download manager.
+ // Check to see if the storage permission has already been granted.
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
+ // Store the image URL for use by `onRequestPermissionResult()`.
+ downloadImageUrl = imageUrl;
+
+ // Show a dialog if the user has previously denied the permission.
+ if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
+ // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
+ DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
+
+ // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
+ downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
+ } else { // Show the permission request directly.
+ // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
+ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
+ }
+ } else { // The storage permission has already been granted.
+ // Get a handle for the download image alert dialog.
+ DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
+
+ // Show the download image alert dialog.
+ downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
+ }
+ }
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a Copy URL entry.
+ menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
+ // Save the link URL in a clip data.
+ ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
+
+ // Set the clip data as the clipboard's primary clip.
+ clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with App entry.
+ menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the link URL with an external app.
+ openWithApp(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add an Open with Browser entry.
+ menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
+ // Open the link URL with an external browser.
+ openWithBrowser(linkUrl);
+
+ // Consume the event.
+ return true;
+ });
+
+ // Add a cancel entry, which by default closes the context menu.
menu.add(R.string.cancel);
break;
}
// Reset the image URL variable.
downloadImageUrl = "";
break;
+
+ case SAVE_WEBPAGE_IMAGE_REQUEST_CODE:
+ // Check to see if the storage permission was granted. If the dialog was canceled the grant result will be empty.
+ if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
+ // Save the webpage image.
+ new SaveWebpageImage(this, currentWebView).execute(saveWebsiteImageFilePath);
+ } else { // The storage permission was not granted.
+ // Display an error snackbar.
+ Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
+ }
+
+ // Reset the save website image file path.
+ saveWebsiteImageFilePath = "";
+ break;
}
}
}
}
- // Process the results of an upload file chooser. Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
+ // Process the results of a file browse.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
- // File uploads only work on API >= 21.
- if (Build.VERSION.SDK_INT >= 21) {
- // Pass the file to the WebView.
- fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
+ // Run the commands that correlate to the specified request code.
+ switch (requestCode) {
+ case FILE_UPLOAD_REQUEST_CODE:
+ // File uploads only work on API >= 21.
+ if (Build.VERSION.SDK_INT >= 21) {
+ // Pass the file to the WebView.
+ fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
+ }
+ break;
+
+ case BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE:
+ // Don't do anything if the user pressed back from the file picker.
+ if (resultCode == Activity.RESULT_OK) {
+ // Get a handle for the save dialog fragment.
+ DialogFragment saveWebpageImageDialogFragment= (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_as_image));
+
+ // Only update the file name if the dialog still exists.
+ if (saveWebpageImageDialogFragment != null) {
+ // Get a handle for the save webpage image dialog.
+ Dialog saveWebpageImageDialog = saveWebpageImageDialogFragment.getDialog();
+
+ // Get a handle for the file name edit text.
+ EditText fileNameEditText = saveWebpageImageDialog.findViewById(R.id.file_name_edittext);
+
+ // Instantiate the file name helper.
+ FileNameHelper fileNameHelper = new FileNameHelper();
+
+ // Convert the file name URI to a file name path.
+ String fileNamePath = fileNameHelper.convertUriToFileNamePath(data.getData());
+
+ // Set the file name path as the text of the file name edit text.
+ fileNameEditText.setText(fileNamePath);
+ }
+ }
+ break;
}
}
inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
}
+ @Override
+ public void onSaveWebpageImage(DialogFragment dialogFragment) {
+ // Get a handle for the file name edit text.
+ EditText fileNameEditText = dialogFragment.getDialog().findViewById(R.id.file_name_edittext);
+
+ // Get the file path string.
+ saveWebsiteImageFilePath = fileNameEditText.getText().toString();
+
+ // Check to see if the storage permission is needed.
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
+ // Save the webpage image.
+ new SaveWebpageImage(this, currentWebView).execute(saveWebsiteImageFilePath);
+ } else { // The storage permission has not been granted.
+ // Get the external private directory `File`.
+ File externalPrivateDirectoryFile = getExternalFilesDir(null);
+
+ // Remove the incorrect lint error below that the file might be null.
+ assert externalPrivateDirectoryFile != null;
+
+ // Get the external private directory string.
+ String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
+
+ // Check to see if the file path is in the external private directory.
+ if (saveWebsiteImageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
+ // Save the webpage image.
+ new SaveWebpageImage(this, currentWebView).execute(saveWebsiteImageFilePath);
+ } else { // The file path is in a public directory.
+ // Check if the user has previously denied the storage permission.
+ if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
+ // Instantiate the storage permission alert dialog.
+ DialogFragment storagePermissionDialogFragment = new StoragePermissionDialog();
+
+ // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
+ storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
+ } else { // Show the permission request directly.
+ // Request the write external storage permission. The webpage image will be saved when it finishes.
+ ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, SAVE_WEBPAGE_IMAGE_REQUEST_CODE);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onCloseStoragePermissionDialog() {
+ // Request the write external storage permission. The webpage image will be saved when it finishes.
+ ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, SAVE_WEBPAGE_IMAGE_REQUEST_CODE);
+ }
+
private void applyAppSettings() {
// Initialize the app if this is the first run. This is done here instead of in `onCreate()` to shorten the time that an unthemed background is displayed on app startup.
if (webViewDefaultUserAgent == null) {
// Flag the intent to open in a new task.
openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- // Show the chooser.
- startActivity(openWithAppIntent);
+ try {
+ // Show the chooser.
+ startActivity(openWithAppIntent);
+ } catch (ActivityNotFoundException exception) {
+ // Show a snackbar with the error.
+ Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
+ }
}
private void openWithBrowser(String url) {
// Flag the intent to open in a new task.
openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- // Show the chooser.
- startActivity(openWithBrowserIntent);
+ try {
+ // Show the chooser.
+ startActivity(openWithBrowserIntent);
+ } catch (ActivityNotFoundException exception) {
+ // Show a snackbar with the error.
+ Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
+ }
}
private String sanitizeUrl(String url) {
// Create an intent to open a chooser based ont the file chooser parameters.
Intent fileChooserIntent = fileChooserParams.createIntent();
- // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
- startActivityForResult(fileChooserIntent, 0);
+ // Open the file chooser.
+ startActivityForResult(fileChooserIntent, FILE_UPLOAD_REQUEST_CODE);
}
return true;
}