/
WebPageTab.kt
1484 lines (1298 loc) · 53.4 KB
/
WebPageTab.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2020-2021 Stéphane Lenclud
* Copyright 2014 A.C.R. Development
*/
package fulguris.view
import fulguris.Capabilities
import fulguris.R
import fulguris.activity.ThemedActivity
import fulguris.browser.TabModel
import fulguris.activity.WebBrowserActivity
import fulguris.constant.*
import fulguris.browser.WebBrowser
import fulguris.di.*
import fulguris.dialog.LightningDialogBuilder
import fulguris.download.LightningDownloadListener
import fulguris.extensions.*
import fulguris.isSupported
import fulguris.network.NetworkConnectivityModel
import fulguris.settings.fragment.DisplaySettingsFragment.Companion.MIN_BROWSER_TEXT_SIZE
import fulguris.settings.preferences.DomainPreferences
import fulguris.settings.preferences.UserPreferences
import fulguris.settings.preferences.userAgent
import fulguris.settings.preferences.webViewEngineVersionDesktop
import fulguris.ssl.SslState
import fulguris.utils.*
import android.annotation.SuppressLint
import android.app.Activity
import android.app.DownloadManager
import android.content.IntentFilter
import android.content.SharedPreferences
import android.graphics.*
import android.net.Uri
import android.net.http.SslCertificate
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.*
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.View.OnScrollChangeListener
import android.view.View.OnTouchListener
import android.webkit.CookieManager
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebSettings
import android.webkit.WebSettings.LOAD_DEFAULT
import android.webkit.WebSettings.LOAD_NO_CACHE
import android.webkit.WebSettings.LayoutAlgorithm
import android.webkit.WebView
import androidx.annotation.RequiresApi
import androidx.collection.ArrayMap
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewFeature
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.EntryPointAccessors
import fulguris.constant.Hosts
import fulguris.constant.Schemes
import fulguris.constant.Uris
import fulguris.constant.WINDOWS_DESKTOP_USER_AGENT_PREFIX
import fulguris.di.HiltEntryPoint
import fulguris.di.configPrefs
import fulguris.extensions.canScrollVertically
import fulguris.extensions.dp
import fulguris.extensions.isDarkTheme
import fulguris.extensions.makeSnackbar
import fulguris.extensions.px
import fulguris.extensions.removeFromParent
import fulguris.extensions.setIcon
import fulguris.utils.ThemeUtils
import fulguris.utils.isBookmarkUrl
import fulguris.utils.isDownloadsUrl
import fulguris.utils.isHistoryUrl
import fulguris.utils.isSpecialUrl
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import timber.log.Timber
import java.lang.ref.WeakReference
/**
* [WebPageTab] acts as a tab for the browser, handling WebView creation and handling logic, as
* well as properly initialing it. All interactions with the WebView should be made through this
* class.
*/
class WebPageTab(
private val activity: Activity,
tabInitializer: TabInitializer,
val isIncognito: Boolean,
// TODO: Could we remove those?
private val homePageInitializer: HomePageInitializer,
private val incognitoPageInitializer: IncognitoPageInitializer,
private val bookmarkPageInitializer: BookmarkPageInitializer,
private val downloadPageInitializer: DownloadPageInitializer,
private val historyPageInitializer: HistoryPageInitializer
): WebView.FindListener,
SharedPreferences.OnSharedPreferenceChangeListener {
/**
* The unique ID of the view.
*/
val id = View.generateViewId()
/**
* Getter for the [WebPageHeader] of the current [WebPageTab] instance.
*/
val titleInfo: WebPageHeader
/**
* Meta theme-color content value as extracted from page HTML
*/
var htmlMetaThemeColor: Int = KHtmlMetaThemeColorInvalid
/**
* Define the number of times we should try to fetch HTML meta tehme-color
*/
var fetchMetaThemeColorTries = KFetchMetaThemeColorTries
/**
* A tab initializer that should be run when the view is first attached.
* Notably contains a bundle to be load in our webView.
*/
private var latentTabInitializer: FreezableBundleInitializer? = null
/**
* Gets the current WebView instance of the tab.
*
* @return the WebView instance of the tab, which can be null.
*/
var webView: WebViewEx? = null
private set
private lateinit var webPageClient: WebPageClient
/**
* The URL we tried to load
*/
private var iTargetUrl: Uri = Uri.parse("")
private val webBrowser: WebBrowser
private lateinit var gestureDetector: GestureDetector
private val paint = Paint()
/**
* Sets whether this tab was the result of a new intent sent to the browser.
* That's notably used to decide if we close our activity when closing this tab thus going back to the app which opened it.
*/
var isNewTab: Boolean = false
/**
* This method sets the tab as the foreground tab or a background tab.
*/
var isForeground: Boolean = false
set(aIsForeground) {
field = aIsForeground
if (isForeground) {
// When frozen tab goes foreground we need to load its bundle in webView
latentTabInitializer?.apply {
// Lazy creation of our WebView
createWebView()
// Load bundle in WebView
initializeContent(this)
// Discard tab initializer since we just consumed it
latentTabInitializer = null
}
} else {
// A tab sent to the background is not so new anymore
isNewTab = false
}
webBrowser.onTabChanged(this)
}
/**
* Gets whether or not the page rendering is inverted or not. The main purpose of this is to
* indicate that JavaScript should be run at the end of a page load to invert only the images
* back to their non-inverted states.
*
* @return true if the page is in inverted mode, false otherwise.
*/
var invertPage = false
private set
/**
* True if desktop mode is enabled for this tab.
*/
var desktopMode = false
set(aDesktopMode) {
field = aDesktopMode
// Set our user agent accordingly
if (aDesktopMode) {
webView?.settings?.userAgentString = WINDOWS_DESKTOP_USER_AGENT_PREFIX + webViewEngineVersionDesktop(activity.application)
} else {
setUserAgentForPreference(userPreferences)
}
}
/**
*
*/
var darkMode = false
set(aDarkMode) {
field = aDarkMode
applyDarkMode();
}
/**
* Enable user to override domain settings dark mode preference at the tab level.
* TODO: should we persist that guy?
* Maybe not as we could see this as a temporary option
*/
var darkModeBypassDomainSettings = false
/**
*
*/
var desktopModeBypassDomainSettings = false
/**
* Get our find in page search query.
*
* @return The find in page search query or an empty string.
*/
var searchQuery: String = ""
set(aSearchQuery) {
field = aSearchQuery
//find(searchQuery)
}
/**
* Define if this tab has an active find in page search.
*/
var searchActive = false
/**
*
*/
private val webViewHandler = WebViewHandler(this)
/**
* This method gets the additional headers that should be added with each request the browser
* makes.
*
* @return a non null Map of Strings with the additional request headers.
*/
internal val requestHeaders = ArrayMap<String, String>()
private val maxFling: Float
private val hiltEntryPoint = EntryPointAccessors.fromApplication(activity.applicationContext, HiltEntryPoint::class.java)
val userPreferences: UserPreferences = hiltEntryPoint.userPreferences
val dialogBuilder: LightningDialogBuilder = hiltEntryPoint.dialogBuilder
val proxyUtils: fulguris.utils.ProxyUtils = hiltEntryPoint.proxyUtils
val databaseScheduler: Scheduler = hiltEntryPoint.databaseScheduler()
val mainScheduler: Scheduler = hiltEntryPoint.mainScheduler()
val networkConnectivityModel: NetworkConnectivityModel = hiltEntryPoint.networkConnectivityModel
val defaultDomainSettings = DomainPreferences(activity)
private val networkDisposable: Disposable
/**
* This method determines whether the current tab is visible or not.
*
* @return true if the WebView is non-null and visible, false otherwise.
*/
val isShown: Boolean
get() = webView?.isShown == true
/**
* Gets the current progress of the WebView.
*
* @return returns a number between 0 and 100 with the current progress of the WebView. If the
* WebView is null, then the progress returned will be 100.
*/
val progress: Int
get() = webView?.progress ?: 100
/**
* Tells if a web page is currently loading.
*/
val isLoading
get() = progress != 100
/**
* Get the current user agent used by the WebView.
*
* @return retuns the current user agent of the WebView instance, or an empty string if the
* WebView is null.
*/
private val userAgent: String
get() = webView?.settings?.userAgentString ?: ""
/**
* Gets the favicon currently in use by the page. If the current page does not have a favicon,
* it returns a default icon.
*
* @return a non-null Bitmap with the current favicon.
*/
val favicon: Bitmap
get() = titleInfo.getFavicon()
/**
* Get the current title of the page, retrieved from the title object.
*
* @return the title of the page, or an empty string if there is no title.
*/
val title: String
get() = titleInfo.getTitle()
/**
* Get the current [SslCertificate] if there is any associated with the current page.
*/
val sslCertificate: SslCertificate?
get() = webView?.certificate
/**
* Get the current URL of the WebView, or an empty string if the WebView is null or the URL is
* null.
*
* @return the current URL or an empty string.
*/
val url: String
get() {
//TODO: One day find a way to write this expression without !! and without duplicating iTargetUrl.toString(), Kotlin is so weird
return if (webView == null || webView!!.url.isNullOrBlank() || webView!!.url.isSpecialUrl()) {
iTargetUrl.toString()
} else {
webView!!.url as String
}
}
/**
* Used to check if our URL really changed
*/
var lastUrl: String = ""
/**
* Return true if this tab is frozen, meaning it was not yet loaded from its bundle
*/
val isFrozen : Boolean
get() = latentTabInitializer?.tabModel?.webView != null
/**
* We had forgotten to unregisterReceiver our download listener thus leaking them all whenever we switched between sessions.
* It turns out android as a hardcoded limit of 1000 [BroadcastReceiver] per application.
* So after a while switching between sessions with many tabs we would get an exception saying:
* "Too many receivers, total of 1000, registered for pid"
* See: https://stackoverflow.com/q/58179733/3969362
* TODO: Do we really need one of those per tab/WebView?
*/
private var iDownloadListener: LightningDownloadListener? = null
/**
* Constructor
*/
init {
//activity.injector.inject(this)
webBrowser = activity as WebBrowser
titleInfo = WebPageHeader(activity)
maxFling = ViewConfiguration.get(activity).scaledMaximumFlingVelocity.toFloat()
// Mark our URL
iTargetUrl = Uri.parse(tabInitializer.url())
if (tabInitializer !is FreezableBundleInitializer) {
// Create our WebView now
//TODO: it looks like our special URLs don't get frozen for some reason
createWebView()
initializeContent(tabInitializer)
desktopMode = defaultDomainSettings.desktopMode
darkMode = defaultDomainSettings.darkModeParent
} else {
// Our WebView will only be created whenever our tab goes to the foreground
latentTabInitializer = tabInitializer
titleInfo.setTitle(tabInitializer.tabModel.title)
tabInitializer.tabModel.favicon.let {titleInfo.setFavicon(it)}
desktopMode = tabInitializer.tabModel.desktopMode
darkMode = tabInitializer.tabModel.darkMode
searchQuery = tabInitializer.tabModel.searchQuery
searchActive = tabInitializer.tabModel.searchActive
}
networkDisposable = networkConnectivityModel.connectivity()
.observeOn(mainScheduler)
.subscribe(::setNetworkAvailable)
}
/**
*
*/
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
when (key) {
activity.getString(R.string.pref_key_scrollbar_size) -> {
webView?.scrollBarSize = userPreferences.scrollbarSize.px.toInt()
webView?.postInvalidate()
}
activity.getString(R.string.pref_key_scrollbar_fading) -> {
webView?.isScrollbarFadingEnabled = userPreferences.scrollbarFading
webView?.postInvalidate()
}
activity.getString(R.string.pref_key_scrollbar_delay_before_fade) ->
webView?.scrollBarDefaultDelayBeforeFade = userPreferences.scrollbarDelayBeforeFade.toInt()
activity.getString(R.string.pref_key_scrollbar_fade_duration) ->
webView?.scrollBarFadeDuration = userPreferences.scrollbarFadeDuration.toInt()
}
}
/**
* Create our WebView.
*/
private fun createWebView() {
userPreferences.preferences.registerOnSharedPreferenceChangeListener(this)
webPageClient = WebPageClient(activity, this)
// Inflate our WebView as loading it from XML layout is needed to be able to set scrollbars color
webView = activity.layoutInflater.inflate(R.layout.webview, null) as WebViewEx
webView?.apply {
proxy = this@WebPageTab
Timber.d("WebView scrollbar defaults: ${scrollBarSize.toFloat().dp}, $scrollBarDefaultDelayBeforeFade, $scrollBarFadeDuration")
scrollBarSize = userPreferences.scrollbarSize.px.toInt()
isScrollbarFadingEnabled = userPreferences.scrollbarFading
scrollBarDefaultDelayBeforeFade = userPreferences.scrollbarDelayBeforeFade.toInt()
scrollBarFadeDuration = userPreferences.scrollbarFadeDuration.toInt()
setFindListener(this@WebPageTab)
//id = this@[WebPageTab].id
gestureDetector = GestureDetector(activity, CustomGestureListener(this))
isFocusableInTouchMode = true
isFocusable = true
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
isAnimationCacheEnabled = false
isAlwaysDrawnWithCacheEnabled = false
}
// Some web sites are broken if the background color is not white, thanks bbc.com and bbc.com/news for not defining background color.
// However whatever we set here should be irrelevant as this is being taken care of in [BrowserActivity.changeToolbarBackground]
// Though strictly speaking in a perfect world where web sites always define their background color themselves this should be our theme background color.
setBackgroundColor(ThemeUtils.getBackgroundColor(activity))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES
}
isSaveEnabled = true
setNetworkAvailable(true)
webChromeClient = WebPageChromeClient(activity, this@WebPageTab)
webViewClient = webPageClient
createDownloadListener()
// For older devices show Tool Bar On Page Top won't work after fling to top.
// Who cares? I mean those devices are probably from 2014 or older.
val tl = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) TouchListener().also { setOnScrollChangeListener(it) } else TouchListenerLollipop()
setOnTouchListener(tl)
initializeSettings()
}
initializePreferences()
// If search was active enable it again
if (searchActive) {
find(searchQuery)
}
}
/**
*
*/
private fun createDownloadListener() {
// We want to receive download complete notifications
iDownloadListener = LightningDownloadListener(activity)
webView?.setDownloadListener(iDownloadListener.also { activity.registerReceiver(it, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) })
}
/**
*
*/
private fun destroyDownloadListener() {
//See: https://console.firebase.google.com/project/fulguris-b1f69/crashlytics/app/android:net.slions.fulguris.full.playstore/issues/ea99c7ea0c57f66eae6e95532a16859d
if (iDownloadListener!=null) {
webView?.setDownloadListener(null)
activity.unregisterReceiver(iDownloadListener)
iDownloadListener = null
}
}
fun currentSslState(): SslState = webPageClient.sslState
/**
* This method loads the homepage for the browser. Either it loads the URL stored as the
* homepage, or loads the startpage or bookmark page if either of those are set as the homepage.
*/
fun loadHomePage() {
if (isIncognito) {
iTargetUrl = Uri.parse(Uris.FulgurisIncognito)
initializeContent(incognitoPageInitializer)
} else {
iTargetUrl = Uri.parse(Uris.FulgurisHome)
initializeContent(homePageInitializer)
}
}
/**
* This function loads the bookmark page via the [BookmarkPageInitializer].
*/
fun loadBookmarkPage() {
iTargetUrl = Uri.parse(Uris.FulgurisBookmarks)
initializeContent(bookmarkPageInitializer)
}
/**
* This function loads the download page via the [DownloadPageInitializer].
*/
fun loadDownloadsPage() {
iTargetUrl = Uri.parse(Uris.FulgurisDownloads)
initializeContent(downloadPageInitializer)
}
/**
*
*/
fun loadHistoryPage() {
iTargetUrl = Uri.parse(Uris.FulgurisHistory)
initializeContent(historyPageInitializer)
}
/**
* Basically activate our tab initializer which typically loads something in our WebView.
* [ResultMessageInitializer] being a notable exception as it will only send a message to something to load target URL at a later stage.
*/
private fun initializeContent(tabInitializer: TabInitializer) {
webView?.let { tabInitializer.initialize(it, requestHeaders) }
}
/**
* Initialize the preference driven settings of the WebView. This method must be called whenever
* the preferences are changed within SharedPreferences.
* Apparently called whenever the app is sent to the foreground.
*/
@SuppressLint("NewApi", "SetJavaScriptEnabled")
fun initializePreferences() {
val settings = webView?.settings ?: return
webPageClient.updatePreferences()
val modifiesHeaders = userPreferences.doNotTrackEnabled
|| userPreferences.saveDataEnabled
|| userPreferences.removeIdentifyingHeadersEnabled
if (userPreferences.doNotTrackEnabled) {
requestHeaders[HEADER_DNT] = "1"
} else {
requestHeaders.remove(HEADER_DNT)
}
if (userPreferences.saveDataEnabled) {
requestHeaders[HEADER_SAVEDATA] = "on"
} else {
requestHeaders.remove(HEADER_SAVEDATA)
}
if (userPreferences.removeIdentifyingHeadersEnabled) {
requestHeaders[HEADER_REQUESTED_WITH] = ""
requestHeaders[HEADER_WAP_PROFILE] = ""
} else {
requestHeaders.remove(HEADER_REQUESTED_WITH)
requestHeaders.remove(HEADER_WAP_PROFILE)
}
settings.defaultTextEncodingName = userPreferences.textEncoding
setColorMode(userPreferences.renderingMode)
if (!isIncognito) {
settings.setGeolocationEnabled(userPreferences.locationEnabled)
} else {
settings.setGeolocationEnabled(false)
}
// Since this runs when the activity resumes we need to also take desktop mode into account
// Set the user agent properly taking desktop mode into account
desktopMode = desktopMode
// Don't just do the following as that's not taking desktop mode into account
//setUserAgentForPreference(userPreferences)
settings.saveFormData = userPreferences.savePasswordsEnabled && !isIncognito
if (defaultDomainSettings.javaScriptEnabled) {
settings.javaScriptEnabled = true
settings.javaScriptCanOpenWindowsAutomatically = true
} else {
settings.javaScriptEnabled = false
settings.javaScriptCanOpenWindowsAutomatically = false
}
if (userPreferences.textReflowEnabled) {
settings.layoutAlgorithm = LayoutAlgorithm.NARROW_COLUMNS
try {
settings.layoutAlgorithm = LayoutAlgorithm.TEXT_AUTOSIZING
} catch (e: Exception) {
// This shouldn't be necessary, but there are a number
// of KitKat devices that crash trying to set this
Timber.e(e,"Problem setting LayoutAlgorithm to TEXT_AUTOSIZING")
}
} else {
settings.layoutAlgorithm = LayoutAlgorithm.NORMAL
}
settings.blockNetworkImage = !userPreferences.loadImages
// Modifying headers causes SEGFAULTS, so disallow multi window if headers are enabled.
settings.setSupportMultipleWindows(userPreferences.popupsEnabled && !modifiesHeaders)
settings.loadWithOverviewMode = userPreferences.overviewModeEnabled
settings.textZoom = userPreferences.browserTextSize + MIN_BROWSER_TEXT_SIZE
// Apply default settings for third-party cookies
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, defaultDomainSettings.thirdPartyCookies)
applyDarkMode();
}
/**
* Apply dark mode as needed.
* We try to go dark when using app dark theme or when page is forced to dark mode.
*
* To test that you can load:
* https://septatrix.github.io/prefers-color-scheme-test/
*
* See also:
* https://stackoverflow.com/questions/57449900/letting-webview-on-android-work-with-prefers-color-scheme-dark
*/
private fun applyDarkMode() {
val settings = webView?.settings ?: return
// We needed to add this for force dark mode to work when targeting SDK>=33
// See: https://developer.android.com/about/versions/13/behavior-changes-13#webview-color-theme
if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
// For forced dark mode to work on website that do not provide a dark theme we need to enable this
WebSettingsCompat.setAlgorithmicDarkeningAllowed(settings, darkMode)
}
// If forced dark mode is supported
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK) &&
// and we are in dark theme or forced dark mode
((activity as ThemedActivity).isDarkTheme() || darkMode)) {
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK_STRATEGY)) {
if (darkMode) {
// User requested forced dark mode from menu, we need to enable user agent dark mode then.
WebSettingsCompat.setForceDarkStrategy(
settings,
// Looks like that flag it's not working and will just do user agent dark mode even if page supports dark web theme.
// That means that when using app light theme you can't get dark web theme, you will just get user agent dark theme.
// No big deal though, just use app dark theme if you want proper web dark theme.
WebSettingsCompat.DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING
)
} else {
// We are in app dark theme but this page does not forces to dark mode
// Just request dark web theme then.
// That's actually the only way to dark web theme rather than user agent darkening, see above comment.
WebSettingsCompat.setForceDarkStrategy(
settings,
WebSettingsCompat.DARK_STRATEGY_WEB_THEME_DARKENING_ONLY
)
}
}
// We are either in app dark theme or forced dark mode, just request dark theme without actually forcing it.
// Yes I know that flag's name is misleading to say the least.
WebSettingsCompat.setForceDark(settings, WebSettingsCompat.FORCE_DARK_ON)
} else {
// We are neither app dark theme or force dark mode or force dark mode is not supported.
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
// We are in app light theme and force dark mode is disabled therefore:
WebSettingsCompat.setForceDark(settings, WebSettingsCompat.FORCE_DARK_OFF)
} else {
// WebView force dark mode is not supported.
if (darkMode) {
// Fallback to our special rendering mode then if user requests dark mode
// TODO: Have a setting option to make this the default behaviour?
setColorMode(RenderingMode.INVERTED_GRAYSCALE)
} else {
setColorMode(userPreferences.renderingMode)
}
}
}
}
/**
* Initialize the settings of the WebView that are intrinsic to Lightning and cannot be altered
* by the user. Distinguish between Incognito and Regular tabs here.
*/
@SuppressLint("NewApi")
private fun WebView.initializeSettings() {
settings.apply {
// That needs to be false for WebRTC to work at all, don't ask me why
mediaPlaybackRequiresUserGesture = false
if (API >= Build.VERSION_CODES.LOLLIPOP && !isIncognito) {
mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
} else if (API >= Build.VERSION_CODES.LOLLIPOP) {
// We're in Incognito mode, reject
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
}
if (!isIncognito || Capabilities.FULL_INCOGNITO.isSupported) {
domStorageEnabled = true
cacheMode = LOAD_DEFAULT
databaseEnabled = true
cacheMode = WebSettings.LOAD_DEFAULT
} else {
domStorageEnabled = false
// TODO: Is this really needed for incognito mode?
cacheMode = LOAD_NO_CACHE
databaseEnabled = false
cacheMode = WebSettings.LOAD_NO_CACHE
}
setSupportZoom(true)
builtInZoomControls = true
displayZoomControls = false
allowContentAccess = true
allowFileAccess = true
allowFileAccessFromFileURLs = false
allowUniversalAccessFromFileURLs = false
// Needed to prevent CTRL+TAB to scroll back to top of the page
// See: https://github.com/Slion/Fulguris/issues/82
setNeedInitialFocus(false)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
getPathObservable("geolocation")
.subscribeOn(databaseScheduler)
.observeOn(mainScheduler)
.subscribe { file ->
setGeolocationDatabasePath(file.path)
}
}
}
}
private fun getPathObservable(subFolder: String) = Single.fromCallable {
activity.getDir(subFolder, 0)
}
/**
* This method is used to toggle the user agent between desktop and the current preference of
* the user.
*/
fun toggleDesktopUserAgent(aBypass: Boolean = true) {
// Toggle desktop mode
desktopMode = !desktopMode
desktopModeBypassDomainSettings = aBypass
}
/**
*
*/
fun toggleDarkMode(aBypass: Boolean = true) {
// Toggle dark mode
darkMode = !darkMode
darkModeBypassDomainSettings = aBypass
}
/**
* This method sets the user agent of the current tab based on the user's preference
*/
private fun setUserAgentForPreference(userPreferences: UserPreferences) {
webView?.settings?.userAgentString = userPreferences.userAgent(activity.application)
}
/**
* Save the state of this tab Web View and return it as a [Bundle].
* We get that state bundle either directly from our Web View,
* or from our frozen tab initializer if ever our Web View was never loaded.
*/
private fun webViewState(): Bundle = latentTabInitializer?.tabModel?.webView
?: Bundle(ClassLoader.getSystemClassLoader()).also {
webView?.saveState(it)
}
/**
*
*/
fun getModel() = TabModel(url, title, desktopMode, darkMode, favicon, searchQuery, searchActive, webViewState())
/**
* Save the state of this tab and return it as a [Bundle].
*/
fun saveState(): Bundle {
return getModel().toBundle()
}
/**
* Pause the current WebView instance.
*/
fun onPause() {
webView?.onPause()
Timber.d("WebView onPause: ${webView?.id}")
}
/**
* Resume the current WebView instance.
*/
fun onResume() {
webView?.onResume()
Timber.d("WebView onResume: ${webView?.id}")
}
/**
* Notify the WebView to stop the current load.
*/
fun stopLoading() {
webView?.stopLoading()
}
/**
* This method forces the layer type to hardware, which
* enables hardware rendering on the WebView instance
* of the current [WebPageTab].
*/
private fun setHardwareRendering() {
webView?.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
}
/**
* This method sets the layer type to none, which
* means that either the GPU and CPU can both compose
* the layers when necessary.
*/
private fun setNormalRendering() {
webView?.setLayerType(View.LAYER_TYPE_NONE, null)
}
/**
* This method forces the layer type to software, which
* disables hardware rendering on the WebView instance
* of the current [WebPageTab] and makes the CPU render
* the view.
*/
fun setSoftwareRendering() {
webView?.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
/**
* Sets the current rendering color of the WebView instance
* of the current [WebPageTab]. The for modes are normal
* rendering, inverted rendering, grayscale rendering,
* and inverted grayscale rendering
*
* @param mode the integer mode to set as the rendering mode.
* see the numbers in documentation above for the
* values this method accepts.
*/
private fun setColorMode(mode: RenderingMode) {
invertPage = false
when (mode) {
RenderingMode.NORMAL -> {
paint.colorFilter = null
// setSoftwareRendering(); // Some devices get segfaults
// in the WebView with Hardware Acceleration enabled,
// the only fix is to disable hardware rendering
//setNormalRendering()
// SL: enabled that and the performance gain is very noticeable on F(x)tec Pro1
// Notably on: https://www.bbc.com/worklife
setHardwareRendering()
}
RenderingMode.INVERTED -> {
val filterInvert = ColorMatrixColorFilter(
negativeColorArray
)
paint.colorFilter = filterInvert
setHardwareRendering()
invertPage = true
}
RenderingMode.GRAYSCALE -> {
val cm = ColorMatrix()
cm.setSaturation(0f)
val filterGray = ColorMatrixColorFilter(cm)
paint.colorFilter = filterGray
setHardwareRendering()
}
RenderingMode.INVERTED_GRAYSCALE -> {
val matrix = ColorMatrix()
matrix.set(negativeColorArray)
val matrixGray = ColorMatrix()
matrixGray.setSaturation(0f)
val concat = ColorMatrix()
concat.setConcat(matrix, matrixGray)
val filterInvertGray = ColorMatrixColorFilter(concat)
paint.colorFilter = filterInvertGray
setHardwareRendering()
invertPage = true
}
RenderingMode.INCREASE_CONTRAST -> {
val increaseHighContrast = ColorMatrixColorFilter(increaseContrastColorArray)
paint.colorFilter = increaseHighContrast
setHardwareRendering()
}
}
}
/**
* Pauses the JavaScript timers of the
* WebView instance, which will trigger a
* pause for all WebViews in the app.
*/
fun pauseTimers() {
webView?.pauseTimers()
Timber.d("Pausing JS timers")
}
/**
* Resumes the JavaScript timers of the
* WebView instance, which will trigger a
* resume for all WebViews in the app.
*/
fun resumeTimers() {
webView?.resumeTimers()
Timber.d("Resuming JS timers")
}
/**
* Requests focus down on the WebView instance
* if the view does not already have focus.
*/
fun requestFocus() {
if (webView?.hasFocus() == false) {
webView?.requestFocus()
}
}
/**
* Sets the visibility of the WebView to either
* View.GONE, View.VISIBLE, or View.INVISIBLE.
* other values passed in will have no effect.
*
* @param visible the visibility to set on the WebView.
*/
fun setVisibility(visible: Int) {
webView?.visibility = visible
}
/**
* Tells the WebView to reload the current page.
* If the proxy settings are not ready then the
* this method will not have an affect as the
* proxy must start before the load occurs.
*/
fun reload() {
// Check if configured proxy is available
if (!proxyUtils.isProxyReady(activity)) {
// User has been notified
return
}
// Handle the case where we display error page for instance
loadUrl(url)
//webView?.reload()
}
/**
* Finds all the instances of the text passed to this
* method and highlights the instances of that text
* in the WebView.
*
* @param text the text to search for.
*/
@SuppressLint("NewApi")
fun find(text: String) {
resetFind()
searchQuery = text
searchActive = true
// Kick off our search
webView?.findAllAsync(text)
}
fun findNext() {
webView?.findNext(true)
}
fun findPrevious() {
webView?.findNext(false)
}