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.appcompat.app.ActionBar;
39 import androidx.appcompat.app.AppCompatActivity;
40 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
41 import androidx.core.app.NavUtils;
42 import androidx.fragment.app.DialogFragment;
43 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
45 import com.stoutner.privacybrowser.R;
46 import com.stoutner.privacybrowser.asynctasks.GetSource;
47 import com.stoutner.privacybrowser.dialogs.AboutViewSourceDialog;
49 public class ViewSourceActivity extends AppCompatActivity {
50 // `activity` is used in `onCreate()` and `goBack()`.
51 private Activity activity;
53 // The color spans are used in `onCreate()` and `highlightUrlText()`.
54 private ForegroundColorSpan redColorSpan;
55 private ForegroundColorSpan initialGrayColorSpan;
56 private ForegroundColorSpan finalGrayColorSpan;
59 protected void onCreate(Bundle savedInstanceState) {
60 // Get a handle for the shared preferences.
61 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
63 // Get the screenshot and theme preferences.
64 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
65 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
67 // Disable screenshots if not allowed.
68 if (!allowScreenshots) {
69 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
74 setTheme(R.style.PrivacyBrowserDark);
76 setTheme(R.style.PrivacyBrowserLight);
79 // Run the default commands.
80 super.onCreate(savedInstanceState);
82 // Get the launching intent
83 Intent intent = getIntent();
85 // Get the information from the intent.
86 String userAgent = intent.getStringExtra("user_agent");
87 String currentUrl = intent.getStringExtra("current_url");
89 // Store a handle for the current activity.
92 // Set the content view.
93 setContentView(R.layout.view_source_coordinatorlayout);
95 // The AndroidX toolbar must be used until the minimum API is >= 21.
96 Toolbar toolbar = findViewById(R.id.view_source_toolbar);
97 setSupportActionBar(toolbar);
99 // Get a handle for the action bar.
100 final ActionBar actionBar = getSupportActionBar();
102 // Remove the incorrect lint warning that the action bar might be null.
103 assert actionBar != null;
105 // Add the custom layout to the action bar.
106 actionBar.setCustomView(R.layout.view_source_app_bar);
107 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
109 // Get a handle for the url text box.
110 EditText urlEditText = findViewById(R.id.url_edittext);
112 // Populate the URL text box.
113 urlEditText.setText(currentUrl);
115 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
116 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
117 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
118 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
120 // Apply text highlighting to the URL.
123 // Get a handle for the input method manager, which is used to hide the keyboard.
124 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
126 // Remove the lint warning that the input method manager might be null.
127 assert inputMethodManager != null;
129 // Remove the formatting from the URL when the user is editing the text.
130 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
131 if (hasFocus) { // The user is editing `urlTextBox`.
132 // Remove the highlighting.
133 urlEditText.getText().removeSpan(redColorSpan);
134 urlEditText.getText().removeSpan(initialGrayColorSpan);
135 urlEditText.getText().removeSpan(finalGrayColorSpan);
136 } else { // The user has stopped editing `urlTextBox`.
137 // Hide the soft keyboard.
138 inputMethodManager.hideSoftInputFromWindow(urlEditText.getWindowToken(), 0);
140 // Move to the beginning of the string.
141 urlEditText.setSelection(0);
143 // Reapply the highlighting.
148 // Set the go button on the keyboard to request new source data.
149 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
150 // Request new source data if the enter key was pressed.
151 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
152 // Hide the soft keyboard.
153 inputMethodManager.hideSoftInputFromWindow(urlEditText.getWindowToken(), 0);
155 // Remove the focus from the URL box.
156 urlEditText.clearFocus();
159 String url = urlEditText.getText().toString();
161 // Get new source data for the current URL if it beings with `http`.
162 if (url.startsWith("http")) {
163 new GetSource(this, userAgent).execute(url);
166 // Consume the key press.
169 // Do not consume the key press.
174 // Get a handle for the swipe refresh layout.
175 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.view_source_swiperefreshlayout);
177 // Implement swipe to refresh.
178 swipeRefreshLayout.setOnRefreshListener(() -> {
180 String url = urlEditText.getText().toString();
182 // Get new source data for the URL if it begins with `http`.
183 if (url.startsWith("http")) {
184 new GetSource(this, userAgent).execute(url);
186 // Stop the refresh animation.
187 swipeRefreshLayout.setRefreshing(false);
191 // Set the swipe to refresh color according to the theme.
193 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
194 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
196 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
199 // Get the source using an AsyncTask if the URL begins with `http`.
200 if (currentUrl.startsWith("http")) {
201 new GetSource(this, userAgent).execute(currentUrl);
206 public boolean onCreateOptionsMenu(Menu menu) {
207 // Inflate the menu. This adds items to the action bar if it is present.
208 getMenuInflater().inflate(R.menu.view_source_options_menu, menu);
215 public boolean onOptionsItemSelected(MenuItem menuItem) {
216 // Get a handle for the about alert dialog.
217 DialogFragment aboutDialogFragment = new AboutViewSourceDialog();
219 // Show the about alert dialog.
220 aboutDialogFragment.show(getSupportFragmentManager(), getString(R.string.about));
222 // Consume the event.
226 public void goBack(View view) {
228 NavUtils.navigateUpFromSameTask(activity);
231 private void highlightUrlText() {
232 // Get a handle for the URL EditText.
233 EditText urlEditText = findViewById(R.id.url_edittext);
235 // Get the URL string.
236 String urlString = urlEditText.getText().toString();
238 // Highlight the URL according to the protocol.
239 if (urlString.startsWith("file://")) { // This is a file URL.
240 // De-emphasize only the protocol.
241 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
242 } else if (urlString.startsWith("content://")) {
243 // De-emphasize only the protocol.
244 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
245 } else { // This is a web URL.
246 // Get the index of the `/` immediately after the domain name.
247 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
249 // Create a base URL string.
253 if (endOfDomainName > 0) { // There is at least one character after the base URL.
255 baseUrl = urlString.substring(0, endOfDomainName);
256 } else { // There are no characters after the base URL.
257 // Set the base URL to be the entire URL string.
261 // Get the index of the last `.` in the domain.
262 int lastDotIndex = baseUrl.lastIndexOf(".");
264 // Get the index of the penultimate `.` in the domain.
265 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
267 // Markup the beginning of the URL.
268 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
269 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
271 // De-emphasize subdomains.
272 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
273 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
275 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
276 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
277 // De-emphasize the protocol and the additional subdomains.
278 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
279 } else { // There is only one subdomain in the domain name.
280 // De-emphasize only the protocol.
281 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
285 // De-emphasize the text after the domain name.
286 if (endOfDomainName > 0) {
287 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);