-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
TabListMediator.java
2060 lines (1857 loc) · 97.1 KB
/
TabListMediator.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 2019 The Chromium Authors
// 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.tasks.tab_management;
import static org.chromium.chrome.browser.tasks.tab_management.MessageCardViewProperties.MESSAGE_TYPE;
import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_ALPHA;
import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.CARD_TYPE;
import static org.chromium.chrome.browser.tasks.tab_management.TabListModel.CardProperties.ModelType.TAB;
import static org.chromium.chrome.browser.tasks.tab_management.TabProperties.CLOSE_BUTTON_DESCRIPTION_STRING;
import static org.chromium.chrome.browser.tasks.tab_management.TabProperties.TAB_ID;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Pair;
import android.util.Size;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnScrollListener;
import org.chromium.base.Callback;
import org.chromium.base.Log;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.preferences.ChromePreferenceKeys;
import org.chromium.chrome.browser.preferences.SharedPreferencesManager;
import org.chromium.chrome.browser.price_tracking.PriceTrackingFeatures;
import org.chromium.chrome.browser.price_tracking.PriceTrackingUtilities;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabCreationState;
import org.chromium.chrome.browser.tab.TabLaunchType;
import org.chromium.chrome.browser.tab.TabObserver;
import org.chromium.chrome.browser.tab.TabSelectionType;
import org.chromium.chrome.browser.tab.state.ShoppingPersistedTabData;
import org.chromium.chrome.browser.tabmodel.EmptyTabModelFilter;
import org.chromium.chrome.browser.tabmodel.TabList;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModelFilter;
import org.chromium.chrome.browser.tabmodel.TabModelObserver;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.tasks.pseudotab.PseudoTab;
import org.chromium.chrome.browser.tasks.tab_groups.EmptyTabGroupModelFilterObserver;
import org.chromium.chrome.browser.tasks.tab_groups.TabGroupModelFilter;
import org.chromium.chrome.browser.tasks.tab_groups.TabGroupTitleUtils;
import org.chromium.chrome.browser.tasks.tab_groups.TabGroupUtils;
import org.chromium.chrome.browser.tasks.tab_management.PriceMessageService.PriceTabData;
import org.chromium.chrome.browser.tasks.tab_management.TabListCoordinator.TabListMode;
import org.chromium.chrome.browser.tasks.tab_management.TabListFaviconProvider.TabFavicon;
import org.chromium.chrome.browser.tasks.tab_management.TabListFaviconProvider.TabFaviconFetcher;
import org.chromium.chrome.browser.tasks.tab_management.TabProperties.UiType;
import org.chromium.chrome.browser.tasks.tab_management.TabSwitcherMediator.PriceWelcomeMessageController;
import org.chromium.chrome.browser.tasks.tab_management.TabUiMetricsHelper.TabSelectionEditorActionMetricGroups;
import org.chromium.chrome.tab_ui.R;
import org.chromium.components.browser_ui.styles.SemanticColorUtils;
import org.chromium.components.browser_ui.widget.selectable_list.SelectionDelegate;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.feature_engagement.FeatureConstants;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.modelutil.ListObservable;
import org.chromium.ui.modelutil.ListObservable.ListObserver;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.modelutil.SimpleRecyclerViewAdapter;
import org.chromium.url.GURL;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Mediator for business logic for the tab grid. This class should be initialized with a list of
* tabs and a TabModel to observe for changes and should not have any logic around what the list
* signifies.
* TODO(yusufo): Move some of the logic here to a parent component to make the above true.
*/
class TabListMediator {
// Comparator to sort Tabs in descending order of the last shown time.
private static final Comparator<PseudoTab> LAST_SHOWN_COMPARATOR =
(a, b) -> (Long.compare(b.getTimestampMillis(), a.getTimestampMillis()));
// The |mVisible| relies on whether the tab list is null when the last time
// resetWithListOfTabs() was called, but not whether the RecyclerView is actually showing on the
// screen.
private boolean mVisible;
private boolean mShownIPH;
private Tab mTabToAddDelayed;
/**
* An interface to get the thumbnails to be shown inside the tab grid cards.
*/
public interface ThumbnailProvider {
/**
* @see TabContentManager#getTabThumbnailWithCallback
*/
void getTabThumbnailWithCallback(int tabId, Size thumbnailSize, Callback<Bitmap> callback,
boolean forceUpdate, boolean writeToCache, boolean isSelected);
}
/**
* An interface to handle requests about updating TabGridDialog.
*/
public interface TabGridDialogHandler {
/**
* This method updates the status of the ungroup bar in TabGridDialog.
*
* @param status The status in {@link TabGridDialogView.UngroupBarStatus} that the ungroup
* bar should be updated to.
*/
void updateUngroupBarStatus(@TabGridDialogView.UngroupBarStatus int status);
/**
* This method updates the content of the TabGridDialog.
*
* @param tabId The id of the {@link Tab} that is used to update TabGridDialog.
*/
void updateDialogContent(int tabId);
}
/**
* An interface to expose functionality needed to support reordering in grid layouts in
* accessibility mode.
*/
public interface TabGridAccessibilityHelper {
/**
* This method gets the possible actions for reordering a tab in grid layout.
*
* @param view The host view that triggers the accessibility action.
* @return The list of possible {@link AccessibilityAction}s for host view.
*/
List<AccessibilityAction> getPotentialActionsForView(View view);
/**
* This method gives the previous and target position of current reordering based on the
* host view and current action.
*
* @param view The host view that triggers the accessibility action.
* @param action The id of the action.
* @return {@link Pair} that contains previous and target position of this action.
*/
Pair<Integer, Integer> getPositionsOfReorderAction(View view, int action);
/**
* This method returns whether the given action is a type of the reordering actions.
*
* @param action The accessibility action.
* @return Whether the given action is a reordering action.
*/
boolean isReorderAction(int action);
}
/**
* Provides capability to asynchronously acquire {@link ShoppingPersistedTabData}
*/
static class ShoppingPersistedTabDataFetcher {
protected Tab mTab;
protected PriceWelcomeMessageController mPriceWelcomeMessageController;
/**
* @param tab {@link Tab} {@link ShoppingPersistedTabData} will be acquired for.
* @param priceWelcomeMessageController to show the price welcome message.
*/
ShoppingPersistedTabDataFetcher(
Tab tab, @Nullable PriceWelcomeMessageController priceWelcomeMessageController) {
mTab = tab;
mPriceWelcomeMessageController = priceWelcomeMessageController;
}
/**
* Asynchronously acquire {@link ShoppingPersistedTabData}
* @param callback {@link Callback} to pass {@link ShoppingPersistedTabData} back in
*/
public void fetch(Callback<ShoppingPersistedTabData> callback) {
ShoppingPersistedTabData.from(mTab, (res) -> {
callback.onResult(res);
maybeShowPriceWelcomeMessage(res);
});
}
@VisibleForTesting
void maybeShowPriceWelcomeMessage(
@Nullable ShoppingPersistedTabData shoppingPersistedTabData) {
// Avoid inserting message while RecyclerView is computing a layout.
new Handler().post(() -> {
if (!PriceTrackingUtilities.isPriceWelcomeMessageCardEnabled()
|| (mPriceWelcomeMessageController == null)
|| (shoppingPersistedTabData == null)
|| (shoppingPersistedTabData.getPriceDrop() == null)) {
return;
}
mPriceWelcomeMessageController.showPriceWelcomeMessage(
new PriceTabData(mTab.getId(), shoppingPersistedTabData.getPriceDrop()));
});
}
}
/**
* The object to set to {@link TabProperties#THUMBNAIL_FETCHER} for the TabGridViewBinder to
* obtain the thumbnail asynchronously.
*/
static class ThumbnailFetcher {
static Callback<Bitmap> sBitmapCallbackForTesting;
static int sFetchCountForTesting;
private ThumbnailProvider mThumbnailProvider;
private int mId;
private boolean mForceUpdate;
private boolean mWriteToCache;
ThumbnailFetcher(
ThumbnailProvider provider, int id, boolean forceUpdate, boolean writeToCache) {
mThumbnailProvider = provider;
mId = id;
mForceUpdate = forceUpdate;
mWriteToCache = writeToCache;
}
void fetch(Callback<Bitmap> callback, Size thumbnailSize, boolean isSelected) {
Callback<Bitmap> forking = (bitmap) -> {
if (sBitmapCallbackForTesting != null) sBitmapCallbackForTesting.onResult(bitmap);
callback.onResult(bitmap);
};
sFetchCountForTesting++;
mThumbnailProvider.getTabThumbnailWithCallback(
mId, thumbnailSize, forking, mForceUpdate, mWriteToCache, isSelected);
}
}
/**
* An interface to show IPH for a tab.
*/
public interface IphProvider { void showIPH(View anchor); }
private final IphProvider mIphProvider = new IphProvider() {
private static final int IPH_DELAY_MS = 1000;
@Override
public void showIPH(View anchor) {
if (mShownIPH) return;
mShownIPH = true;
new Handler().postDelayed(
()
-> TabGroupUtils.maybeShowIPH(
FeatureConstants.TAB_GROUPS_YOUR_TABS_ARE_TOGETHER_FEATURE,
anchor, null),
IPH_DELAY_MS);
}
};
/**
* An interface to get a SelectionDelegate that contains the selected items for a selectable
* tab list.
*/
public interface SelectionDelegateProvider { SelectionDelegate getSelectionDelegate(); }
/**
* An interface to get the onClickListener when clicking on a grid card.
*/
interface GridCardOnClickListenerProvider {
/**
* @return {@link TabActionListener} to open Tab Grid dialog.
* If the given {@link Tab} is not able to create group, return null;
*/
@Nullable
TabActionListener openTabGridDialog(@NonNull Tab tab);
/**
* Run additional actions on tab selection.
* @param tabId The ID of selected {@link Tab}.
* @param fromActionButton Whether it is called from the Action button on the card.
*/
void onTabSelecting(int tabId, boolean fromActionButton);
}
@IntDef({TabClosedFrom.TAB_STRIP, TabClosedFrom.GRID_TAB_SWITCHER,
TabClosedFrom.GRID_TAB_SWITCHER_GROUP})
@Retention(RetentionPolicy.SOURCE)
private @interface TabClosedFrom {
int TAB_STRIP = 0;
// int TAB_GRID_SHEET = 1; // Obsolete
int GRID_TAB_SWITCHER = 2;
int GRID_TAB_SWITCHER_GROUP = 3;
int NUM_ENTRIES = 4;
}
private static final String TAG = "TabListMediator";
private static Map<Integer, Integer> sTabClosedFromMapTabClosedFromMap = new HashMap<>();
private static Set<Integer> sViewedTabIds = new HashSet<>();
private final Context mContext;
private final TabListModel mModel;
private final @TabListMode int mMode;
private final TabModelSelector mTabModelSelector;
private final TabActionListener mTabClosedListener;
private final PseudoTab.TitleProvider mTitleProvider;
private final SelectionDelegateProvider mSelectionDelegateProvider;
private final GridCardOnClickListenerProvider mGridCardOnClickListenerProvider;
private final TabGridDialogHandler mTabGridDialogHandler;
private final TabListFaviconProvider mTabListFaviconProvider;
private final PriceWelcomeMessageController mPriceWelcomeMessageController;
private Size mDefaultGridCardSize;
private String mComponentName;
private ThumbnailProvider mThumbnailProvider;
private boolean mActionsOnAllRelatedTabs;
private ComponentCallbacks mComponentCallbacks;
private TabGridItemTouchHelperCallback mTabGridItemTouchHelperCallback;
private int mNextTabId = Tab.INVALID_TAB_ID;
private @UiType int mUiType;
private GridLayoutManager mGridLayoutManager;
// mRecyclerView and mOnScrollListener are null, unless the the price drop IPH or badge is
// enabled.
private @Nullable RecyclerView mRecyclerView;
private @Nullable OnScrollListener mOnScrollListener;
private final TabActionListener mTabSelectedListener = new TabActionListener() {
@Override
public void run(int tabId) {
if (mModel.indexFromId(tabId) == TabModel.INVALID_TAB_INDEX) return;
mNextTabId = tabId;
if (!mActionsOnAllRelatedTabs) {
Tab currentTab = mTabModelSelector.getCurrentTab();
Tab newlySelectedTab =
TabModelUtils.getTabById(mTabModelSelector.getCurrentModel(), tabId);
// We filtered the tab switching related metric for components that takes actions on
// all related tabs (e.g. GTS) because that component can switch to different
// TabModel before switching tabs, while this class only contains information for
// all tabs that are in the same TabModel, more specifically:
// * For Tabs.TabOffsetOfSwitch, we do not want to log anything if the user
// switched from normal to incognito or vice-versa.
// * For MobileTabSwitched, as compared to the VTS, we need to account for
// MobileTabReturnedToCurrentTab action. This action is defined as return to the
// same tab as before entering the component, and we don't have this information
// here.
recordUserSwitchedTab(currentTab, newlySelectedTab);
}
if (mGridCardOnClickListenerProvider != null) {
mGridCardOnClickListenerProvider.onTabSelecting(
tabId, true /* fromActiionButton */);
} else {
mTabModelSelector.getCurrentModel().setIndex(
TabModelUtils.getTabIndexById(mTabModelSelector.getCurrentModel(), tabId),
TabSelectionType.FROM_USER, false);
}
}
/**
* Records MobileTabSwitched for the component. Also, records Tabs.TabOffsetOfSwitch but
* only when fromTab and toTab are within the same group. This method only records UMA
* for components other than TabSwitcher.
*
* @param fromTab The previous selected tab.
* @param toTab The new selected tab.
*/
private void recordUserSwitchedTab(Tab fromTab, Tab toTab) {
int fromFilterIndex = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter()
.indexOf(fromTab);
int toFilterIndex = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter()
.indexOf(toTab);
RecordUserAction.record("MobileTabSwitched." + mComponentName);
if (fromFilterIndex != toFilterIndex) return;
int fromIndex = TabModelUtils.getTabIndexById(
mTabModelSelector.getCurrentModel(), fromTab.getId());
int toIndex = TabModelUtils.getTabIndexById(
mTabModelSelector.getCurrentModel(), toTab.getId());
RecordHistogram.recordSparseHistogram(
"Tabs.TabOffsetOfSwitch." + mComponentName, fromIndex - toIndex);
}
};
private final TabActionListener mSelectableTabOnClickListener = new TabActionListener() {
@Override
public void run(int tabId) {
int index = mModel.indexFromId(tabId);
if (index == TabModel.INVALID_TAB_INDEX) return;
boolean selected = mModel.get(index).model.get(TabProperties.IS_SELECTED);
if (selected) {
TabUiMetricsHelper.recordSelectionEditorActionMetrics(
TabSelectionEditorActionMetricGroups.UNSELECTED);
} else {
TabUiMetricsHelper.recordSelectionEditorActionMetrics(
TabSelectionEditorActionMetricGroups.SELECTED);
}
mModel.get(index).model.set(TabProperties.IS_SELECTED, !selected);
// Reset thumbnail to ensure the color of the blank tab slots is correct.
TabGroupModelFilter filter =
(TabGroupModelFilter) mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter();
Tab tab = mTabModelSelector.getTabById(tabId);
if (tab != null && filter.hasOtherRelatedTabs(tab)) {
mModel.get(index).model.set(TabProperties.THUMBNAIL_FETCHER,
new ThumbnailFetcher(mThumbnailProvider, tabId, false, false));
}
}
};
private final TabObserver mTabObserver = new EmptyTabObserver() {
@Override
public void onDidStartNavigationInPrimaryMainFrame(
Tab tab, NavigationHandle navigationHandle) {
// The URL of the tab and the navigation handle can match without it being a same
// document navigation if the tab had no renderer and needed to start a new one.
// See https://crbug.com/1359002.
if (navigationHandle.isSameDocument() || UrlUtilities.isNTPUrl(tab.getUrl())
|| tab.getUrl().equals(navigationHandle.getUrl())) {
return;
}
if (mModel.indexFromId(tab.getId()) == TabModel.INVALID_TAB_INDEX) return;
if (TabUiFeatureUtilities.isTabGroupsAndroidContinuationEnabled(mContext)) {
mModel.get(mModel.indexFromId(tab.getId()))
.model.set(TabProperties.FAVICON_FETCHER,
mTabListFaviconProvider.getDefaultFaviconFetcher(
tab.isIncognito()));
} else {
mModel.get(mModel.indexFromId(tab.getId()))
.model.set(TabProperties.FAVICON,
mTabListFaviconProvider.getDefaultFavicon(tab.isIncognito()));
}
}
@Override
public void onTitleUpdated(Tab updatedTab) {
int index = mModel.indexFromId(updatedTab.getId());
// TODO(crbug.com/1098100) The null check for tab here should be redundant once we have
// resolved the bug.
if (index == TabModel.INVALID_TAB_INDEX
|| mTabModelSelector.getTabById(updatedTab.getId()) == null) {
return;
}
mModel.get(index).model.set(
TabProperties.TITLE, getLatestTitleForTab(PseudoTab.fromTab(updatedTab)));
}
@Override
public void onFaviconUpdated(Tab updatedTab, Bitmap icon, GURL iconUrl) {
updateFaviconForTab(PseudoTab.fromTab(updatedTab), icon, iconUrl);
}
@Override
public void onUrlUpdated(Tab tab) {
if (!TabUiFeatureUtilities.isTabGroupsAndroidContinuationEnabled(mContext)) return;
int index = mModel.indexFromId(tab.getId());
if (index == TabModel.INVALID_TAB_INDEX && mActionsOnAllRelatedTabs) {
Tab currentGroupSelectedTab =
TabGroupUtils.getSelectedTabInGroupForTab(mTabModelSelector, tab);
if (currentGroupSelectedTab == null) return;
index = mModel.indexFromId(currentGroupSelectedTab.getId());
}
if (index == TabModel.INVALID_TAB_INDEX) return;
mModel.get(index).model.set(TabProperties.URL_DOMAIN, getDomainForTab(tab));
}
};
private final TabModelObserver mTabModelObserver;
private ListObserver<Void> mListObserver;
private TabGroupTitleEditor mTabGroupTitleEditor;
private TabGroupModelFilter.Observer mTabGroupObserver;
private View.AccessibilityDelegate mAccessibilityDelegate;
private int mLastSelectedTabListModelIndex = TabList.INVALID_TAB_INDEX;
/**
* Interface for implementing a {@link Runnable} that takes a tabId for a generic action.
*/
public interface TabActionListener { void run(int tabId); }
/**
* Construct the Mediator with the given Models and observing hooks from the given
* ChromeActivity.
* @param context The context used to get some configuration information.
* @param model The Model to keep state about a list of {@link Tab}s.
* @param mode The {@link TabListMode}
* @param tabModelSelector {@link TabModelSelector} that will provide and receive signals about
* the tabs concerned.
* @param thumbnailProvider {@link ThumbnailProvider} to provide screenshot related details.
* @param titleProvider {@link PseudoTab.TitleProvider} for a given tab's title to show.
* @param tabListFaviconProvider Provider for all favicon related drawables.
* @param actionOnRelatedTabs Whether tab-related actions should be operated on all related
* tabs.
* @param selectionDelegateProvider Provider for a {@link SelectionDelegate} that is used for
* a selectable list. It's null when selection is not possible.
* @param gridCardOnClickListenerProvider Provides the onClickListener for opening dialog when
* click on a grid card.
* @param dialogHandler A handler to handle requests about updating TabGridDialog.
* @param priceWelcomeMessageController A controller to show PriceWelcomeMessage.
* @param componentName This is a unique string to identify different components.
* @param uiType The type of UI this mediator should be building.
*/
public TabListMediator(Context context, TabListModel model, @TabListMode int mode,
TabModelSelector tabModelSelector, @Nullable ThumbnailProvider thumbnailProvider,
@Nullable PseudoTab.TitleProvider titleProvider,
TabListFaviconProvider tabListFaviconProvider, boolean actionOnRelatedTabs,
@Nullable SelectionDelegateProvider selectionDelegateProvider,
@Nullable GridCardOnClickListenerProvider gridCardOnClickListenerProvider,
@Nullable TabGridDialogHandler dialogHandler,
@Nullable PriceWelcomeMessageController priceWelcomeMessageController,
String componentName, @UiType int uiType) {
mContext = context;
mTabModelSelector = tabModelSelector;
mThumbnailProvider = thumbnailProvider;
mModel = model;
mMode = mode;
mTabListFaviconProvider = tabListFaviconProvider;
mComponentName = componentName;
mTitleProvider = titleProvider;
mSelectionDelegateProvider = selectionDelegateProvider;
mGridCardOnClickListenerProvider = gridCardOnClickListenerProvider;
mTabGridDialogHandler = dialogHandler;
mActionsOnAllRelatedTabs = actionOnRelatedTabs;
mUiType = uiType;
mPriceWelcomeMessageController = priceWelcomeMessageController;
mTabModelObserver = new TabModelObserver() {
@Override
public void didSelectTab(Tab tab, int type, int lastId) {
mNextTabId = Tab.INVALID_TAB_ID;
if (tab.getId() == lastId) return;
int oldIndex = mModel.indexFromId(lastId);
int newIndex = mModel.indexFromId(tab.getId());
if (newIndex == TabModel.INVALID_TAB_INDEX && mActionsOnAllRelatedTabs
&& type == TabSelectionType.FROM_UNDO) {
// If a tab in tab group does not exist in model and needs to be selected from
// undo, identify the related TabIds and determine newIndex based on if any of
// the related ids are present in model.
newIndex = getIndexForTabWithRelatedTabs(tab);
if (newIndex != Tab.INVALID_TAB_ID) {
model.updateTabListModelIdForGroup(tab, newIndex);
}
}
mLastSelectedTabListModelIndex = oldIndex;
if (mTabToAddDelayed != null && mTabToAddDelayed == tab) {
// If tab is being added later, it will be selected later.
return;
}
selectTab(oldIndex, newIndex);
}
@Override
public void tabClosureUndone(Tab tab) {
onTabAdded(tab, !mActionsOnAllRelatedTabs);
if (sTabClosedFromMapTabClosedFromMap.containsKey(tab.getId())) {
@TabClosedFrom
int from = sTabClosedFromMapTabClosedFromMap.get(tab.getId());
switch (from) {
case TabClosedFrom.TAB_STRIP:
RecordUserAction.record("TabStrip.UndoCloseTab");
break;
case TabClosedFrom.GRID_TAB_SWITCHER:
RecordUserAction.record("GridTabSwitch.UndoCloseTab");
break;
case TabClosedFrom.GRID_TAB_SWITCHER_GROUP:
RecordUserAction.record("GridTabSwitcher.UndoCloseTabGroup");
break;
default:
assert false
: "tabClosureUndone for tab that closed from an unknown UI";
}
sTabClosedFromMapTabClosedFromMap.remove(tab.getId());
}
// TODO(yuezhanggg): clean up updateTab() calls in this class.
if (mActionsOnAllRelatedTabs) {
TabModelFilter filter = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter();
int filterIndex = filter.indexOf(tab);
if (filterIndex == TabList.INVALID_TAB_INDEX
|| getRelatedTabsForId(tab.getId()).size() == 1
|| filterIndex >= mModel.size()) {
return;
}
Tab currentGroupSelectedTab = filter.getTabAt(filterIndex);
int tabListModelIndex = mModel.indexOfNthTabCard(filterIndex);
assert mModel.indexFromId(currentGroupSelectedTab.getId()) == tabListModelIndex;
updateTab(tabListModelIndex, PseudoTab.fromTab(currentGroupSelectedTab),
mModel.get(tabListModelIndex).model.get(TabProperties.IS_SELECTED),
false, false);
}
}
@Override
public void didAddTab(Tab tab, @TabLaunchType int type,
@TabCreationState int creationState, boolean markedForSelection) {
if (!mTabModelSelector.isTabStateInitialized()) return;
// Check if we need to delay tab addition to model.
boolean delayAdd = (type == TabLaunchType.FROM_TAB_SWITCHER_UI)
&& markedForSelection
&& TabSwitcherCoordinator.COMPONENT_NAME.equals(mComponentName);
if (delayAdd) {
mTabToAddDelayed = tab;
return;
}
onTabAdded(tab, !mActionsOnAllRelatedTabs);
if (type == TabLaunchType.FROM_RESTORE && mActionsOnAllRelatedTabs) {
// When tab is restored after restoring stage (e.g. exiting multi-window mode,
// switching between dark/light mode in incognito), we need to update related
// property models.
TabModelFilter filter = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter();
int filterIndex = filter.indexOf(tab);
if (filterIndex == TabList.INVALID_TAB_INDEX) return;
Tab currentGroupSelectedTab = filter.getTabAt(filterIndex);
// TabModel and TabListModel may be in the process of syncing up through
// restoring. Examples of this situation are switching between light/dark mode
// in incognito, exiting multi-window mode, etc.
int tabListModelIndex = mModel.indexOfNthTabCard(filterIndex);
if (mModel.indexFromId(currentGroupSelectedTab.getId()) != tabListModelIndex) {
return;
}
updateTab(tabListModelIndex, PseudoTab.fromTab(currentGroupSelectedTab),
mModel.get(tabListModelIndex).model.get(TabProperties.IS_SELECTED),
false, false);
}
}
@Override
public void willCloseTab(Tab tab, boolean animate, boolean didCloseAlone) {
if (mModel.indexFromId(tab.getId()) == TabModel.INVALID_TAB_INDEX) return;
tab.removeObserver(mTabObserver);
mModel.removeAt(mModel.indexFromId(tab.getId()));
}
@Override
public void didMoveTab(Tab tab, int newIndex, int curIndex) {
if (mTabModelSelector.getTabModelFilterProvider().getCurrentTabModelFilter()
instanceof TabGroupModelFilter) {
return;
}
onTabMoved(mModel.indexOfNthTabCard(newIndex), mModel.indexOfNthTabCard(curIndex));
}
@Override
public void tabRemoved(Tab tab) {
if (mModel.indexFromId(tab.getId()) == TabModel.INVALID_TAB_INDEX) return;
mModel.removeAt(mModel.indexFromId(tab.getId()));
}
};
// TODO(meiliang): follow up with unit tests to test the close signal is sent correctly with
// the recommendedNextTab.
mTabClosedListener = new TabActionListener() {
@Override
public void run(int tabId) {
// TODO(crbug.com/990698): Consider disabling all touch events during animation.
if (mModel.indexFromId(tabId) == TabModel.INVALID_TAB_INDEX) return;
Tab closingTab =
TabModelUtils.getTabById(mTabModelSelector.getCurrentModel(), tabId);
if (closingTab == null) return;
RecordUserAction.record("MobileTabClosed." + mComponentName);
if (mActionsOnAllRelatedTabs) {
List<Tab> related = getRelatedTabsForId(tabId);
if (related.size() > 1) {
onGroupClosedFrom(tabId);
mTabModelSelector.getCurrentModel().closeMultipleTabs(related, true);
return;
}
}
onTabClosedFrom(tabId, mComponentName);
Tab currentTab = mTabModelSelector.getCurrentTab();
Tab nextTab = currentTab == closingTab ? getNextTab(tabId) : null;
mTabModelSelector.getCurrentModel().closeTab(
closingTab, nextTab, false, false, true);
}
private Tab getNextTab(int closingTabId) {
int closingTabIndex = mModel.indexFromId(closingTabId);
if (closingTabIndex == TabModel.INVALID_TAB_INDEX) {
assert false;
return null;
}
int nextTabId = Tab.INVALID_TAB_ID;
if (mModel.size() > 1) {
int nextTabIndex = closingTabIndex == 0
? mModel.getTabIndexAfter(closingTabIndex)
: mModel.getTabIndexBefore(closingTabIndex);
nextTabId = nextTabIndex == TabModel.INVALID_TAB_INDEX
? Tab.INVALID_TAB_ID
: mModel.get(nextTabIndex).model.get(TabProperties.TAB_ID);
}
return TabModelUtils.getTabById(mTabModelSelector.getCurrentModel(), nextTabId);
}
};
mTabGridItemTouchHelperCallback = new TabGridItemTouchHelperCallback(context, mModel,
mTabModelSelector, mTabClosedListener, mTabGridDialogHandler, mComponentName,
mActionsOnAllRelatedTabs, mMode);
// Right now we need to update layout only if there is a price welcome message card in tab
// switcher.
if (mMode == TabListMode.GRID && mUiType != UiType.SELECTABLE
&& PriceTrackingFeatures.isPriceTrackingEnabled()) {
mListObserver = new ListObserver<Void>() {
@Override
public void onItemRangeInserted(ListObservable source, int index, int count) {
updateLayout();
}
@Override
public void onItemRangeRemoved(ListObservable source, int index, int count) {
updateLayout();
}
@Override
public void onItemRangeChanged(
ListObservable<Void> source, int index, int count, @Nullable Void payload) {
updateLayout();
}
@Override
public void onItemMoved(ListObservable source, int curIndex, int newIndex) {
updateLayout();
}
};
mModel.addObserver(mListObserver);
}
}
/**
* @param onLongPressTabItemEventListener to handle long press events on tabs.
*/
public void setOnLongPressTabItemEventListener(
@Nullable TabGridItemTouchHelperCallback
.OnLongPressTabItemEventListener onLongPressTabItemEventListener) {
mTabGridItemTouchHelperCallback.setOnLongPressTabItemEventListener(
onLongPressTabItemEventListener);
}
/**
* @param size The default size to use for any new Tab cards.
*/
void setDefaultGridCardSize(Size size) {
mDefaultGridCardSize = size;
}
/**
* @return The default size to use for any tab cards.
*/
Size getDefaultGridCardSize() {
return mDefaultGridCardSize;
}
private void selectTab(int oldIndex, int newIndex) {
if (oldIndex != TabModel.INVALID_TAB_INDEX) {
int lastId = mModel.get(oldIndex).model.get(TAB_ID);
mModel.get(oldIndex).model.set(TabProperties.IS_SELECTED, false);
if (mActionsOnAllRelatedTabs && mThumbnailProvider != null && mVisible) {
mModel.get(oldIndex).model.set(TabProperties.THUMBNAIL_FETCHER,
new ThumbnailFetcher(mThumbnailProvider, lastId, true, false));
}
}
if (newIndex != TabModel.INVALID_TAB_INDEX) {
int newId = mModel.get(newIndex).model.get(TAB_ID);
mModel.get(newIndex).model.set(TabProperties.IS_SELECTED, true);
if (mThumbnailProvider != null && mVisible) {
mModel.get(newIndex).model.set(TabProperties.THUMBNAIL_FETCHER,
new ThumbnailFetcher(mThumbnailProvider, newId, true, false));
}
}
}
public void initWithNative() {
mTabListFaviconProvider.initWithNative(
mTabModelSelector.getModel(/*isIncognito=*/false).getProfile());
mTabModelSelector.getTabModelFilterProvider().addTabModelFilterObserver(mTabModelObserver);
if (mTabModelSelector.getTabModelFilterProvider().getCurrentTabModelFilter()
instanceof TabGroupModelFilter) {
mTabGroupObserver = new EmptyTabGroupModelFilterObserver() {
@Override
public void didMoveWithinGroup(
Tab movedTab, int tabModelOldIndex, int tabModelNewIndex) {
if (!mVisible || tabModelNewIndex == tabModelOldIndex) return;
TabModel tabModel = mTabModelSelector.getCurrentModel();
// For the tab switcher update the tab card correctly.
if (mActionsOnAllRelatedTabs && mThumbnailProvider != null
&& !isShowingTabsInMRUOrder()) {
int indexInModel = getIndexForTabWithRelatedTabs(movedTab);
if (indexInModel == TabModel.INVALID_TAB_INDEX) return;
TabModelFilter filter = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter();
Tab lastShownTab = filter.getTabAt(filter.indexOf(movedTab));
mModel.get(indexInModel)
.model.set(TabProperties.THUMBNAIL_FETCHER,
new ThumbnailFetcher(mThumbnailProvider,
lastShownTab.getId(), true, false));
return;
}
// For the grid dialog maintain order.
int curPosition = mModel.indexFromId(movedTab.getId());
if (!isValidMovePosition(curPosition)) return;
Tab destinationTab = tabModel.getTabAt(tabModelNewIndex > tabModelOldIndex
? tabModelNewIndex - 1
: tabModelNewIndex + 1);
int newPosition = mModel.indexFromId(destinationTab.getId());
if (!isValidMovePosition(newPosition)) return;
mModel.move(curPosition, newPosition);
}
@Override
public void didMoveTabOutOfGroup(Tab movedTab, int prevFilterIndex) {
if (!mVisible) return;
assert !(mActionsOnAllRelatedTabs && mTabGridDialogHandler != null);
TabGroupModelFilter filter =
(TabGroupModelFilter) mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter();
Tab groupTab = filter.getTabAt(prevFilterIndex);
boolean isUngroupingLastTabInGroup = groupTab.getId() == movedTab.getId();
if (mActionsOnAllRelatedTabs) {
if (isUngroupingLastTabInGroup) return;
Tab currentSelectedTab = mTabModelSelector.getCurrentTab();
if (isShowingTabsInMRUOrder()) {
int groupTabIndex = mModel.indexFromId(groupTab.getId());
if (groupTabIndex == TabModel.INVALID_TAB_INDEX) {
// It is possible that the movedTab is the Tab for its group in the
// model.
groupTabIndex = mModel.indexFromId(movedTab.getId());
}
if (!isValidMovePosition(groupTabIndex)) return;
boolean isSelected = currentSelectedTab.getId() == groupTab.getId();
// We may need to adjust the group's index after removing the movedTab
// from the group.
int newGroupTabIndexMRU =
mModel.getNewPositionInMruOrderList(groupTab.getId());
updateTab(groupTabIndex, PseudoTab.fromTab(groupTab), isSelected, true,
false);
if (groupTabIndex != newGroupTabIndexMRU) {
// The move API will first remove the item at groupTabIndex. Thus,
// we need to decrease newGroupTabIndexMRU if an item has been
// removed before it.
mModel.move(groupTabIndex,
groupTabIndex < newGroupTabIndexMRU
? newGroupTabIndexMRU - 1
: newGroupTabIndexMRU);
}
int modelIndex = mModel.getNewPositionInMruOrderList(movedTab.getId());
addTabInfoToModel(PseudoTab.fromTab(movedTab), modelIndex,
currentSelectedTab.getId() == movedTab.getId());
} else {
// Only add a tab to the model if it represents a new card (new group or
// new singular tab). However, always update the previous group to clean
// up old state. The addition of the new tab to an existing group is
// handled in didMergeTabToGroup().
if (!filter.hasOtherRelatedTabs(movedTab)) {
int filterIndex = filter.indexOf(movedTab);
addTabInfoToModel(PseudoTab.fromTab(movedTab),
mModel.indexOfNthTabCard(filterIndex),
currentSelectedTab.getId() == movedTab.getId());
}
boolean isSelected =
mTabModelSelector.getCurrentTabId() == groupTab.getId();
updateTab(mModel.indexOfNthTabCard(prevFilterIndex),
PseudoTab.fromTab(groupTab), isSelected, true, false);
}
} else {
int curTabListModelIndex = mModel.indexFromId(movedTab.getId());
if (!isValidMovePosition(curTabListModelIndex)) return;
mModel.removeAt(curTabListModelIndex);
if (mTabGridDialogHandler != null) {
mTabGridDialogHandler.updateDialogContent(isUngroupingLastTabInGroup
? Tab.INVALID_TAB_ID
: filter.getTabAt(prevFilterIndex).getId());
}
}
}
@Override
public void didMergeTabToGroup(Tab movedTab, int selectedTabIdInGroup) {
if (!mVisible || !mActionsOnAllRelatedTabs) return;
// When merging Tab 1 to Tab 2 as a new group, or merging Tab 1 to an existing
// group 1, we can always find the current indexes of 1) Tab 1 and 2) Tab 2 or
// group 1 in the model. The method getIndexesForMergeToGroup() returns these
// two ids by using Tab 1's related Tabs, which have been updated in TabModel.
List<Tab> relatedTabs = getRelatedTabsForId(movedTab.getId());
Pair<Integer, Integer> positions = mModel.getIndexesForMergeToGroup(
mTabModelSelector.getCurrentModel(), relatedTabs);
int srcIndex = positions.second;
int desIndex = positions.first;
// If only the desIndex is valid then the movedTab was already part of another
// group and is not present in the model. This happens only during an undo.
// Refresh just the desIndex tab card in the model. The removal of the movedTab
// from its previous group was already handled by didMoveTabOutOfGroup.
if (desIndex != TabModel.INVALID_TAB_INDEX
&& srcIndex == TabModel.INVALID_TAB_INDEX) {
boolean isSelected = false;
for (Tab tab : relatedTabs) {
isSelected |= tab == mTabModelSelector.getCurrentTab();
}
updateTab(desIndex,
PseudoTab.fromTab(mTabModelSelector.getTabById(
mModel.get(desIndex).model.get(TabProperties.TAB_ID))),
isSelected, false, false);
return;
}
if (!isValidMovePosition(srcIndex) || !isValidMovePosition(desIndex)) return;
Tab newSelectedTabInMergedGroup = null;
boolean isMRU = isShowingTabsInMRUOrder();
if (isMRU) {
// We need to choose the Tab that represents the new group. It should be the
// last selected tab for the new formed group.
Tab oldSelectedTabInMergedGroup = mTabModelSelector.getTabById(
mModel.get(desIndex).model.get(TabProperties.TAB_ID));
int mergedGroupIndex = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter()
.indexOf(oldSelectedTabInMergedGroup);
newSelectedTabInMergedGroup = mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter()
.getTabAt(mergedGroupIndex);
}
mModel.removeAt(srcIndex);
if (getRelatedTabsForId(movedTab.getId()).size() == 2) {
// When users use drop-to-merge to create a group.
RecordUserAction.record("TabGroup.Created.DropToMerge");
} else {
RecordUserAction.record("TabGrid.Drag.DropToMerge");
}
desIndex = srcIndex > desIndex ? desIndex : mModel.getTabIndexBefore(desIndex);
if (!isMRU) {
newSelectedTabInMergedGroup =
mTabModelSelector.getTabModelFilterProvider()
.getCurrentTabModelFilter()
.getTabAt(mModel.getTabCardCountsBefore(desIndex));
}
boolean isSelected =
mTabModelSelector.getCurrentTab() == newSelectedTabInMergedGroup;
updateTab(desIndex, PseudoTab.fromTab(newSelectedTabInMergedGroup), isSelected,
true, false);
if (isSelected && isMRU && desIndex != 0) {
// In MRU order, always moves the new group which contains the current
// selected Tab to the position 0.
mModel.move(desIndex, 0);
}
}