]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ViewSourceActivity.kt
173313f65da654b540f2d88af163bc59ba176aa3
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / ViewSourceActivity.kt
1 /*
2  * Copyright © 2017-2021 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.content.res.Configuration
23 import android.os.Build
24 import android.os.Bundle
25 import android.text.SpannableStringBuilder
26 import android.text.Spanned
27 import android.text.style.ForegroundColorSpan
28 import android.util.TypedValue
29 import android.view.KeyEvent
30 import android.view.Menu
31 import android.view.MenuItem
32 import android.view.View
33 import android.view.View.OnFocusChangeListener
34 import android.view.WindowManager
35 import android.view.inputmethod.InputMethodManager
36 import android.widget.EditText
37 import android.widget.ProgressBar
38 import android.widget.TextView
39
40 import androidx.appcompat.app.ActionBar
41 import androidx.appcompat.app.AppCompatActivity
42 import androidx.appcompat.widget.Toolbar
43 import androidx.core.app.NavUtils
44 import androidx.fragment.app.DialogFragment
45 import androidx.lifecycle.ViewModelProvider
46 import androidx.preference.PreferenceManager
47 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
48
49 import com.google.android.material.snackbar.Snackbar
50
51 import com.stoutner.privacybrowser.R
52 import com.stoutner.privacybrowser.dialogs.AboutViewSourceDialog
53 import com.stoutner.privacybrowser.helpers.ProxyHelper
54 import com.stoutner.privacybrowser.viewmodelfactories.WebViewSourceFactory
55 import com.stoutner.privacybrowser.viewmodels.WebViewSource
56
57 import java.util.Locale
58
59 // Declare the public constants.
60 const val CURRENT_URL = "current_url"
61 const val USER_AGENT = "user_agent"
62
63 class ViewSourceActivity: AppCompatActivity() {
64     // Declare the class variables.
65     private lateinit var initialGrayColorSpan: ForegroundColorSpan
66     private lateinit var finalGrayColorSpan: ForegroundColorSpan
67     private lateinit var redColorSpan: ForegroundColorSpan
68
69     override fun onCreate(savedInstanceState: Bundle?) {
70         // Get a handle for the shared preferences.
71         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
72
73         // Get the screenshot preference.
74         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
75
76         // Disable screenshots if not allowed.
77         if (!allowScreenshots) {
78             window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
79         }
80
81         // Set the theme.
82         setTheme(R.style.PrivacyBrowser)
83
84         // Run the default commands.
85         super.onCreate(savedInstanceState)
86
87         // Get the launching intent
88         val intent = intent
89
90         // Get the information from the intent.
91         val currentUrl = intent.getStringExtra(CURRENT_URL)
92         val userAgent = intent.getStringExtra(USER_AGENT)
93
94         // Set the content view.
95         setContentView(R.layout.view_source_coordinatorlayout)
96
97         // Get a handle for the toolbar.
98         val toolbar = findViewById<Toolbar>(R.id.view_source_toolbar)
99
100         // Set the support action bar.
101         setSupportActionBar(toolbar)
102
103         // Get a handle for the action bar.
104         val actionBar = supportActionBar!!
105
106         // Add the custom layout to the action bar.
107         actionBar.setCustomView(R.layout.view_source_app_bar)
108
109         // Instruct the action bar to display a custom layout.
110         actionBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
111
112         // Get handles for the views.
113         val urlEditText = findViewById<EditText>(R.id.url_edittext)
114         val requestHeadersTextView = findViewById<TextView>(R.id.request_headers)
115         val responseMessageTextView = findViewById<TextView>(R.id.response_message)
116         val responseHeadersTextView = findViewById<TextView>(R.id.response_headers)
117         val responseBodyTextView = findViewById<TextView>(R.id.response_body)
118         val progressBar = findViewById<ProgressBar>(R.id.progress_bar)
119         val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.view_source_swiperefreshlayout)
120
121         // Populate the URL text box.
122         urlEditText.setText(currentUrl)
123
124         // Initialize the gray foreground color spans for highlighting the URLs.  The deprecated `getColor()` must be used until the minimum API >= 23.
125         @Suppress("DEPRECATION")
126         initialGrayColorSpan = ForegroundColorSpan(resources.getColor(R.color.gray_500))
127         @Suppress("DEPRECATION")
128         finalGrayColorSpan = ForegroundColorSpan(resources.getColor(R.color.gray_500))
129
130         // Get the current theme status.
131         val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
132
133         // Set the red color span according to the theme.  The deprecated `getColor()` must be used until the minimum API >= 23.
134         redColorSpan = if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
135             @Suppress("DEPRECATION")
136             ForegroundColorSpan(resources.getColor(R.color.red_a700))
137         } else {
138             @Suppress("DEPRECATION")
139             ForegroundColorSpan(resources.getColor(R.color.red_900))
140         }
141
142         // Apply text highlighting to the URL.
143         highlightUrlText()
144
145         // Get a handle for the input method manager, which is used to hide the keyboard.
146         val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
147
148         // Remove the formatting from the URL when the user is editing the text.
149         urlEditText.onFocusChangeListener = OnFocusChangeListener { _: View?, hasFocus: Boolean ->
150             if (hasFocus) {  // The user is editing the URL text box.
151                 // Remove the highlighting.
152                 urlEditText.text.removeSpan(redColorSpan)
153                 urlEditText.text.removeSpan(initialGrayColorSpan)
154                 urlEditText.text.removeSpan(finalGrayColorSpan)
155             } else {  // The user has stopped editing the URL text box.
156                 // Hide the soft keyboard.
157                 inputMethodManager.hideSoftInputFromWindow(urlEditText.windowToken, 0)
158
159                 // Move to the beginning of the string.
160                 urlEditText.setSelection(0)
161
162                 // Reapply the highlighting.
163                 highlightUrlText()
164             }
165         }
166
167         // Set the refresh color scheme according to the theme.
168         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
169             swipeRefreshLayout.setColorSchemeResources(R.color.blue_700)
170         } else {
171             swipeRefreshLayout.setColorSchemeResources(R.color.violet_500)
172         }
173
174         // Initialize a color background typed value.
175         val colorBackgroundTypedValue = TypedValue()
176
177         // Get the color background from the theme.
178         theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
179
180         // Get the color background int from the typed value.
181         val colorBackgroundInt = colorBackgroundTypedValue.data
182
183         // Set the swipe refresh background color.
184         swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
185
186         // Populate the locale string.
187         val localeString = if (Build.VERSION.SDK_INT >= 24) {  // SDK >= 24 has a list of locales.
188             // Get the list of locales.
189             val localeList = resources.configuration.locales
190
191             // Initialize a string builder to extract the locales from the list.
192             val localesStringBuilder = StringBuilder()
193
194             // Initialize a `q` value, which is used by `WebView` to indicate the order of importance of the languages.
195             var q = 10
196
197             // Populate the string builder with the contents of the locales list.
198             for (i in 0 until localeList.size()) {
199                 // Append a comma if there is already an item in the string builder.
200                 if (i > 0) {
201                     localesStringBuilder.append(",")
202                 }
203
204                 // Get the locale from the list.
205                 val locale = localeList[i]
206
207                 // Add the locale to the string.  `locale` by default displays as `en_US`, but WebView uses the `en-US` format.
208                 localesStringBuilder.append(locale.language)
209                 localesStringBuilder.append("-")
210                 localesStringBuilder.append(locale.country)
211
212                 // If not the first locale, append `;q=0.x`, which drops by .1 for each removal from the main locale until q=0.1.
213                 if (q < 10) {
214                     localesStringBuilder.append(";q=0.")
215                     localesStringBuilder.append(q)
216                 }
217
218                 // Decrement `q` if it is greater than 1.
219                 if (q > 1) {
220                     q--
221                 }
222
223                 // Add a second entry for the language only portion of the locale.
224                 localesStringBuilder.append(",")
225                 localesStringBuilder.append(locale.language)
226
227                 // Append `1;q=0.x`, which drops by .1 for each removal form the main locale until q=0.1.
228                 localesStringBuilder.append(";q=0.")
229                 localesStringBuilder.append(q)
230
231                 // Decrement `q` if it is greater than 1.
232                 if (q > 1) {
233                     q--
234                 }
235             }
236
237             // Store the populated string builder in the locale string.
238             localesStringBuilder.toString()
239         } else {  // SDK < 24 only has a primary locale.
240             // Store the locale in the locale string.
241             Locale.getDefault().toString()
242         }
243
244         // Instantiate the proxy helper.
245         val proxyHelper = ProxyHelper()
246
247         // Get the current proxy.
248         val proxy = proxyHelper.getCurrentProxy(this)
249
250         // Make the progress bar visible.
251         progressBar.visibility = View.VISIBLE
252
253         // Set the progress bar to be indeterminate.
254         progressBar.isIndeterminate = true
255
256         // Instantiate the WebView source factory.
257         val webViewSourceFactory: ViewModelProvider.Factory = WebViewSourceFactory(currentUrl!!, userAgent!!, localeString, proxy, MainWebViewActivity.executorService)
258
259         // Instantiate the WebView source view model class.
260         val webViewSource = ViewModelProvider(this, webViewSourceFactory).get(WebViewSource::class.java)
261
262         // Create a source observer.
263         webViewSource.observeSource().observe(this, { sourceStringArray: Array<SpannableStringBuilder> ->
264             // Populate the text views.  This can take a long time, and freezes the user interface, if the response body is particularly large.
265             requestHeadersTextView.text = sourceStringArray[0]
266             responseMessageTextView.text = sourceStringArray[1]
267             responseHeadersTextView.text = sourceStringArray[2]
268             responseBodyTextView.text = sourceStringArray[3]
269
270             // Hide the progress bar.
271             progressBar.isIndeterminate = false
272             progressBar.visibility = View.GONE
273
274             //Stop the swipe to refresh indicator if it is running
275             swipeRefreshLayout.isRefreshing = false
276         })
277
278         // Create an error observer.
279         webViewSource.observeErrors().observe(this, { errorString: String ->
280             // Display an error snackbar if the string is not `""`.
281             if (errorString != "") {
282                 Snackbar.make(swipeRefreshLayout, errorString, Snackbar.LENGTH_LONG).show()
283             }
284         })
285
286         // Implement swipe to refresh.
287         swipeRefreshLayout.setOnRefreshListener {
288             // Make the progress bar visible.
289             progressBar.visibility = View.VISIBLE
290
291             // Set the progress bar to be indeterminate.
292             progressBar.isIndeterminate = true
293
294             // Get the URL.
295             val urlString = urlEditText.text.toString()
296
297             // Get the updated source.
298             webViewSource.updateSource(urlString)
299         }
300
301         // Set the go button on the keyboard to request new source data.
302         urlEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
303             // Request new source data if the enter key was pressed.
304             if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
305                 // Hide the soft keyboard.
306                 inputMethodManager.hideSoftInputFromWindow(urlEditText.windowToken, 0)
307
308                 // Remove the focus from the URL box.
309                 urlEditText.clearFocus()
310
311                 // Make the progress bar visible.
312                 progressBar.visibility = View.VISIBLE
313
314                 // Set the progress bar to be indeterminate.
315                 progressBar.isIndeterminate = true
316
317                 // Get the URL.
318                 val urlString = urlEditText.text.toString()
319
320                 // Get the updated source.
321                 webViewSource.updateSource(urlString)
322
323                 // Consume the key press.
324                 return@setOnKeyListener true
325             } else {
326                 // Do not consume the key press.
327                 return@setOnKeyListener false
328             }
329         }
330     }
331
332     override fun onCreateOptionsMenu(menu: Menu): Boolean {
333         // Inflate the menu.  This adds items to the action bar if it is present.
334         menuInflater.inflate(R.menu.view_source_options_menu, menu)
335
336         // Display the menu.
337         return true
338     }
339
340     override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
341         // Get a handle for the about alert dialog.
342         val aboutDialogFragment: DialogFragment = AboutViewSourceDialog()
343
344         // Show the about alert dialog.
345         aboutDialogFragment.show(supportFragmentManager, getString(R.string.about))
346
347         // Consume the event.
348         return true
349     }
350
351     // This method must be named `goBack()` and must have a View argument to match the default back arrow in the app bar.
352     fun goBack(@Suppress("UNUSED_PARAMETER") view: View) {
353         // Go home.
354         NavUtils.navigateUpFromSameTask(this)
355     }
356
357     private fun highlightUrlText() {
358         // Get a handle for the URL edit text.
359         val urlEditText = findViewById<EditText>(R.id.url_edittext)
360
361         // Get the URL string.
362         val urlString = urlEditText.text.toString()
363
364         // Highlight the URL according to the protocol.
365         if (urlString.startsWith("file://")) {  // This is a file URL.
366             // De-emphasize only the protocol.
367             urlEditText.text.setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
368         } else if (urlString.startsWith("content://")) {
369             // De-emphasize only the protocol.
370             urlEditText.text.setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
371         } else {  // This is a web URL.
372             // Get the index of the `/` immediately after the domain name.
373             val endOfDomainName = urlString.indexOf("/", urlString.indexOf("//") + 2)
374
375             // Get the base URL.
376             val baseUrl = if (endOfDomainName > 0) {  // There is at least one character after the base URL.
377                 // Get the base URL.
378                 urlString.substring(0, endOfDomainName)
379             } else {  // There are no characters after the base URL.
380                 // Set the base URL to be the entire URL string.
381                 urlString
382             }
383
384             // Get the index of the last `.` in the domain.
385             val lastDotIndex = baseUrl.lastIndexOf(".")
386
387             // Get the index of the penultimate `.` in the domain.
388             val penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1)
389
390             // Markup the beginning of the URL.
391             if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
392                 urlEditText.text.setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
393
394                 // De-emphasize subdomains.
395                 if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
396                     urlEditText.text.setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
397                 }
398             } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
399                 if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
400                     // De-emphasize the protocol and the additional subdomains.
401                     urlEditText.text.setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
402                 } else {  // There is only one subdomain in the domain name.
403                     // De-emphasize only the protocol.
404                     urlEditText.text.setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
405                 }
406             }
407
408             // De-emphasize the text after the domain name.
409             if (endOfDomainName > 0) {
410                 urlEditText.text.setSpan(finalGrayColorSpan, endOfDomainName, urlString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
411             }
412         }
413     }
414 }