2 * Copyright © 2017-2019 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.app.DialogFragment;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.os.Bundle;
27 import android.text.Spanned;
28 import android.text.style.ForegroundColorSpan;
29 import android.view.KeyEvent;
30 import android.view.Menu;
31 import android.view.MenuItem;
32 import android.view.View;
33 import android.view.WindowManager;
34 import android.view.inputmethod.InputMethodManager;
35 import android.widget.EditText;
37 import androidx.appcompat.app.ActionBar;
38 import androidx.appcompat.app.AppCompatActivity;
39 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
40 import androidx.core.app.NavUtils;
41 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
43 import com.stoutner.privacybrowser.R;
44 import com.stoutner.privacybrowser.asynctasks.GetSource;
45 import com.stoutner.privacybrowser.dialogs.AboutViewSourceDialog;
47 public class ViewSourceActivity extends AppCompatActivity {
48 // `activity` is used in `onCreate()` and `goBack()`.
49 private Activity activity;
51 // The color spans are used in `onCreate()` and `highlightUrlText()`.
52 private ForegroundColorSpan redColorSpan;
53 private ForegroundColorSpan initialGrayColorSpan;
54 private ForegroundColorSpan finalGrayColorSpan;
57 protected void onCreate(Bundle savedInstanceState) {
58 // Disable screenshots if not allowed.
59 if (!MainWebViewActivity.allowScreenshots) {
60 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
64 if (MainWebViewActivity.darkTheme) {
65 setTheme(R.style.PrivacyBrowserDark);
67 setTheme(R.style.PrivacyBrowserLight);
70 // Run the default commands.
71 super.onCreate(savedInstanceState);
73 // Get the launching intent
74 Intent intent = getIntent();
76 // Get the user agent.
77 String userAgent = intent.getStringExtra("user_agent");
79 // Store a handle for the current activity.
82 // Set the content view.
83 setContentView(R.layout.view_source_coordinatorlayout);
85 // The AndroidX toolbar must be used until the minimum API is >= 21.
86 Toolbar toolbar = findViewById(R.id.view_source_toolbar);
87 setSupportActionBar(toolbar);
89 // Get a handle for the action bar.
90 final ActionBar actionBar = getSupportActionBar();
92 // Remove the incorrect lint warning that the action bar might be null.
93 assert actionBar != null;
95 // Add the custom layout to the action bar.
96 actionBar.setCustomView(R.layout.view_source_app_bar);
97 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
99 // Get a handle for the url text box.
100 EditText urlEditText = findViewById(R.id.url_edittext);
102 // Get the formatted URL string from the main activity.
103 String formattedUrlString = MainWebViewActivity.formattedUrlString;
105 // Populate the URL text box.
106 urlEditText.setText(formattedUrlString);
108 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
109 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
110 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
111 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
113 // Apply text highlighting to the URL.
116 // Get a handle for the input method manager, which is used to hide the keyboard.
117 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
119 // Remove the lint warning that the input method manager might be null.
120 assert inputMethodManager != null;
122 // Remove the formatting from the URL when the user is editing the text.
123 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
124 if (hasFocus) { // The user is editing `urlTextBox`.
125 // Remove the highlighting.
126 urlEditText.getText().removeSpan(redColorSpan);
127 urlEditText.getText().removeSpan(initialGrayColorSpan);
128 urlEditText.getText().removeSpan(finalGrayColorSpan);
129 } else { // The user has stopped editing `urlTextBox`.
130 // Hide the soft keyboard.
131 inputMethodManager.hideSoftInputFromWindow(urlEditText.getWindowToken(), 0);
133 // Move to the beginning of the string.
134 urlEditText.setSelection(0);
136 // Reapply the highlighting.
141 // Set the go button on the keyboard to request new source data.
142 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
143 // Request new source data if the enter key was pressed.
144 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
145 // Hide the soft keyboard.
146 inputMethodManager.hideSoftInputFromWindow(urlEditText.getWindowToken(), 0);
148 // Remove the focus from the URL box.
149 urlEditText.clearFocus();
152 String url = urlEditText.getText().toString();
154 // Get new source data for the current URL if it beings with `http`.
155 if (url.startsWith("http")) {
156 new GetSource(this, userAgent).execute(url);
159 // Consume the key press.
162 // Do not consume the key press.
167 // Implement swipe to refresh.
168 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.view_source_swiperefreshlayout);
169 swipeRefreshLayout.setOnRefreshListener(() -> {
171 String url = urlEditText.getText().toString();
173 // Get new source data for the URL if it begins with `http`.
174 if (url.startsWith("http")) {
175 new GetSource(this, userAgent).execute(url);
177 // Stop the refresh animation.
178 swipeRefreshLayout.setRefreshing(false);
182 // Set the swipe to refresh color according to the theme.
183 if (MainWebViewActivity.darkTheme) {
184 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
185 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
187 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
190 // Get the source using an AsyncTask if the URL begins with `http`.
191 if (formattedUrlString.startsWith("http")) {
192 new GetSource(this, userAgent).execute(formattedUrlString);
197 public boolean onCreateOptionsMenu(Menu menu) {
198 // Inflate the menu. This adds items to the action bar if it is present.
199 getMenuInflater().inflate(R.menu.view_source_options_menu, menu);
206 public boolean onOptionsItemSelected(MenuItem menuItem) {
207 // Get a handle for the about alert dialog.
208 DialogFragment aboutDialogFragment = new AboutViewSourceDialog();
210 // Show the about alert dialog.
211 aboutDialogFragment.show(getFragmentManager(), getString(R.string.about));
213 // Consume the event.
217 public void goBack(View view) {
219 NavUtils.navigateUpFromSameTask(activity);
222 private void highlightUrlText() {
223 // Get a handle for the URL EditText.
224 EditText urlEditText = findViewById(R.id.url_edittext);
226 // Get the URL string.
227 String urlString = urlEditText.getText().toString();
229 // Highlight the URL according to the protocol.
230 if (urlString.startsWith("file://")) { // This is a file URL.
231 // De-emphasize only the protocol.
232 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
233 } else if (urlString.startsWith("content://")) {
234 // De-emphasize only the protocol.
235 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
236 } else { // This is a web URL.
237 // Get the index of the `/` immediately after the domain name.
238 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
240 // Create a base URL string.
244 if (endOfDomainName > 0) { // There is at least one character after the base URL.
246 baseUrl = urlString.substring(0, endOfDomainName);
247 } else { // There are no characters after the base URL.
248 // Set the base URL to be the entire URL string.
252 // Get the index of the last `.` in the domain.
253 int lastDotIndex = baseUrl.lastIndexOf(".");
255 // Get the index of the penultimate `.` in the domain.
256 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
258 // Markup the beginning of the URL.
259 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
260 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
262 // De-emphasize subdomains.
263 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
264 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
266 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
267 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
268 // De-emphasize the protocol and the additional subdomains.
269 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
270 } else { // There is only one subdomain in the domain name.
271 // De-emphasize only the protocol.
272 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
276 // De-emphasize the text after the domain name.
277 if (endOfDomainName > 0) {
278 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);