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