]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ViewSourceActivity.java
a0f51d14b7a2853f31fd5df68ab08d151f42079b
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / ViewSourceActivity.java
1 /*
2  * Copyright © 2017-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
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;
37
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;
45
46 import com.stoutner.privacybrowser.R;
47 import com.stoutner.privacybrowser.asynctasks.GetSource;
48 import com.stoutner.privacybrowser.dialogs.AboutViewSourceDialog;
49
50 public class ViewSourceActivity extends AppCompatActivity {
51     // `activity` is used in `onCreate()` and `goBack()`.
52     private Activity activity;
53
54     // The color spans are used in `onCreate()` and `highlightUrlText()`.
55     private ForegroundColorSpan redColorSpan;
56     private ForegroundColorSpan initialGrayColorSpan;
57     private ForegroundColorSpan finalGrayColorSpan;
58
59     @Override
60     protected void onCreate(Bundle savedInstanceState) {
61         // Get a handle for the shared preferences.
62         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
63
64         // Get the screenshot and theme preferences.
65         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
66         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
67
68         // Disable screenshots if not allowed.
69         if (!allowScreenshots) {
70             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
71         }
72
73         // Set the theme.
74         if (darkTheme) {
75             setTheme(R.style.PrivacyBrowserDark);
76         } else {
77             setTheme(R.style.PrivacyBrowserLight);
78         }
79
80         // Run the default commands.
81         super.onCreate(savedInstanceState);
82
83         // Get the launching intent
84         Intent intent = getIntent();
85
86         // Get the information from the intent.
87         String userAgent = intent.getStringExtra("user_agent");
88         String currentUrl = intent.getStringExtra("current_url");
89
90         // Store a handle for the current activity.
91         activity = this;
92
93         // Set the content view.
94         setContentView(R.layout.view_source_coordinatorlayout);
95
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);
99
100         // Get a handle for the action bar.
101         final ActionBar actionBar = getSupportActionBar();
102
103         // Remove the incorrect lint warning that the action bar might be null.
104         assert actionBar != null;
105
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);
109
110         // Get a handle for the url text box.
111         EditText urlEditText = findViewById(R.id.url_edittext);
112
113         // Populate the URL text box.
114         urlEditText.setText(currentUrl);
115
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));
120
121         // Apply text highlighting to the URL.
122         highlightUrlText();
123
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);
126
127         // Remove the lint warning that the input method manager might be null.
128         assert inputMethodManager != null;
129
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);
140
141                 // Move to the beginning of the string.
142                 urlEditText.setSelection(0);
143
144                 // Reapply the highlighting.
145                 highlightUrlText();
146             }
147         });
148
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);
155
156                 // Remove the focus from the URL box.
157                 urlEditText.clearFocus();
158
159                 // Get the URL.
160                 String url = urlEditText.getText().toString();
161
162                 // Get new source data for the current URL if it beings with `http`.
163                 if (url.startsWith("http")) {
164                     new GetSource(this, this, userAgent).execute(url);
165                 }
166
167                 // Consume the key press.
168                 return true;
169             } else {
170                 // Do not consume the key press.
171                 return false;
172             }
173         });
174
175         // Get a handle for the swipe refresh layout.
176         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.view_source_swiperefreshlayout);
177
178         // Implement swipe to refresh.
179         swipeRefreshLayout.setOnRefreshListener(() -> {
180             // Get the URL.
181             String url = urlEditText.getText().toString();
182
183             // Get new source data for the URL if it begins with `http`.
184             if (url.startsWith("http")) {
185                 new GetSource(this, this, userAgent).execute(url);
186             } else {
187                 // Stop the refresh animation.
188                 swipeRefreshLayout.setRefreshing(false);
189             }
190         });
191
192         // Set the swipe to refresh color according to the theme.
193         if (darkTheme) {
194             swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
195             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_800);
196         } else {
197             swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
198         }
199
200         // Get the source using an AsyncTask if the URL begins with `http`.
201         if ((currentUrl != null) && currentUrl.startsWith("http")) {
202             new GetSource(this, this, userAgent).execute(currentUrl);
203         }
204     }
205
206     @Override
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);
210
211         // Display the menu.
212         return true;
213     }
214
215     @Override
216     public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
217         // Get a handle for the about alert dialog.
218         DialogFragment aboutDialogFragment = new AboutViewSourceDialog();
219
220         // Show the about alert dialog.
221         aboutDialogFragment.show(getSupportFragmentManager(), getString(R.string.about));
222
223         // Consume the event.
224         return true;
225     }
226
227     public void goBack(View view) {
228         // Go home.
229         NavUtils.navigateUpFromSameTask(activity);
230     }
231
232     private void highlightUrlText() {
233         // Get a handle for the URL EditText.
234         EditText urlEditText = findViewById(R.id.url_edittext);
235
236         // Get the URL string.
237         String urlString = urlEditText.getText().toString();
238
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));
249
250             // Create a base URL string.
251             String baseUrl;
252
253             // Get the base URL.
254             if (endOfDomainName > 0) {  // There is at least one character after the base URL.
255                 // Get 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.
259                 baseUrl = urlString;
260             }
261
262             // Get the index of the last `.` in the domain.
263             int lastDotIndex = baseUrl.lastIndexOf(".");
264
265             // Get the index of the penultimate `.` in the domain.
266             int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
267
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);
271
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);
275                 }
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);
283                 }
284             }
285
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);
289             }
290         }
291     }
292 }