-
Notifications
You must be signed in to change notification settings - Fork 873
/
BrowserTabFragment.kt
1763 lines (1493 loc) · 66.3 KB
/
BrowserTabFragment.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 (c) 2018 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.browser
import android.Manifest
import android.animation.LayoutTransition.CHANGING
import android.animation.LayoutTransition.DISAPPEARING
import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.app.ActivityOptions
import android.appwidget.AppWidgetManager
import android.content.*
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.text.Editable
import android.view.*
import android.view.View.*
import android.view.inputmethod.EditorInfo
import android.webkit.*
import android.webkit.WebView.FindListener
import android.webkit.WebView.HitTestResult
import android.webkit.WebView.HitTestResult.*
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.AnyThread
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.text.HtmlCompat
import androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY
import androidx.core.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.transaction
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.Observer
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.duckduckgo.app.autocomplete.api.AutoComplete.AutoCompleteSuggestion
import com.duckduckgo.app.bookmarks.ui.EditBookmarkDialogFragment
import com.duckduckgo.app.brokensite.BrokenSiteActivity
import com.duckduckgo.app.brokensite.BrokenSiteData
import com.duckduckgo.app.browser.BrowserTabViewModel.*
import com.duckduckgo.app.browser.autocomplete.BrowserAutoCompleteSuggestionsAdapter
import com.duckduckgo.app.browser.downloader.DownloadFailReason
import com.duckduckgo.app.browser.downloader.FileDownloadNotificationManager
import com.duckduckgo.app.browser.downloader.FileDownloader
import com.duckduckgo.app.browser.downloader.FileDownloader.FileDownloadListener
import com.duckduckgo.app.browser.downloader.FileDownloader.PendingFileDownload
import com.duckduckgo.app.browser.filechooser.FileChooserIntentBuilder
import com.duckduckgo.app.browser.model.BasicAuthenticationCredentials
import com.duckduckgo.app.browser.model.BasicAuthenticationRequest
import com.duckduckgo.app.browser.model.LongPressTarget
import com.duckduckgo.app.browser.omnibar.KeyboardAwareEditText
import com.duckduckgo.app.browser.omnibar.OmnibarScrolling
import com.duckduckgo.app.browser.session.WebViewSessionStorage
import com.duckduckgo.app.browser.shortcut.ShortcutBuilder
import com.duckduckgo.app.browser.tabpreview.WebViewPreviewGenerator
import com.duckduckgo.app.browser.tabpreview.WebViewPreviewPersister
import com.duckduckgo.app.browser.ui.HttpAuthenticationDialogFragment
import com.duckduckgo.app.browser.useragent.UserAgentProvider
import com.duckduckgo.app.cta.ui.*
import com.duckduckgo.app.fire.fireproofwebsite.data.FireproofWebsiteEntity
import com.duckduckgo.app.fire.fireproofwebsite.data.website
import com.duckduckgo.app.global.ViewModelFactory
import com.duckduckgo.app.global.device.DeviceInfo
import com.duckduckgo.app.global.model.orderedTrackingEntities
import com.duckduckgo.app.global.view.*
import com.duckduckgo.app.privacy.renderer.icon
import com.duckduckgo.app.statistics.VariantManager
import com.duckduckgo.app.statistics.pixels.Pixel
import com.duckduckgo.app.survey.model.Survey
import com.duckduckgo.app.survey.ui.SurveyActivity
import com.duckduckgo.app.tabs.model.TabEntity
import com.duckduckgo.app.tabs.ui.TabSwitcherActivity
import com.duckduckgo.app.widget.ui.AddWidgetInstructionsActivity
import com.duckduckgo.widget.SearchWidgetLight
import com.google.android.material.snackbar.Snackbar
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.fragment_browser_tab.*
import kotlinx.android.synthetic.main.include_add_widget_instruction_buttons.view.*
import kotlinx.android.synthetic.main.include_cta_buttons.view.*
import kotlinx.android.synthetic.main.include_dax_dialog_cta.*
import kotlinx.android.synthetic.main.include_find_in_page.*
import kotlinx.android.synthetic.main.include_new_browser_tab.*
import kotlinx.android.synthetic.main.include_omnibar_toolbar.*
import kotlinx.android.synthetic.main.include_omnibar_toolbar.omnibarTextInput
import kotlinx.android.synthetic.main.include_omnibar_toolbar.view.browserMenu
import kotlinx.android.synthetic.main.include_omnibar_toolbar.view.fireIconMenu
import kotlinx.android.synthetic.main.include_omnibar_toolbar.view.privacyGradeButton
import kotlinx.android.synthetic.main.include_omnibar_toolbar.view.tabsMenu
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.*
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.addBookmarksPopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.addToHome
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.backPopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.brokenSitePopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.findInPageMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.fireproofWebsitePopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.forwardPopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.newTabPopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.refreshPopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.requestDesktopSiteCheckMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.settingsPopupMenuItem
import kotlinx.android.synthetic.main.popup_window_browser_menu.view.whitelistPopupMenuItem
import kotlinx.coroutines.*
import org.jetbrains.anko.longToast
import org.jetbrains.anko.share
import timber.log.Timber
import java.io.File
import javax.inject.Inject
import kotlin.concurrent.thread
import kotlin.coroutines.CoroutineContext
class BrowserTabFragment : Fragment(), FindListener, CoroutineScope, DaxDialogListener, TrackersAnimatorListener {
private val supervisorJob = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = supervisorJob + Dispatchers.Main
@Inject
lateinit var webViewClient: BrowserWebViewClient
@Inject
lateinit var webChromeClient: BrowserChromeClient
@Inject
lateinit var viewModelFactory: ViewModelFactory
@Inject
lateinit var deviceInfo: DeviceInfo
@Inject
lateinit var fileChooserIntentBuilder: FileChooserIntentBuilder
@Inject
lateinit var fileDownloader: FileDownloader
@Inject
lateinit var fileDownloadNotificationManager: FileDownloadNotificationManager
@Inject
lateinit var webViewSessionStorage: WebViewSessionStorage
@Inject
lateinit var shortcutBuilder: ShortcutBuilder
@Inject
lateinit var clipboardManager: ClipboardManager
@Inject
lateinit var pixel: Pixel
@Inject
lateinit var ctaViewModel: CtaViewModel
@Inject
lateinit var omnibarScrolling: OmnibarScrolling
@Inject
lateinit var previewGenerator: WebViewPreviewGenerator
@Inject
lateinit var previewPersister: WebViewPreviewPersister
@Inject
lateinit var variantManager: VariantManager
val tabId get() = requireArguments()[TAB_ID_ARG] as String
lateinit var userAgentProvider: UserAgentProvider
var messageFromPreviousTab: Message? = null
private val initialUrl get() = requireArguments().getString(URL_EXTRA_ARG)
private val skipHome get() = requireArguments().getBoolean(SKIP_HOME_ARG)
private lateinit var popupMenu: BrowserPopupMenu
private lateinit var autoCompleteSuggestionsAdapter: BrowserAutoCompleteSuggestionsAdapter
// Used to represent a file to download, but may first require permission
private var pendingFileDownload: PendingFileDownload? = null
private var pendingUploadTask: ValueCallback<Array<Uri>>? = null
private lateinit var renderer: BrowserTabFragmentRenderer
private lateinit var decorator: BrowserTabFragmentDecorator
private val viewModel: BrowserTabViewModel by lazy {
val viewModel = ViewModelProvider(this, viewModelFactory).get(BrowserTabViewModel::class.java)
viewModel.loadData(tabId, initialUrl, skipHome)
viewModel
}
private val animatorHelper by lazy { BrowserTrackersAnimatorHelper() }
private val smoothProgressAnimator by lazy { SmoothProgressAnimator(pageLoadingIndicator) }
// Optimization to prevent against excessive work generating WebView previews; an existing job will be cancelled if a new one is launched
private var bitmapGeneratorJob: Job? = null
private val browserActivity
get() = activity as? BrowserActivity
private val tabsButton: TabSwitcherButton?
get() = appBarLayout.tabsMenu
private val fireMenuButton: ViewGroup?
get() = appBarLayout.fireIconMenu
private val menuButton: ViewGroup?
get() = appBarLayout.browserMenu
private var webView: DuckDuckGoWebView? = null
private val errorSnackbar: Snackbar by lazy {
Snackbar.make(browserLayout, R.string.crashedWebViewErrorMessage, Snackbar.LENGTH_INDEFINITE)
.setBehavior(NonDismissibleBehavior())
}
private val findInPageTextWatcher = object : TextChangedWatcher() {
override fun afterTextChanged(editable: Editable) {
viewModel.userFindingInPage(findInPageInput.text.toString())
}
}
private val omnibarInputTextWatcher = object : TextChangedWatcher() {
override fun afterTextChanged(editable: Editable) {
viewModel.onOmnibarInputStateChanged(omnibarTextInput.text.toString(), omnibarTextInput.hasFocus(), true)
}
}
private val logoHidingListener by lazy { LogoHidingLayoutChangeLifecycleListener(ddgLogo) }
private var alertDialog: AlertDialog? = null
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
removeDaxDialogFromActivity()
renderer = BrowserTabFragmentRenderer()
decorator = BrowserTabFragmentDecorator()
if (savedInstanceState != null) {
updateFragmentListener()
}
}
private fun updateFragmentListener() {
val fragment = fragmentManager?.findFragmentByTag(DOWNLOAD_CONFIRMATION_TAG) as? DownloadConfirmationFragment
fragment?.downloadListener = createDownloadListener()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_browser_tab, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
configureObservers()
configurePrivacyGrade()
configureWebView()
configureSwipeRefresh()
viewModel.registerWebViewListener(webViewClient, webChromeClient)
configureOmnibarTextInput()
configureFindInPage()
configureAutoComplete()
configureKeyboardAwareLogoAnimation()
decorator.decorateWithFeatures()
animatorHelper.setListener(this)
if (savedInstanceState == null) {
viewModel.onViewReady()
messageFromPreviousTab?.let {
processMessage(it)
}
}
lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
if (isVisible) {
updateOrDeleteWebViewPreview()
}
}
})
}
private fun getDaxDialogFromActivity(): Fragment? = activity?.supportFragmentManager?.findFragmentByTag(DAX_DIALOG_DIALOG_TAG)
private fun removeDaxDialogFromActivity() {
val fragment = getDaxDialogFromActivity()
fragment?.let {
activity?.supportFragmentManager?.transaction { remove(it) }
}
}
private fun processMessage(message: Message) {
val transport = message.obj as WebView.WebViewTransport
transport.webView = webView
message.sendToTarget()
decorator.animateTabsCount()
viewModel.onMessageProcessed()
}
private fun updateOrDeleteWebViewPreview() {
val url = viewModel.url
Timber.d("Updating or deleting WebView preview for $url")
if (url == null) {
viewModel.deleteTabPreview(tabId)
} else {
generateWebViewPreviewImage()
}
}
private fun launchTabSwitcher() {
val activity = activity ?: return
startActivity(TabSwitcherActivity.intent(activity, tabId))
activity.overridePendingTransition(R.anim.tab_anim_fade_in, R.anim.slide_to_bottom)
}
override fun onResume() {
super.onResume()
appBarLayout.setExpanded(true)
viewModel.onViewResumed()
logoHidingListener.onResume()
// onResume can be called for a hidden/backgrounded fragment, ensure this tab is visible.
if (fragmentIsVisible()) {
viewModel.onViewVisible()
}
addTextChangedListeners()
}
override fun onPause() {
logoHidingListener.onPause()
dismissDownloadFragment()
dismissAuthenticationDialog()
super.onPause()
}
private fun dismissAuthenticationDialog() {
if (isAdded) {
val fragment = parentFragmentManager.findFragmentByTag(AUTHENTICATION_DIALOG_TAG) as? HttpAuthenticationDialogFragment
fragment?.dismiss()
}
}
private fun dismissDownloadFragment() {
val fragment = fragmentManager?.findFragmentByTag(DOWNLOAD_CONFIRMATION_TAG) as? DownloadConfirmationFragment
fragment?.dismiss()
}
private fun addHomeShortcut(homeShortcut: Command.AddHomeShortcut, context: Context) {
val shortcutInfo = shortcutBuilder.buildPinnedPageShortcut(context, homeShortcut)
ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null)
}
private fun configureObservers() {
viewModel.autoCompleteViewState.observe(viewLifecycleOwner, Observer<AutoCompleteViewState> {
it?.let { renderer.renderAutocomplete(it) }
})
viewModel.globalLayoutState.observe(viewLifecycleOwner, Observer<GlobalLayoutViewState> {
it?.let { renderer.renderGlobalViewState(it) }
})
viewModel.browserViewState.observe(viewLifecycleOwner, Observer<BrowserViewState> {
it?.let { renderer.renderBrowserViewState(it) }
})
viewModel.loadingViewState.observe(viewLifecycleOwner, Observer<LoadingViewState> {
it?.let { renderer.renderLoadingIndicator(it) }
})
viewModel.omnibarViewState.observe(viewLifecycleOwner, Observer<OmnibarViewState> {
it?.let { renderer.renderOmnibar(it) }
})
viewModel.findInPageViewState.observe(viewLifecycleOwner, Observer<FindInPageViewState> {
it?.let { renderer.renderFindInPageState(it) }
})
viewModel.ctaViewState.observe(viewLifecycleOwner, Observer {
it?.let { renderer.renderCtaViewState(it) }
})
viewModel.command.observe(viewLifecycleOwner, Observer {
processCommand(it)
})
viewModel.survey.observe(viewLifecycleOwner, Observer<Survey> {
it.let { viewModel.onSurveyChanged(it) }
})
viewModel.privacyGradeViewState.observe(viewLifecycleOwner, Observer {
it.let { renderer.renderPrivacyGrade(it) }
})
addTabsObserver()
}
private fun addTabsObserver() {
viewModel.tabs.observe(viewLifecycleOwner, Observer<List<TabEntity>> {
it?.let {
decorator.renderTabIcon(it)
}
})
}
private fun fragmentIsVisible(): Boolean {
// using isHidden rather than isVisible, as isVisible will incorrectly return false when windowToken is not yet initialized.
// changes on isHidden will be received in onHiddenChanged
return !isHidden
}
private fun showHome() {
errorSnackbar.dismiss()
newTabLayout.show()
showKeyboardImmediately()
appBarLayout.setExpanded(true)
webView?.onPause()
webView?.hide()
omnibarScrolling.disableOmnibarScrolling(toolbarContainer)
logoHidingListener.onReadyToShowLogo()
}
private fun showBrowser() {
newTabLayout.gone()
webView?.show()
webView?.onResume()
omnibarScrolling.enableOmnibarScrolling(toolbarContainer)
}
fun submitQuery(query: String) {
viewModel.onUserSubmittedQuery(query)
}
private fun navigate(url: String) {
hideKeyboard()
renderer.hideFindInPage()
viewModel.registerDaxBubbleCtaDismissed()
webView?.loadUrl(url)
}
fun onRefreshRequested() {
viewModel.onRefreshRequested()
}
fun refresh() {
webView?.reload()
}
private fun processCommand(it: Command?) {
if (it !is Command.DaxCommand) {
renderer.cancelTrackersAnimation()
}
when (it) {
is Command.Refresh -> refresh()
is Command.OpenInNewTab -> {
browserActivity?.openInNewTab(it.query)
}
is Command.OpenMessageInNewTab -> {
browserActivity?.openMessageInNewTab(it.message)
}
is Command.OpenInNewBackgroundTab -> {
openInNewBackgroundTab()
}
is Command.LaunchNewTab -> browserActivity?.launchNewTab()
is Command.ShowBookmarkAddedConfirmation -> bookmarkAdded(it.bookmarkId, it.title, it.url)
is Command.ShowFireproofWebSiteConfirmation -> fireproofWebsiteConfirmation(it.fireproofWebsiteEntity)
is Command.Navigate -> {
navigate(it.url)
}
is Command.NavigateBack -> {
webView?.goBackOrForward(-it.steps)
}
is Command.NavigateForward -> {
webView?.goForward()
}
is Command.ResetHistory -> {
resetWebView()
}
is Command.DialNumber -> {
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:${it.telephoneNumber}")
openExternalDialog(intent, null, false)
}
is Command.SendEmail -> {
val intent = Intent(Intent.ACTION_SENDTO)
intent.data = Uri.parse(it.emailAddress)
openExternalDialog(intent)
}
is Command.SendSms -> {
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:${it.telephoneNumber}"))
openExternalDialog(intent)
}
is Command.ShowKeyboard -> {
showKeyboard()
}
is Command.HideKeyboard -> {
hideKeyboard()
}
is Command.BrokenSiteFeedback -> {
launchBrokenSiteFeedback(it.data)
}
is Command.ShowFullScreen -> {
webViewFullScreenContainer.addView(
it.view, ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
)
}
is Command.DownloadImage -> requestImageDownload(it.url, it.requestUserConfirmation)
is Command.FindInPageCommand -> webView?.findAllAsync(it.searchTerm)
is Command.DismissFindInPage -> webView?.findAllAsync("")
is Command.ShareLink -> launchSharePageChooser(it.url)
is Command.CopyLink -> {
clipboardManager.primaryClip = ClipData.newPlainText(null, it.url)
}
is Command.ShowFileChooser -> {
launchFilePicker(it)
}
is Command.AddHomeShortcut -> {
context?.let { context ->
addHomeShortcut(it, context)
}
}
is Command.HandleExternalAppLink -> {
openExternalDialog(it.appLink.intent, it.appLink.fallbackUrl, false)
}
is Command.LaunchSurvey -> launchSurvey(it.survey)
is Command.LaunchAddWidget -> launchAddWidget()
is Command.LaunchLegacyAddWidget -> launchLegacyAddWidget()
is Command.RequiresAuthentication -> showAuthenticationDialog(it.request)
is Command.SaveCredentials -> saveBasicAuthCredentials(it.request, it.credentials)
is Command.GenerateWebViewPreviewImage -> generateWebViewPreviewImage()
is Command.LaunchTabSwitcher -> launchTabSwitcher()
is Command.ShowErrorWithAction -> showErrorSnackbar(it)
is Command.DaxCommand.FinishTrackerAnimation -> finishTrackerAnimation()
is Command.DaxCommand.HideDaxDialog -> showHideTipsDialog(it.cta)
is Command.HideWebContent -> webView?.hide()
is Command.ShowWebContent -> webView?.show()
}
}
private fun launchBrokenSiteFeedback(data: BrokenSiteData) {
context?.let {
val options = ActivityOptions.makeSceneTransitionAnimation(browserActivity).toBundle()
startActivity(BrokenSiteActivity.intent(it, data), options)
}
}
private fun showErrorSnackbar(command: Command.ShowErrorWithAction) {
// Snackbar is global and it should appear only the foreground fragment
if (!errorSnackbar.view.isAttachedToWindow && isVisible) {
errorSnackbar.setAction(R.string.crashedWebViewErrorAction) { command.action() }.show()
}
}
private fun generateWebViewPreviewImage() {
webView?.let { webView ->
// if there's an existing job for generating a preview, cancel that in favor of the new request
bitmapGeneratorJob?.cancel()
bitmapGeneratorJob = launch {
Timber.d("Generating WebView preview")
try {
val preview = previewGenerator.generatePreview(webView)
val fileName = previewPersister.save(preview, tabId)
viewModel.updateTabPreview(tabId, fileName)
Timber.d("Saved and updated tab preview")
} catch (e: Exception) {
Timber.d(e, "Failed to generate WebView preview")
}
}
}
}
private fun openInNewBackgroundTab() {
appBarLayout.setExpanded(true, true)
viewModel.tabs.removeObservers(this)
decorator.incrementTabs()
}
private fun openExternalDialog(intent: Intent, fallbackUrl: String? = null, useFirstActivityFound: Boolean = true) {
context?.let {
val pm = it.packageManager
val activities = pm.queryIntentActivities(intent, 0)
if (activities.isEmpty()) {
if (fallbackUrl != null) {
webView?.loadUrl(fallbackUrl)
} else {
showToast(R.string.unableToOpenLink)
}
} else {
if (activities.size == 1 || useFirstActivityFound) {
val activity = activities.first()
val appTitle = activity.loadLabel(pm)
Timber.i("Exactly one app available for intent: $appTitle")
launchExternalAppDialog(it) { it.startActivity(intent) }
} else {
val title = getString(R.string.openExternalApp)
val intentChooser = Intent.createChooser(intent, title)
launchExternalAppDialog(it) { it.startActivity(intentChooser) }
}
}
}
}
private fun launchExternalAppDialog(context: Context, onClick: () -> Unit) {
val isShowing = alertDialog?.isShowing
if (isShowing != true) {
alertDialog = AlertDialog.Builder(context)
.setTitle(R.string.launchingExternalApp)
.setMessage(getString(R.string.confirmOpenExternalApp))
.setPositiveButton(R.string.yes) { _, _ ->
onClick()
}
.setNeutralButton(R.string.closeTab) { dialog, _ ->
dialog.dismiss()
launch {
viewModel.closeCurrentTab()
destroyWebView()
}
}
.setNegativeButton(R.string.no) { dialog, _ ->
dialog.dismiss()
}
.show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_CHOOSE_FILE) {
handleFileUploadResult(resultCode, data)
}
}
private fun handleFileUploadResult(resultCode: Int, intent: Intent?) {
if (resultCode != RESULT_OK || intent == null) {
Timber.i("Received resultCode $resultCode (or received null intent) indicating user did not select any files")
pendingUploadTask?.onReceiveValue(null)
return
}
val uris = fileChooserIntentBuilder.extractSelectedFileUris(intent)
pendingUploadTask?.onReceiveValue(uris)
}
private fun showToast(@StringRes messageId: Int) {
context?.applicationContext?.longToast(messageId)
}
private fun showAuthenticationDialog(request: BasicAuthenticationRequest) {
activity?.supportFragmentManager?.let { fragmentManager ->
val dialog = HttpAuthenticationDialogFragment.createHttpAuthenticationDialog(request.site)
dialog.show(fragmentManager, AUTHENTICATION_DIALOG_TAG)
dialog.listener = viewModel
dialog.request = request
}
}
private fun saveBasicAuthCredentials(request: BasicAuthenticationRequest, credentials: BasicAuthenticationCredentials) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val webViewDatabase = WebViewDatabase.getInstance(context)
webViewDatabase.setHttpAuthUsernamePassword(request.host, request.realm, credentials.username, credentials.password)
} else {
@Suppress("DEPRECATION")
webView?.setHttpAuthUsernamePassword(request.host, request.realm, credentials.username, credentials.password)
}
}
private fun configureAutoComplete() {
val context = context ?: return
autoCompleteSuggestionsList.layoutManager = LinearLayoutManager(context)
autoCompleteSuggestionsAdapter = BrowserAutoCompleteSuggestionsAdapter(
immediateSearchClickListener = {
userSelectedAutocomplete(it)
},
editableSearchClickListener = {
viewModel.onUserSelectedToEditQuery(it.phrase)
}
)
autoCompleteSuggestionsList.adapter = autoCompleteSuggestionsAdapter
}
private fun configurePrivacyGrade() {
toolbar.privacyGradeButton.setOnClickListener {
browserActivity?.launchPrivacyDashboard()
}
}
private fun configureFindInPage() {
findInPageInput.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus && findInPageInput.text.toString() != viewModel.findInPageViewState.value?.searchTerm) {
viewModel.userFindingInPage(findInPageInput.text.toString())
}
}
previousSearchTermButton.setOnClickListener { webView?.findNext(false) }
nextSearchTermButton.setOnClickListener { webView?.findNext(true) }
closeFindInPagePanel.setOnClickListener {
viewModel.dismissFindInView()
}
}
private fun configureOmnibarTextInput() {
omnibarTextInput.onFocusChangeListener =
OnFocusChangeListener { _, hasFocus: Boolean ->
viewModel.onOmnibarInputStateChanged(omnibarTextInput.text.toString(), hasFocus, false)
if (!hasFocus) {
omnibarTextInput.hideKeyboard()
focusDummy.requestFocus()
}
}
omnibarTextInput.onBackKeyListener = object : KeyboardAwareEditText.OnBackKeyListener {
override fun onBackKey(): Boolean {
omnibarTextInput.hideKeyboard()
focusDummy.requestFocus()
return true
}
}
omnibarTextInput.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, keyEvent ->
if (actionId == EditorInfo.IME_ACTION_GO || keyEvent?.keyCode == KeyEvent.KEYCODE_ENTER) {
userEnteredQuery(omnibarTextInput.text.toString())
return@OnEditorActionListener true
}
false
})
clearTextButton.setOnClickListener { omnibarTextInput.setText("") }
}
private fun configureKeyboardAwareLogoAnimation() {
newTabLayout.layoutTransition?.apply {
// we want layout transitions for when the size changes; we don't want them when items disappear (can cause glitch on call to action button)
enableTransitionType(CHANGING)
disableTransitionType(DISAPPEARING)
setDuration(LAYOUT_TRANSITION_MS)
}
rootView.addOnLayoutChangeListener(logoHidingListener)
}
private fun userSelectedAutocomplete(suggestion: AutoCompleteSuggestion) {
// send pixel before submitting the query and changing the autocomplete state to empty; otherwise will send the wrong params
GlobalScope.launch {
viewModel.fireAutocompletePixel(suggestion)
withContext(Dispatchers.Main) {
viewModel.onUserSubmittedQuery(suggestion.phrase)
}
}
}
private fun userEnteredQuery(query: String) {
viewModel.onUserSubmittedQuery(query)
}
@SuppressLint("SetJavaScriptEnabled")
private fun configureWebView() {
webView = layoutInflater.inflate(
R.layout.include_duckduckgo_browser_webview,
webViewContainer,
true
).findViewById(R.id.browserWebView) as DuckDuckGoWebView
webView?.let {
userAgentProvider = UserAgentProvider(it.settings.userAgentString, deviceInfo)
it.webViewClient = webViewClient
it.webChromeClient = webChromeClient
it.settings.apply {
userAgentString = userAgentProvider.getUserAgent()
javaScriptEnabled = true
domStorageEnabled = true
loadWithOverviewMode = true
useWideViewPort = true
builtInZoomControls = true
displayZoomControls = false
mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
setSupportMultipleWindows(true)
disableWebSql(this)
setSupportZoom(true)
}
it.setDownloadListener { url, _, contentDisposition, mimeType, _ ->
requestFileDownload(url, contentDisposition, mimeType, true)
}
it.setOnTouchListener { _, _ ->
if (omnibarTextInput.isFocused) {
focusDummy.requestFocus()
}
false
}
it.setEnableSwipeRefreshCallback { enable ->
swipeRefreshContainer?.isEnabled = enable
}
registerForContextMenu(it)
it.setFindListener(this)
}
if (BuildConfig.DEBUG) {
WebView.setWebContentsDebuggingEnabled(true)
}
}
private fun configureSwipeRefresh() {
swipeRefreshContainer.setColorSchemeColors(ContextCompat.getColor(requireContext(), R.color.cornflowerBlue))
swipeRefreshContainer.setOnRefreshListener {
onRefreshRequested()
}
swipeRefreshContainer.setCanChildScrollUpCallback {
webView?.canScrollVertically(-1) ?: false
}
// avoids progressView from showing under toolbar
swipeRefreshContainer.progressViewStartOffset = swipeRefreshContainer.progressViewStartOffset - 15
}
/**
* Explicitly disable database to try protect against Magellan WebSQL/SQLite vulnerability
*/
private fun disableWebSql(settings: WebSettings) {
settings.databaseEnabled = false
}
private fun addTextChangedListeners() {
findInPageInput.replaceTextChangedListener(findInPageTextWatcher)
omnibarTextInput.replaceTextChangedListener(omnibarInputTextWatcher)
}
override fun onCreateContextMenu(menu: ContextMenu, view: View, menuInfo: ContextMenu.ContextMenuInfo?) {
webView?.hitTestResult?.let {
val target = getLongPressTarget(it) ?: return
viewModel.userLongPressedInWebView(target, menu)
}
}
/**
* Use requestFocusNodeHref to get the a tag url for the touched image.
*/
private fun getTargetUrlForImageSource(): String? {
val handler = Handler()
val message = handler.obtainMessage()
webView?.requestFocusNodeHref(message)
return message.data.getString(URL_BUNDLE_KEY)
}
private fun getLongPressTarget(hitTestResult: HitTestResult): LongPressTarget? {
return when {
hitTestResult.extra == null -> null
hitTestResult.type == UNKNOWN_TYPE -> null
hitTestResult.type == IMAGE_TYPE -> LongPressTarget(
url = hitTestResult.extra,
imageUrl = hitTestResult.extra,
type = hitTestResult.type
)
hitTestResult.type == SRC_IMAGE_ANCHOR_TYPE -> LongPressTarget(
url = getTargetUrlForImageSource(),
imageUrl = hitTestResult.extra,
type = hitTestResult.type
)
else -> LongPressTarget(
url = hitTestResult.extra,
type = hitTestResult.type
)
}
}
override fun onContextItemSelected(item: MenuItem): Boolean {
webView?.hitTestResult?.let {
val target = getLongPressTarget(it)
if (target != null && viewModel.userSelectedItemFromLongPressMenu(target, item)) {
return true
}
}
return super.onContextItemSelected(item)
}
private fun bookmarkAdded(bookmarkId: Long, title: String?, url: String?) {
Snackbar.make(browserLayout, R.string.bookmarkEdited, Snackbar.LENGTH_LONG)
.setAction(R.string.edit) {
val addBookmarkDialog = EditBookmarkDialogFragment.instance(bookmarkId, title, url)
addBookmarkDialog.show(childFragmentManager, ADD_BOOKMARK_FRAGMENT_TAG)
addBookmarkDialog.listener = viewModel
}
.show()
}
private fun fireproofWebsiteConfirmation(entity: FireproofWebsiteEntity) {
Snackbar.make(
rootView,
HtmlCompat.fromHtml(getString(R.string.fireproofWebsiteSnackbarConfirmation, entity.website()), FROM_HTML_MODE_LEGACY),
Snackbar.LENGTH_LONG
)
.setAction(R.string.fireproofWebsiteSnackbarAction) {
viewModel.onFireproofWebsiteSnackbarUndoClicked(entity)
}
.show()
}
private fun launchSharePageChooser(url: String) {
activity?.share(url, "")
}
override fun onFindResultReceived(activeMatchOrdinal: Int, numberOfMatches: Int, isDoneCounting: Boolean) {
viewModel.onFindResultsReceived(activeMatchOrdinal, numberOfMatches)
}
private fun EditText.replaceTextChangedListener(textWatcher: TextChangedWatcher) {
removeTextChangedListener(textWatcher)
addTextChangedListener(textWatcher)
}
private fun hideKeyboardImmediately() {
if (!isHidden) {
Timber.v("Keyboard now hiding")
omnibarTextInput.hideKeyboard()
focusDummy.requestFocus()
}
}
private fun hideKeyboard() {
if (!isHidden) {
Timber.v("Keyboard now hiding")
omnibarTextInput.postDelayed(KEYBOARD_DELAY) { omnibarTextInput?.hideKeyboard() }
focusDummy.requestFocus()
}
}
private fun showKeyboardImmediately() {
if (!isHidden) {
Timber.v("Keyboard now showing")
omnibarTextInput?.showKeyboard()
}
}
private fun showKeyboard() {
if (!isHidden) {
Timber.v("Keyboard now showing")
omnibarTextInput.postDelayed(KEYBOARD_DELAY) { omnibarTextInput?.showKeyboard() }
}
}
/**
* Attempting to save the WebView's state can result in a TransactionTooLargeException being thrown.
* This will only happen if the bundle size is too large - but the exact size is undefined.
* Instead of saving using normal Android state mechanism - use our own implementation instead.
*/
override fun onSaveInstanceState(bundle: Bundle) {
viewModel.saveWebViewState(webView, tabId)
super.onSaveInstanceState(bundle)