-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
LocationBarMediator.java
1384 lines (1209 loc) · 59.4 KB
/
LocationBarMediator.java
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 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omnibox;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Property;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.CallbackController;
import org.chromium.base.CommandLine;
import org.chromium.base.ObserverList;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.base.supplier.ObservableSupplier;
import org.chromium.base.supplier.OneshotSupplier;
import org.chromium.base.supplier.OneshotSupplierImpl;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.download.DownloadUtils;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.gsa.GSAState;
import org.chromium.chrome.browser.lens.LensController;
import org.chromium.chrome.browser.lens.LensEntryPoint;
import org.chromium.chrome.browser.lens.LensIntentParams;
import org.chromium.chrome.browser.lens.LensQueryParams;
import org.chromium.chrome.browser.locale.LocaleManager;
import org.chromium.chrome.browser.ntp.FakeboxDelegate;
import org.chromium.chrome.browser.ntp.NewTabPageUma;
import org.chromium.chrome.browser.omnibox.UrlBar.UrlBarDelegate;
import org.chromium.chrome.browser.omnibox.UrlBarCoordinator.SelectionState;
import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader;
import org.chromium.chrome.browser.omnibox.status.StatusCoordinator;
import org.chromium.chrome.browser.omnibox.suggestions.AutocompleteCoordinator;
import org.chromium.chrome.browser.omnibox.voice.AssistantVoiceSearchService;
import org.chromium.chrome.browser.omnibox.voice.VoiceRecognitionHandler;
import org.chromium.chrome.browser.preferences.SharedPreferencesManager;
import org.chromium.chrome.browser.privacy.settings.PrivacyPreferencesManagerImpl;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.ui.native_page.NativePage;
import org.chromium.chrome.browser.util.ChromeAccessibilityUtil;
import org.chromium.chrome.browser.util.KeyNavigationUtil;
import org.chromium.components.browser_ui.styles.ChromeColors;
import org.chromium.components.browser_ui.widget.animation.CancelAwareAnimatorListener;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.externalauth.ExternalAuthUtils;
import org.chromium.components.search_engines.TemplateUrl;
import org.chromium.components.search_engines.TemplateUrlService;
import org.chromium.components.search_engines.TemplateUrlService.TemplateUrlServiceObserver;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.common.ResourceRequestBody;
import org.chromium.ui.base.PageTransition;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.interpolators.BakedBezierInterpolator;
import org.chromium.ui.util.ColorUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Mediator for the LocationBar component. Intended location for LocationBar business logic;
* currently, migration of this logic out of LocationBarLayout is in progress.
*/
class LocationBarMediator implements LocationBarDataProvider.Observer, FakeboxDelegate,
VoiceRecognitionHandler.Delegate,
VoiceRecognitionHandler.Observer,
AssistantVoiceSearchService.Observer, UrlBarDelegate,
OnKeyListener, ComponentCallbacks, TemplateUrlServiceObserver {
private static final int ICON_FADE_ANIMATION_DURATION_MS = 150;
private static final int ICON_FADE_ANIMATION_DELAY_MS = 75;
private static final long NTP_KEYBOARD_FOCUS_DURATION_MS = 200;
private static final int WIDTH_CHANGE_ANIMATION_DURATION_MS = 225;
private static final int WIDTH_CHANGE_ANIMATION_DELAY_MS = 75;
private final Property<LocationBarMediator, Float> mUrlFocusChangeFractionProperty =
new Property<LocationBarMediator, Float>(Float.class, "") {
@Override
public Float get(LocationBarMediator object) {
return mUrlFocusChangeFraction;
}
@Override
public void set(LocationBarMediator object, Float value) {
setUrlFocusChangeFraction(value);
}
};
private final Property<LocationBarMediator, Float> mWidthChangeFractionPropertyTablet =
new Property<LocationBarMediator, Float>(Float.class, "") {
@Override
public Float get(LocationBarMediator object) {
return ((LocationBarTablet) mLocationBarLayout).getWidthChangeFraction();
}
@Override
public void set(LocationBarMediator object, Float value) {
((LocationBarTablet) mLocationBarLayout).setWidthChangeAnimationFraction(value);
}
};
private final LocationBarLayout mLocationBarLayout;
private VoiceRecognitionHandler mVoiceRecognitionHandler;
private final LocationBarDataProvider mLocationBarDataProvider;
private final OneshotSupplierImpl<AssistantVoiceSearchService>
mAssistantVoiceSearchServiceSupplier = new OneshotSupplierImpl<>();
private StatusCoordinator mStatusCoordinator;
private AutocompleteCoordinator mAutocompleteCoordinator;
private OmniboxPrerender mOmniboxPrerender;
private UrlBarCoordinator mUrlCoordinator;
private ObservableSupplier<Profile> mProfileSupplier;
private PrivacyPreferencesManagerImpl mPrivacyPreferencesManager;
private CallbackController mCallbackController = new CallbackController();
private final OverrideUrlLoadingDelegate mOverrideUrlLoadingDelegate;
private final LocaleManager mLocaleManager;
private final List<Runnable> mDeferredNativeRunnables = new ArrayList<>();
private final OneshotSupplier<TemplateUrlService> mTemplateUrlServiceSupplier;
private TemplateUrl mSearchEngine;
private final Context mContext;
private final BackKeyBehaviorDelegate mBackKeyBehavior;
private final WindowAndroid mWindowAndroid;
private String mOriginalUrl = "";
private Animator mUrlFocusChangeAnimator;
private final ObserverList<UrlFocusChangeListener> mUrlFocusChangeListeners =
new ObserverList<>();
private final Rect mRootViewBounds = new Rect();
private final SearchEngineLogoUtils mSearchEngineLogoUtils;
private boolean mNativeInitialized;
private boolean mUrlFocusedFromFakebox;
private boolean mUrlFocusedFromQueryTiles;
private boolean mUrlFocusedWithoutAnimations;
private boolean mIsUrlFocusChangeInProgress;
private final boolean mIsTablet;
private boolean mShouldShowLensButtonWhenUnfocused;
private boolean mShouldShowMicButtonWhenUnfocused;
// Whether the microphone and bookmark buttons should be shown in the tablet location bar. These
// buttons are hidden if the window size is < 600dp.
private boolean mShouldShowButtonsWhenUnfocused;
private float mUrlFocusChangeFraction;
private boolean mUrlHasFocus;
private LensController mLensController;
/*package */ LocationBarMediator(@NonNull Context context,
@NonNull LocationBarLayout locationBarLayout,
@NonNull LocationBarDataProvider locationBarDataProvider,
@NonNull ObservableSupplier<Profile> profileSupplier,
@NonNull PrivacyPreferencesManagerImpl privacyPreferencesManager,
@NonNull OverrideUrlLoadingDelegate overrideUrlLoadingDelegate,
@NonNull LocaleManager localeManager,
@NonNull OneshotSupplier<TemplateUrlService> templateUrlServiceSupplier,
@NonNull BackKeyBehaviorDelegate backKeyBehavior, @NonNull WindowAndroid windowAndroid,
boolean isTablet, @NonNull SearchEngineLogoUtils searchEngineLogoUtils,
@NonNull LensController lensController) {
mContext = context;
mLocationBarLayout = locationBarLayout;
mLocationBarDataProvider = locationBarDataProvider;
mLocationBarDataProvider.addObserver(this);
mOverrideUrlLoadingDelegate = overrideUrlLoadingDelegate;
mLocaleManager = localeManager;
mVoiceRecognitionHandler =
new VoiceRecognitionHandler(this, mAssistantVoiceSearchServiceSupplier);
mVoiceRecognitionHandler.addObserver(this);
mProfileSupplier = profileSupplier;
mProfileSupplier.addObserver(mCallbackController.makeCancelable(this::setProfile));
mPrivacyPreferencesManager = privacyPreferencesManager;
mTemplateUrlServiceSupplier = templateUrlServiceSupplier;
mBackKeyBehavior = backKeyBehavior;
mWindowAndroid = windowAndroid;
mIsTablet = isTablet;
mSearchEngineLogoUtils = searchEngineLogoUtils;
mShouldShowButtonsWhenUnfocused = isTablet;
mLensController = lensController;
}
/**
* Sets coordinators post-construction; they can't be set at construction time since
* LocationBarMediator is a delegate for them, so is constructed beforehand.
*
* @param urlCoordinator Coordinator for the url bar.
* @param autocompleteCoordinator Coordinator for the autocomplete component.
* @param statusCoordinator Coordinator for the status icon.
*/
/*package */ void setCoordinators(UrlBarCoordinator urlCoordinator,
AutocompleteCoordinator autocompleteCoordinator, StatusCoordinator statusCoordinator) {
mUrlCoordinator = urlCoordinator;
mAutocompleteCoordinator = autocompleteCoordinator;
mStatusCoordinator = statusCoordinator;
updateShouldAnimateIconChanges();
updateButtonVisibility();
if (mIsTablet) {
mStatusCoordinator.setShowIconsWhenUrlFocused(true);
if (mSearchEngineLogoUtils.shouldShowSearchEngineLogo(
mLocationBarDataProvider.isIncognito())) {
mStatusCoordinator.setStatusIconShown(true);
}
}
}
/*package */ void destroy() {
if (mAssistantVoiceSearchServiceSupplier.get() != null) {
mAssistantVoiceSearchServiceSupplier.get().destroy();
}
mStatusCoordinator = null;
mAutocompleteCoordinator = null;
mUrlCoordinator = null;
mPrivacyPreferencesManager = null;
mVoiceRecognitionHandler.removeObserver(this);
mVoiceRecognitionHandler.destroy();
mVoiceRecognitionHandler = null;
mLocationBarDataProvider.removeObserver(this);
mDeferredNativeRunnables.clear();
TemplateUrlService templateUrlService = mTemplateUrlServiceSupplier.get();
if (templateUrlService != null) {
templateUrlService.removeObserver(this);
}
mUrlFocusChangeListeners.clear();
}
/*package */ void onUrlFocusChange(boolean hasFocus) {
setUrlFocusChangeInProgress(true);
mUrlHasFocus = hasFocus;
updateButtonVisibility();
updateShouldAnimateIconChanges();
onPrimaryColorChanged();
if (hasFocus) {
if (mNativeInitialized) RecordUserAction.record("FocusLocation");
UrlBarData urlBarData = mLocationBarDataProvider.getUrlBarData();
if (urlBarData.editingText != null) {
setUrlBarText(urlBarData, UrlBar.ScrollType.NO_SCROLL, SelectionState.SELECT_ALL);
}
} else {
mUrlFocusedFromFakebox = false;
mUrlFocusedFromQueryTiles = false;
mUrlFocusedWithoutAnimations = false;
}
mStatusCoordinator.onUrlFocusChange(hasFocus);
if (!mUrlFocusedWithoutAnimations) handleUrlFocusAnimation(hasFocus);
if (hasFocus && mLocationBarDataProvider.hasTab()
&& !mLocationBarDataProvider.isIncognito()) {
if (mNativeInitialized
&& mTemplateUrlServiceSupplier.get().isDefaultSearchEngineGoogle()) {
GeolocationHeader.primeLocationForGeoHeader();
} else {
mDeferredNativeRunnables.add(() -> {
if (mTemplateUrlServiceSupplier.get().isDefaultSearchEngineGoogle()) {
GeolocationHeader.primeLocationForGeoHeader();
}
});
}
} // Focus change caused by a closed tab may result in there not being an active tab.
if (!hasFocus && mLocationBarDataProvider.hasTab()) {
setUrl(mLocationBarDataProvider.getCurrentUrl(),
mLocationBarDataProvider.getUrlBarData());
}
}
/*package */ void onFinishNativeInitialization() {
mNativeInitialized = true;
mTemplateUrlServiceSupplier.get().runWhenLoaded(this::registerTemplateUrlObserver);
mOmniboxPrerender = new OmniboxPrerender();
mAssistantVoiceSearchServiceSupplier.set(new AssistantVoiceSearchService(mContext,
ExternalAuthUtils.getInstance(), mTemplateUrlServiceSupplier.get(),
GSAState.getInstance(mContext), this, SharedPreferencesManager.getInstance()));
onAssistantVoiceSearchServiceChanged();
mLocationBarLayout.onFinishNativeInitialization();
setProfile(mProfileSupplier.get());
onPrimaryColorChanged();
mLocationBarLayout.updateStatusVisibility();
for (Runnable deferredRunnable : mDeferredNativeRunnables) {
mLocationBarLayout.post(deferredRunnable);
}
mDeferredNativeRunnables.clear();
updateMicButtonState();
updateLensButtonState();
}
/*package */ void setUrlFocusChangeFraction(float fraction) {
mUrlFocusChangeFraction = fraction;
if (mIsTablet) {
mLocationBarDataProvider.getNewTabPageDelegate().setUrlFocusChangeAnimationPercent(
fraction);
} else {
if (fraction > 0f) {
mLocationBarLayout.setUrlActionContainerVisibility(View.VISIBLE);
} else if (fraction == 0f && !mIsUrlFocusChangeInProgress) {
// If a URL focus change is in progress, then it will handle setting the visibility
// correctly after it completes. If done here, it would cause the URL to jump due
// to a badly timed layout call.
mLocationBarLayout.setUrlActionContainerVisibility(View.GONE);
}
mStatusCoordinator.setUrlFocusChangePercent(fraction);
updateButtonVisibility();
}
}
/*package */ void setUnfocusedWidth(int unfocusedWidth) {
mLocationBarLayout.setUnfocusedWidth(unfocusedWidth);
}
/* package */ void setVoiceRecognitionHandlerForTesting(
VoiceRecognitionHandler voiceRecognitionHandler) {
mVoiceRecognitionHandler = voiceRecognitionHandler;
}
/* package */ void setAssistantVoiceSearchServiceForTesting(
AssistantVoiceSearchService assistantVoiceSearchService) {
mAssistantVoiceSearchServiceSupplier.set(assistantVoiceSearchService);
onAssistantVoiceSearchServiceChanged();
}
/* package */ void setLensControllerForTesting(LensController lensController) {
mLensController = lensController;
}
/* package */ OneshotSupplier<AssistantVoiceSearchService>
getAssistantVoiceSearchServiceSupplierForTesting() {
return mAssistantVoiceSearchServiceSupplier;
}
/* package */ void setIsUrlBarFocusedWithoutAnimationsForTesting(
boolean isUrlBarFocusedWithoutAnimations) {
mUrlFocusedWithoutAnimations = isUrlBarFocusedWithoutAnimations;
}
/*package */ void updateVisualsForState() {
onPrimaryColorChanged();
}
/*package */ void setShowTitle(boolean showTitle) {
// This method is only used in CustomTabToolbar.
}
/*package */ void showUrlBarCursorWithoutFocusAnimations() {
if (mUrlHasFocus || mUrlFocusedFromFakebox) {
return;
}
mUrlFocusedWithoutAnimations = true;
// This method should only be called on devices with a hardware keyboard attached, as
// described in the documentation for LocationBar#showUrlBarCursorWithoutFocusAnimations.
setUrlBarFocus(/*shouldBeFocused=*/true, /*pastedText=*/null,
OmniboxFocusReason.DEFAULT_WITH_HARDWARE_KEYBOARD);
}
/*package */ void revertChanges() {
if (mUrlHasFocus) {
String currentUrl = mLocationBarDataProvider.getCurrentUrl();
if (NativePage.isNativePageUrl(currentUrl, mLocationBarDataProvider.isIncognito())) {
setUrlBarTextEmpty();
} else {
setUrlBarText(mLocationBarDataProvider.getUrlBarData(), UrlBar.ScrollType.NO_SCROLL,
SelectionState.SELECT_ALL);
}
mUrlCoordinator.setKeyboardVisibility(false, false);
} else {
setUrl(mLocationBarDataProvider.getCurrentUrl(),
mLocationBarDataProvider.getUrlBarData());
}
}
/* package */ void onUrlTextChanged() {
updateButtonVisibility();
}
/* package */ void onSuggestionsChanged(String autocompleteText, boolean defaultMatchIsSearch) {
// TODO (https://crbug.com/1152501): Refactor the LBM/LBC relationship such that LBM doesn't
// need to communicate with other coordinators like this.
mStatusCoordinator.onDefaultMatchClassified(defaultMatchIsSearch);
String userText = mUrlCoordinator.getTextWithoutAutocomplete();
if (mUrlCoordinator.shouldAutocomplete()) {
mUrlCoordinator.setAutocompleteText(userText, autocompleteText);
}
// Handle the case where suggestions (in particular zero suggest) are received without the
// URL focusing happening.
if (mUrlFocusedWithoutAnimations && mUrlHasFocus) {
handleUrlFocusAnimation(/*hasFocus=*/true);
}
if (mNativeInitialized
&& !CommandLine.getInstance().hasSwitch(ChromeSwitches.DISABLE_INSTANT)
&& mPrivacyPreferencesManager.shouldPrerender()
&& mLocationBarDataProvider.hasTab()) {
mOmniboxPrerender.prerenderMaybe(userText, mOriginalUrl,
mAutocompleteCoordinator.getCurrentNativeAutocompleteResult(),
mProfileSupplier.get(), mLocationBarDataProvider.getTab());
}
}
/* package */ void loadUrl(String url, int transition, long inputStart) {
loadUrlWithPostData(url, transition, inputStart, null, null);
}
/* package */ void loadUrlWithPostData(
String url, int transition, long inputStart, String postDataType, byte[] postData) {
assert mLocationBarDataProvider != null;
Tab currentTab = mLocationBarDataProvider.getTab();
// The code of the rest of this class ensures that this can't be called until the native
// side is initialized
assert mNativeInitialized : "Loading URL before native side initialized";
// TODO(crbug.com/1085812): Should be taking a full loaded LoadUrlParams.
if (mOverrideUrlLoadingDelegate.willHandleLoadUrlWithPostData(url, transition, postDataType,
postData, mLocationBarDataProvider.isIncognito())) {
return;
}
if (currentTab != null
&& (currentTab.isNativePage()
|| UrlUtilities.isNTPUrl(currentTab.getUrlString()))) {
NewTabPageUma.recordOmniboxNavigation(url, transition);
// Passing in an empty string should not do anything unless the user is at the NTP.
// Since the NTP has no url, pressing enter while clicking on the URL bar should refresh
// the page as it does when you click and press enter on any other site.
if (url.isEmpty()) url = currentTab.getUrlString();
}
// Loads the |url| in a new tab or the current ContentView and gives focus to the
// ContentView.
if (currentTab != null && !url.isEmpty()) {
LoadUrlParams loadUrlParams = new LoadUrlParams(url);
loadUrlParams.setVerbatimHeaders(GeolocationHeader.getGeoHeader(url, currentTab));
loadUrlParams.setTransitionType(transition | PageTransition.FROM_ADDRESS_BAR);
if (inputStart != 0) {
loadUrlParams.setInputStartTimestamp(inputStart);
}
if (!TextUtils.isEmpty(postDataType)) {
StringBuilder headers = new StringBuilder();
String prevHeader = loadUrlParams.getVerbatimHeaders();
if (prevHeader != null && !prevHeader.isEmpty()) {
headers.append(prevHeader);
headers.append("\r\n");
}
loadUrlParams.setExtraHeaders(new HashMap<String, String>() {
{ put("Content-Type", postDataType); }
});
headers.append(loadUrlParams.getExtraHttpRequestHeadersString());
loadUrlParams.setVerbatimHeaders(headers.toString());
}
if (postData != null && postData.length != 0) {
loadUrlParams.setPostData(ResourceRequestBody.createFromBytes(postData));
}
currentTab.loadUrl(loadUrlParams);
RecordUserAction.record("MobileOmniboxUse");
}
mLocaleManager.recordLocaleBasedSearchMetrics(false, url, transition);
focusCurrentTab();
}
/* package */ boolean didFocusUrlFromFakebox() {
return mUrlFocusedFromFakebox;
}
/* package */ boolean didFocusUrlFromQueryTiles() {
return mUrlFocusedFromQueryTiles;
}
/** Recalculates the visibility of the buttons inside the location bar. */
/* package */ void updateButtonVisibility() {
updateDeleteButtonVisibility();
updateMicButtonVisibility();
updateLensButtonVisibility();
if (mIsTablet) {
updateTabletButtonsVisibility();
}
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
/* package */ void registerTemplateUrlObserver() {
final TemplateUrlService templateUrlService = mTemplateUrlServiceSupplier.get();
templateUrlService.addObserver(this);
// Force an update once to populate initial data.
onTemplateURLServiceChanged();
}
/**
* Sets the displayed URL according to the provided url string and UrlBarData.
*
* <p>The URL is converted to the most user friendly format (removing HTTP:// for example).
*
* <p>If the current tab is null, the URL text will be cleared.
*/
/* package */ void setUrl(String currentUrlString, UrlBarData urlBarData) {
// If the URL is currently focused, do not replace the text they have entered with the URL.
// Once they stop editing the URL, the current tab's URL will automatically be filled in.
if (mUrlCoordinator.hasFocus()) {
if (mUrlFocusedWithoutAnimations && !UrlUtilities.isNTPUrl(currentUrlString)) {
// If we did not run the focus animations, then the user has not typed any text.
// So, clear the focus and accept whatever URL the page is currently attempting to
// display. If the NTP is showing, the current page's URL should not be displayed.
setUrlBarFocus(false, null, OmniboxFocusReason.UNFOCUS);
} else {
return;
}
}
mOriginalUrl = currentUrlString;
setUrlBarText(urlBarData, UrlBar.ScrollType.SCROLL_TO_TLD, SelectionState.SELECT_ALL);
}
/* package */ void deleteButtonClicked(View view) {
if (!mNativeInitialized) return;
RecordUserAction.record("MobileOmniboxDeleteUrl");
setUrlBarTextEmpty();
updateButtonVisibility();
}
/* package */ void micButtonClicked(View view) {
if (!mNativeInitialized) return;
RecordUserAction.record("MobileOmniboxVoiceSearch");
mVoiceRecognitionHandler.startVoiceRecognition(
VoiceRecognitionHandler.VoiceInteractionSource.OMNIBOX);
}
/** package */ void lensButtonClicked(View view) {
if (!mNativeInitialized || mLocationBarDataProvider == null) return;
RecordUserAction.record("MobileOmniboxLens");
startLens(LensEntryPoint.OMNIBOX);
}
/* package */ void setUrlFocusChangeInProgress(boolean inProgress) {
if (mUrlCoordinator == null) return;
mIsUrlFocusChangeInProgress = inProgress;
if (!inProgress) {
updateButtonVisibility();
// The accessibility bounding box is not properly updated when focusing the Omnibox
// from the NTP fakebox. Clearing/re-requesting focus triggers the bounding box to
// be recalculated.
if (didFocusUrlFromFakebox() && mUrlHasFocus
&& ChromeAccessibilityUtil.get().isAccessibilityEnabled()) {
String existingText = mUrlCoordinator.getTextWithoutAutocomplete();
mUrlCoordinator.clearFocus();
mUrlCoordinator.requestFocus();
// Existing text (e.g. if the user pasted via the fakebox) from the fake box
// should be restored after toggling the focus.
if (!TextUtils.isEmpty(existingText)) {
mUrlCoordinator.setUrlBarData(UrlBarData.forNonUrlText(existingText),
UrlBar.ScrollType.NO_SCROLL,
UrlBarCoordinator.SelectionState.SELECT_END);
forceOnTextChanged();
}
}
for (UrlFocusChangeListener listener : mUrlFocusChangeListeners) {
listener.onUrlAnimationFinished(mUrlHasFocus);
}
}
}
/**
* Handles any actions to be performed after all other actions triggered by the URL focus
* change. This will be called after any animations are performed to transition from one
* focus state to the other.
* @param hasFocus Whether the URL field has gained focus.
* @param shouldShowKeyboard Whether the keyboard should be shown. This value should be the same
* as hasFocus by default.
*/
/* package */ void finishUrlFocusChange(boolean hasFocus, boolean shouldShowKeyboard) {
if (mUrlCoordinator == null) return;
mUrlCoordinator.setKeyboardVisibility(hasFocus && shouldShowKeyboard, true);
setUrlFocusChangeInProgress(false);
updateShouldAnimateIconChanges();
mStatusCoordinator.onUrlAnimationFinished(hasFocus);
if (!mIsTablet && !hasFocus) {
mLocationBarLayout.setUrlActionContainerVisibility(View.GONE);
}
}
/**
* Handle and run any necessary animations that are triggered off focusing the UrlBar.
* @param hasFocus Whether focus was gained.
*/
@VisibleForTesting
/* package */ void handleUrlFocusAnimation(boolean hasFocus) {
if (hasFocus) {
mUrlFocusedWithoutAnimations = false;
}
for (UrlFocusChangeListener listener : mUrlFocusChangeListeners) {
listener.onUrlFocusChange(hasFocus);
}
// The focus animation for phones is driven by ToolbarPhone, so we don't currently have any
// phone-specific animation logic in this class.
if (mIsTablet) {
if (mUrlFocusChangeAnimator != null && mUrlFocusChangeAnimator.isRunning()) {
mUrlFocusChangeAnimator.cancel();
mUrlFocusChangeAnimator = null;
}
if (mLocationBarDataProvider.getNewTabPageDelegate().isCurrentlyVisible()) {
finishUrlFocusChange(hasFocus, /* shouldShowKeyboard= */ hasFocus);
return;
}
mLocationBarLayout.getRootView().getLocalVisibleRect(mRootViewBounds);
float screenSizeRatio = (mRootViewBounds.height()
/ (float) (Math.max(mRootViewBounds.height(), mRootViewBounds.width())));
mUrlFocusChangeAnimator = ObjectAnimator.ofFloat(
this, mUrlFocusChangeFractionProperty, hasFocus ? 1f : 0f);
mUrlFocusChangeAnimator.setDuration(
(long) (NTP_KEYBOARD_FOCUS_DURATION_MS * screenSizeRatio));
mUrlFocusChangeAnimator.addListener(new CancelAwareAnimatorListener() {
@Override
public void onEnd(Animator animator) {
finishUrlFocusChange(hasFocus, /* shouldShowKeyboard= */ hasFocus);
}
@Override
public void onCancel(Animator animator) {
setUrlFocusChangeInProgress(false);
}
});
mUrlFocusChangeAnimator.start();
}
}
/* package */ void setShouldShowMicButtonWhenUnfocusedForPhone(boolean shouldShow) {
assert !mIsTablet;
mShouldShowMicButtonWhenUnfocused = shouldShow;
}
/* package */ void setShouldShowLensButtonWhenUnfocusedForPhone(boolean shouldShow) {
assert !mIsTablet;
mShouldShowLensButtonWhenUnfocused = shouldShow;
}
/**
* @param shouldShow Whether buttons should be displayed in the URL bar when it's not
* focused.
*/
/* package */ void setShouldShowButtonsWhenUnfocusedForTablet(boolean shouldShow) {
assert mIsTablet;
mShouldShowButtonsWhenUnfocused = shouldShow;
updateButtonVisibility();
}
/**
* @param button The {@link View} of the button to show.
* Returns An animator to run for the given view when showing buttons in the unfocused location
* bar. This should also be used to create animators for showing toolbar buttons.
*/
/* package */ ObjectAnimator createShowButtonAnimatorForTablet(View button) {
assert mIsTablet;
if (button.getVisibility() != View.VISIBLE) {
button.setAlpha(0.f);
}
ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(button, View.ALPHA, 1.f);
buttonAnimator.setInterpolator(BakedBezierInterpolator.FADE_IN_CURVE);
buttonAnimator.setStartDelay(ICON_FADE_ANIMATION_DELAY_MS);
buttonAnimator.setDuration(ICON_FADE_ANIMATION_DURATION_MS);
return buttonAnimator;
}
/**
* @param button The {@link View} of the button to hide.
* Returns An animator to run for the given view when hiding buttons in the unfocused location
* bar. This should also be used to create animators for hiding toolbar buttons.
*/
/* package */ ObjectAnimator createHideButtonAnimatorForTablet(View button) {
assert mIsTablet;
ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(button, View.ALPHA, 0.f);
buttonAnimator.setInterpolator(BakedBezierInterpolator.FADE_OUT_CURVE);
buttonAnimator.setDuration(ICON_FADE_ANIMATION_DURATION_MS);
return buttonAnimator;
}
/**
* Creates animators for showing buttons in the unfocused tablet location bar. The buttons fade
* in while the width of the location bar decreases. There are toolbar buttons that show at
* the same time, causing the width of the location bar to change.
*
* @param toolbarStartPaddingDifference The difference in the toolbar's start padding between
* the beginning and end of the animation.
* @return A List of animators to run.
*/
/* package */ List<Animator> getShowButtonsWhenUnfocusedAnimatorsForTablet(
int toolbarStartPaddingDifference) {
assert mIsTablet;
LocationBarTablet locationBarTablet = ((LocationBarTablet) mLocationBarLayout);
ArrayList<Animator> animators = new ArrayList<>();
Animator widthChangeAnimator =
ObjectAnimator.ofFloat(this, mWidthChangeFractionPropertyTablet, 0f);
widthChangeAnimator.setDuration(WIDTH_CHANGE_ANIMATION_DURATION_MS);
widthChangeAnimator.setInterpolator(BakedBezierInterpolator.TRANSFORM_CURVE);
widthChangeAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
locationBarTablet.startAnimatingWidthChange(toolbarStartPaddingDifference);
setShouldShowButtonsWhenUnfocusedForTablet(true);
}
@Override
public void onAnimationEnd(Animator animation) {
// Only reset values if the animation is ending because it's completely finished
// and not because it was canceled.
if (locationBarTablet.getWidthChangeFraction() == 0.f) {
locationBarTablet.finishAnimatingWidthChange();
locationBarTablet.resetValuesAfterAnimation();
}
}
});
animators.add(widthChangeAnimator);
// When buttons show in the unfocused location bar, either the delete button or bookmark
// button will be showing. If the delete button is currently showing, the bookmark button
// should not fade in.
if (!locationBarTablet.isDeleteButtonVisible()) {
animators.add(createShowButtonAnimatorForTablet(
locationBarTablet.getBookmarkButtonForAnimation()));
}
if (shouldShowSaveOfflineButton()) {
animators.add(createShowButtonAnimatorForTablet(
locationBarTablet.getSaveOfflineButtonForAnimation()));
} else if (!locationBarTablet.isMicButtonVisible()
|| locationBarTablet.getMicButtonAlpha() != 1.f) {
// If the microphone button is already fully visible, don't animate its appearance.
animators.add(createShowButtonAnimatorForTablet(
locationBarTablet.getMicButtonForAnimation()));
}
return animators;
}
/**
* Creates animators for hiding buttons in the unfocused tablet location bar. The buttons fade
* out while the width of the location bar increases. There are toolbar buttons that hide at
* the same time, causing the width of the location bar to change.
*
* @param toolbarStartPaddingDifference The difference in the toolbar's start padding between
* the beginning and end of the animation.
* @return A List of animators to run.
*/
/* package */ List<Animator> getHideButtonsWhenUnfocusedAnimatorsForTablet(
int toolbarStartPaddingDifference) {
LocationBarTablet locationBarTablet = ((LocationBarTablet) mLocationBarLayout);
ArrayList<Animator> animators = new ArrayList<>();
Animator widthChangeAnimator =
ObjectAnimator.ofFloat(this, mWidthChangeFractionPropertyTablet, 1f);
widthChangeAnimator.setStartDelay(WIDTH_CHANGE_ANIMATION_DELAY_MS);
widthChangeAnimator.setDuration(WIDTH_CHANGE_ANIMATION_DURATION_MS);
widthChangeAnimator.setInterpolator(BakedBezierInterpolator.TRANSFORM_CURVE);
widthChangeAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
locationBarTablet.startAnimatingWidthChange(toolbarStartPaddingDifference);
}
@Override
public void onAnimationEnd(Animator animation) {
// Only reset values if the animation is ending because it's completely finished
// and not because it was canceled.
if (locationBarTablet.getWidthChangeFraction() == 1.f) {
locationBarTablet.finishAnimatingWidthChange();
locationBarTablet.resetValuesAfterAnimation();
setShouldShowButtonsWhenUnfocusedForTablet(false);
}
}
});
animators.add(widthChangeAnimator);
// When buttons show in the unfocused location bar, either the delete button or bookmark
// button will be showing. If the delete button is currently showing, the bookmark button
// should not fade out.
if (!locationBarTablet.isDeleteButtonVisible()) {
animators.add(createHideButtonAnimatorForTablet(
locationBarTablet.getBookmarkButtonForAnimation()));
}
if (shouldShowSaveOfflineButton() && locationBarTablet.isSaveOfflineButtonVisible()) {
animators.add(createHideButtonAnimatorForTablet(
locationBarTablet.getSaveOfflineButtonForAnimation()));
} else if (!(mUrlHasFocus && !locationBarTablet.isDeleteButtonVisible())) {
// If the save offline button isn't enabled, the microphone button always shows when
// buttons are shown in the unfocused location bar. When buttons are hidden in the
// unfocused location bar, the microphone shows if the location bar is focused and the
// delete button isn't showing. The microphone button should not be hidden if the
// url bar is currently focused and the delete button isn't showing.
animators.add(createHideButtonAnimatorForTablet(
locationBarTablet.getMicButtonForAnimation()));
}
return animators;
}
/**
* Changes the text on the url bar. The text update will be applied regardless of the current
* focus state (comparing to {@link LocationBarMediator#setUrl} which only applies text updates
* when not focused).
*
* @param urlBarData The contents of the URL bar, both for editing and displaying.
* @param scrollType Specifies how the text should be scrolled in the unfocused state.
* @param selectionState Specifies how the text should be selected in the focused state.
* @return Whether the URL was changed as a result of this call.
*/
/* package */ boolean setUrlBarText(UrlBarData urlBarData, @UrlBar.ScrollType int scrollType,
@SelectionState int selectionState) {
return mUrlCoordinator.setUrlBarData(urlBarData, scrollType, selectionState);
}
/**
* Clear any text in the URL bar.
* @return Whether this changed the existing text.
*/
/* package */ boolean setUrlBarTextEmpty() {
boolean textChanged = mUrlCoordinator.setUrlBarData(
UrlBarData.EMPTY, UrlBar.ScrollType.SCROLL_TO_BEGINNING, SelectionState.SELECT_ALL);
forceOnTextChanged();
return textChanged;
}
/* package */ void forceOnTextChanged() {
String textWithoutAutocomplete = mUrlCoordinator.getTextWithoutAutocomplete();
String textWithAutocomplete = mUrlCoordinator.getTextWithAutocomplete();
mAutocompleteCoordinator.onTextChanged(textWithoutAutocomplete, textWithAutocomplete);
}
// Private methods
private void setProfile(Profile profile) {
if (profile == null || !mNativeInitialized) return;
mAutocompleteCoordinator.setAutocompleteProfile(profile);
mOmniboxPrerender.initializeForProfile(profile);
mLocationBarLayout.setShowIconsWhenUrlFocused(
mSearchEngineLogoUtils.shouldShowSearchEngineLogo(profile.isOffTheRecord()));
}
private void focusCurrentTab() {
assert mLocationBarDataProvider != null;
if (mLocationBarDataProvider.hasTab()) {
View view = mLocationBarDataProvider.getTab().getView();
if (view != null) view.requestFocus();
}
}
@VisibleForTesting
/* package */ void updateAssistantVoiceSearchDrawableAndColors() {
AssistantVoiceSearchService assistantVoiceSearchService =
mAssistantVoiceSearchServiceSupplier.get();
if (assistantVoiceSearchService == null) return;
mLocationBarLayout.setMicButtonTint(assistantVoiceSearchService.getMicButtonColorStateList(
getPrimaryBackgroundColor(), mContext));
mLocationBarLayout.setMicButtonDrawable(
assistantVoiceSearchService.getCurrentMicDrawable());
}
/**
* Update visuals to use a correct light or dark color scheme depending on the primary color.
*/
@VisibleForTesting
/* package */ void updateUseDarkColors() {
// TODO(crbug.com/1114183): Unify light and dark color logic in chrome and make it clear
// whether the foreground or background color is dark.
final boolean useDarkColors =
!ColorUtils.shouldUseLightForegroundOnBackground(getPrimaryBackgroundColor());
mLocationBarLayout.setDeleteButtonTint(
ChromeColors.getPrimaryIconTint(mContext, !useDarkColors));
// If the URL changed colors and is not focused, update the URL to account for the new
// color scheme.
if (mUrlCoordinator.setUseDarkTextColors(useDarkColors) && !isUrlBarFocused()) {
updateUrl();
}
mStatusCoordinator.setUseDarkColors(useDarkColors);
if (mAutocompleteCoordinator != null) {
mAutocompleteCoordinator.updateVisualsForState(
useDarkColors, mLocationBarDataProvider.isIncognito());
}
}
/** Returns the primary color based on the url focus, and incognito state. */
private int getPrimaryBackgroundColor() {
// If the url bar is focused, the toolbar background color is the default color regardless
// of whether it is branded or not.
if (isUrlBarFocused()) {
return ChromeColors.getDefaultThemeColor(
mContext.getResources(), mLocationBarDataProvider.isIncognito());
} else {
return mLocationBarDataProvider.getPrimaryColor();
}
}
private void updateShouldAnimateIconChanges() {
boolean shouldAnimate =
mIsTablet ? isUrlBarFocused() : isUrlBarFocused() || mIsUrlFocusChangeInProgress;
mStatusCoordinator.setShouldAnimateIconChanges(shouldAnimate);
}
private void recordOmniboxFocusReason(@OmniboxFocusReason int reason) {
RecordHistogram.recordEnumeratedHistogram(
"Android.OmniboxFocusReason", reason, OmniboxFocusReason.NUM_ENTRIES);
}
private void updateMicButtonState() {
updateButtonVisibility();
}
private void updateLensButtonState() {
updateButtonVisibility();
}
/**
* Updates the display of the mic button.
*/
private void updateMicButtonVisibility() {
mLocationBarLayout.setMicButtonVisibility(shouldShowMicButton());
}
private void updateLensButtonVisibility() {
mLocationBarLayout.setLensButtonVisibility(shouldShowLensButton());
}
private void updateDeleteButtonVisibility() {
mLocationBarLayout.setDeleteButtonVisibility(shouldShowDeleteButton());
}
private void updateTabletButtonsVisibility() {
assert mIsTablet;
LocationBarTablet locationBarTablet = (LocationBarTablet) mLocationBarLayout;
boolean showBookmarkButton =
mShouldShowButtonsWhenUnfocused && shouldShowPageActionButtons();
locationBarTablet.setBookmarkButtonVisibility(showBookmarkButton);
boolean showSaveOfflineButton =
mShouldShowButtonsWhenUnfocused && shouldShowSaveOfflineButton();
locationBarTablet.setSaveOfflineButtonVisibility(
showSaveOfflineButton, isSaveOfflineButtonEnabled());
}
/**
* @return Whether the delete button should be shown.
*/
private boolean shouldShowDeleteButton() {
// Show the delete button at the end when the bar has focus and has some text.
boolean hasText = mUrlCoordinator != null
&& !TextUtils.isEmpty(mUrlCoordinator.getTextWithAutocomplete());
return hasText && (mUrlHasFocus || mIsUrlFocusChangeInProgress);
}
private boolean shouldShowMicButton() {
if (mIsTablet && mShouldShowButtonsWhenUnfocused) {
return mVoiceRecognitionHandler != null
&& mVoiceRecognitionHandler.isVoiceSearchEnabled() && mNativeInitialized
&& (mUrlHasFocus || mIsUrlFocusChangeInProgress);
} else {
boolean deleteButtonVisible = shouldShowDeleteButton();
return mVoiceRecognitionHandler != null
&& mVoiceRecognitionHandler.isVoiceSearchEnabled() && !deleteButtonVisible
&& (mUrlHasFocus || mIsUrlFocusChangeInProgress || mUrlFocusChangeFraction > 0f
|| mShouldShowMicButtonWhenUnfocused);
}
}
private boolean shouldShowLensButton() {
if (mIsTablet) {
// TODO(b/180967835): add logic to enable Lens for tablets.
return false;
} else if (mShouldShowButtonsWhenUnfocused) {
return isLensEnabled(LensEntryPoint.OMNIBOX) && mNativeInitialized
&& (mUrlHasFocus || mIsUrlFocusChangeInProgress);
} else {
boolean deleteButtonVisible = shouldShowDeleteButton();
return isLensEnabled(LensEntryPoint.OMNIBOX) && !deleteButtonVisible