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.content.Context;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.os.Bundle;
27 import android.preference.PreferenceManager;
28 import android.text.Spanned;
29 import android.text.style.ForegroundColorSpan;
30 import android.view.KeyEvent;
31 import android.view.Menu;
32 import android.view.MenuItem;
33 import android.view.View;
34 import android.view.WindowManager;
35 import android.view.inputmethod.InputMethodManager;
36 import android.widget.EditText;
38 import androidx.annotation.NonNull;
39 import androidx.appcompat.app.ActionBar;
40 import androidx.appcompat.app.AppCompatActivity;
41 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
42 import androidx.core.app.NavUtils;
43 import androidx.fragment.app.DialogFragment;
44 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
46 import com.stoutner.privacybrowser.R;
47 import com.stoutner.privacybrowser.asynctasks.GetSource;
48 import com.stoutner.privacybrowser.dialogs.AboutViewSourceDialog;
50 public class ViewSourceActivity extends AppCompatActivity {
51 // `activity` is used in `onCreate()` and `goBack()`.
52 private Activity activity;
54 // The color spans are used in `onCreate()` and `highlightUrlText()`.
55 private ForegroundColorSpan redColorSpan;
56 private ForegroundColorSpan initialGrayColorSpan;
57 private ForegroundColorSpan finalGrayColorSpan;
60 protected void onCreate(Bundle savedInstanceState) {
61 // Get a handle for the shared preferences.
62 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
64 // Get the screenshot and theme preferences.
65 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
66 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
68 // Disable screenshots if not allowed.
69 if (!allowScreenshots) {
70 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
75 setTheme(R.style.PrivacyBrowserDark);
77 setTheme(R.style.PrivacyBrowserLight);
80 // Run the default commands.
81 super.onCreate(savedInstanceState);
83 // Get the launching intent
84 Intent intent = getIntent();
86 // Get the information from the intent.
87 String userAgent = intent.getStringExtra("user_agent");
88 String currentUrl = intent.getStringExtra("current_url");
90 // Store a handle for the current activity.
93 // Set the content view.
94 setContentView(R.layout.view_source_coordinatorlayout);
96 // The AndroidX toolbar must be used until the minimum API is >= 21.
97 Toolbar toolbar = findViewById(R.id.view_source_toolbar);
98 setSupportActionBar(toolbar);
100 // Get a handle for the action bar.
101 final ActionBar actionBar = getSupportActionBar();
103 // Remove the incorrect lint warning that the action bar might be null.
104 assert actionBar != null;
106 // Add the custom layout to the action bar.
107 actionBar.setCustomView(R.layout.view_source_app_bar);
108 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
110 // Get a handle for the url text box.
111 EditText urlEditText = findViewById(R.id.url_edittext);
113 // Populate the URL text box.
114 urlEditText.setText(currentUrl);
116 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
117 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
118 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
119 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
121 // Apply text highlighting to the URL.
124 // Get a handle for the input method manager, which is used to hide the keyboard.
125 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
127 // Remove the lint warning that the input method manager might be null.
128 assert inputMethodManager != null;
130 // Remove the formatting from the URL when the user is editing the text.
131 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
132 if (hasFocus) { // The user is editing `urlTextBox`.
133 // Remove the highlighting.
134 urlEditText.getText().removeSpan(redColorSpan);
135 urlEditText.getText().removeSpan(initialGrayColorSpan);
136 urlEditText.getText().removeSpan(finalGrayColorSpan);
137 } else { // The user has stopped editing `urlTextBox`.
138 // Hide the soft keyboard.
139 inputMethodManager.hideSoftInputFromWindow(urlEditText.getWindowToken(), 0);
141 // Move to the beginning of the string.
142 urlEditText.setSelection(0);
144 // Reapply the highlighting.
149 // Set the go button on the keyboard to request new source data.
150 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
151 // Request new source data if the enter key was pressed.
152 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
153 // Hide the soft keyboard.
154 inputMethodManager.hideSoftInputFromWindow(urlEditText.getWindowToken(), 0);
156 // Remove the focus from the URL box.
157 urlEditText.clearFocus();
160 String url = urlEditText.getText().toString();
162 // Get new source data for the current URL if it beings with `http`.
163 if (url.startsWith("http")) {
164 new GetSource(this, userAgent).execute(url);
167 // Consume the key press.
170 // Do not consume the key press.
175 // Get a handle for the swipe refresh layout.
176 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.view_source_swiperefreshlayout);
178 // Implement swipe to refresh.
179 swipeRefreshLayout.setOnRefreshListener(() -> {
181 String url = urlEditText.getText().toString();
183 // Get new source data for the URL if it begins with `http`.
184 if (url.startsWith("http")) {
185 new GetSource(this, userAgent).execute(url);
187 // Stop the refresh animation.
188 swipeRefreshLayout.setRefreshing(false);
192 // Set the swipe to refresh color according to the theme.
194 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
195 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
197 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
200 // Get the source using an AsyncTask if the URL begins with `http`.
201 if ((currentUrl != null) && currentUrl.startsWith("http")) {
202 new GetSource(this, userAgent).execute(currentUrl);
207 public boolean onCreateOptionsMenu(Menu menu) {
208 // Inflate the menu. This adds items to the action bar if it is present.
209 getMenuInflater().inflate(R.menu.view_source_options_menu, menu);
216 public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
217 // Get a handle for the about alert dialog.
218 DialogFragment aboutDialogFragment = new AboutViewSourceDialog();
220 // Show the about alert dialog.
221 aboutDialogFragment.show(getSupportFragmentManager(), getString(R.string.about));
223 // Consume the event.
227 public void goBack(View view) {
229 NavUtils.navigateUpFromSameTask(activity);
232 private void highlightUrlText() {
233 // Get a handle for the URL EditText.
234 EditText urlEditText = findViewById(R.id.url_edittext);
236 // Get the URL string.
237 String urlString = urlEditText.getText().toString();
239 // Highlight the URL according to the protocol.
240 if (urlString.startsWith("file://")) { // This is a file URL.
241 // De-emphasize only the protocol.
242 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
243 } else if (urlString.startsWith("content://")) {
244 // De-emphasize only the protocol.
245 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
246 } else { // This is a web URL.
247 // Get the index of the `/` immediately after the domain name.
248 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
250 // Create a base URL string.
254 if (endOfDomainName > 0) { // There is at least one character after the base URL.
256 baseUrl = urlString.substring(0, endOfDomainName);
257 } else { // There are no characters after the base URL.
258 // Set the base URL to be the entire URL string.
262 // Get the index of the last `.` in the domain.
263 int lastDotIndex = baseUrl.lastIndexOf(".");
265 // Get the index of the penultimate `.` in the domain.
266 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
268 // Markup the beginning of the URL.
269 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
270 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
272 // De-emphasize subdomains.
273 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
274 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
276 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
277 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
278 // De-emphasize the protocol and the additional subdomains.
279 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
280 } else { // There is only one subdomain in the domain name.
281 // De-emphasize only the protocol.
282 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
286 // De-emphasize the text after the domain name.
287 if (endOfDomainName > 0) {
288 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);