File: tab_scrubber_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (698 lines) | stat: -rw-r--r-- 25,899 bytes parent folder | download | duplicates (5)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/ash/shell_delegate/tab_scrubber.h"

#include <memory>
#include <utility>

#include "ash/constants/ash_switches.h"
#include "ash/display/event_transformation_handler.h"
#include "ash/shell.h"
#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_enums.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/exo/shell_surface_util.h"
#include "components/exo/test/shell_surface_builder.h"
#include "components/exo/wm_helper.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/aura/window.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/wm/core/window_util.h"

namespace {

constexpr int kScrubbingGestureFingerCount = 3;

// Waits until the immersive mode reveal ends, and therefore the top view of
// the browser is no longer visible.
class ImmersiveRevealEndedWaiter : public ImmersiveModeController::Observer {
 public:
  explicit ImmersiveRevealEndedWaiter(
      ImmersiveModeController* immersive_controller)
      : immersive_controller_(immersive_controller) {
    immersive_controller_->AddObserver(this);
  }

  ImmersiveRevealEndedWaiter(const ImmersiveRevealEndedWaiter&) = delete;
  ImmersiveRevealEndedWaiter& operator=(const ImmersiveRevealEndedWaiter&) =
      delete;

  ~ImmersiveRevealEndedWaiter() override {
    if (immersive_controller_) {
      immersive_controller_->RemoveObserver(this);
    }
  }

  void Wait() {
    if (!immersive_controller_ || !immersive_controller_->IsRevealed()) {
      return;
    }

    base::RunLoop run_loop;
    quit_closure_ = run_loop.QuitClosure();
    run_loop.Run();
  }

 private:
  void MaybeQuitRunLoop() {
    if (!quit_closure_.is_null()) {
      std::move(quit_closure_).Run();
    }
  }

  // ImmersiveModeController::Observer:
  void OnImmersiveRevealEnded() override { MaybeQuitRunLoop(); }

  void OnImmersiveModeControllerDestroyed() override {
    MaybeQuitRunLoop();
    immersive_controller_->RemoveObserver(this);
    immersive_controller_ = nullptr;
  }

  raw_ptr<ImmersiveModeController> immersive_controller_;
  base::OnceClosure quit_closure_;
};

}  // namespace

namespace ash {

class TabScrubberTest : public InProcessBrowserTest,
                        public TabStripModelObserver {
 public:
  TabScrubberTest() = default;

  TabScrubberTest(const TabScrubberTest&) = delete;
  TabScrubberTest& operator=(const TabScrubberTest&) = delete;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(ash::switches::kNaturalScrollDefault);
  }

  void SetUpOnMainThread() override {
    TabScrubber::GetInstance()->use_default_activation_delay_ = false;
    // Disable external monitor scaling of coordinates.
    ash::Shell* shell = ash::Shell::Get();
    shell->event_transformation_handler()->set_transformation_mode(
        ash::EventTransformationHandler::TRANSFORM_NONE);

    wm_helper_ = std::make_unique<exo::WMHelper>();
  }

  void TearDownOnMainThread() override {
    wm_helper_.reset();

    browser()->tab_strip_model()->RemoveObserver(this);
  }

  TabStrip* GetTabStrip(Browser* browser) {
    aura::Window* window = browser->window()->GetNativeWindow();
    // This test depends on TabStrip impl.
    TabStrip* tab_strip =
        BrowserView::GetBrowserViewForNativeWindow(window)->tabstrip();
    DCHECK(tab_strip);
    return tab_strip;
  }

  int GetStartX(Browser* browser, int index, TabScrubber::Direction direction) {
    return TabScrubber::GetStartPoint(GetTabStrip(browser), index, direction)
        .x();
  }

  int GetTabCenter(Browser* browser, int index) {
    return GetTabStrip(browser)
        ->tab_at(index)
        ->GetMirroredBounds()
        .CenterPoint()
        .x();
  }

  // The simulated scroll event's offsets are calculated in the tests rather
  // than generated by the real event system. For the offsets calculation to be
  // correct in an RTL layout, we must invert the direction since it is
  // calculated here in the tests based on the indices and they're inverted in
  // RTL layouts:
  // Tab indices in an English layout : 0 - 1 - 2 - 3 - 4.
  // Tab indices in an Arabic layout  : 4 - 3 - 2 - 1 - 0.
  TabScrubber::Direction InvertDirectionIfNeeded(
      TabScrubber::Direction direction) {
    if (base::i18n::IsRTL()) {
      return direction == TabScrubber::LEFT ? TabScrubber::RIGHT
                                            : TabScrubber::LEFT;
    }

    return direction;
  }

  // Sends one scroll event synchronously without initial or final
  // fling events.
  void SendScrubEvent(Browser* browser, int index) {
    auto event_generator = CreateEventGenerator(browser);
    int active_index = browser->tab_strip_model()->active_index();
    TabScrubber::Direction direction =
        index < active_index ? TabScrubber::LEFT : TabScrubber::RIGHT;

    direction = InvertDirectionIfNeeded(direction);

    int offset = GetTabCenter(browser, index) -
                 GetStartX(browser, active_index, direction);
    ui::ScrollEvent scroll_event(ui::EventType::kScroll, gfx::Point(0, 0),
                                 ui::EventTimeForNow(), 0, offset, 0, offset, 0,
                                 kScrubbingGestureFingerCount);
    event_generator->Dispatch(&scroll_event);
  }

  enum ScrubType {
    EACH_TAB,
    SKIP_TABS,
    REPEAT_TABS,
  };

  // Sends asynchronous events and waits for tab at |index| to become
  // active.
  void Scrub(Browser* browser, int index, ScrubType scrub_type) {
    auto event_generator = CreateEventGenerator(browser);
    activation_order_.clear();
    int active_index = browser->tab_strip_model()->active_index();
    ASSERT_NE(index, active_index);
    ASSERT_TRUE(scrub_type != SKIP_TABS || ((index - active_index) % 2) == 0);
    TabScrubber::Direction direction;
    int increment;
    if (index < active_index) {
      direction = TabScrubber::LEFT;
      increment = -1;
    } else {
      direction = TabScrubber::RIGHT;
      increment = 1;
    }

    direction = InvertDirectionIfNeeded(direction);

    if (scrub_type == SKIP_TABS) {
      increment *= 2;
    }
    browser->tab_strip_model()->AddObserver(this);
    ScrollGenerator scroll_generator(event_generator.get());
    int last = GetStartX(browser, active_index, direction);
    for (int i = active_index + increment; i != (index + increment);
         i += increment) {
      int tab_center = GetTabCenter(browser, i);
      scroll_generator.GenerateScroll(tab_center - last);
      last = GetStartX(browser, i, direction);
      if (scrub_type == REPEAT_TABS) {
        scroll_generator.GenerateScroll(increment);
        last += increment;
      }
    }
    browser->tab_strip_model()->RemoveObserver(this);
  }

  // Sends events and waits for tab at |index| to become active
  // if it's different from the currently active tab.
  // If the active tab is expected to stay the same, send events
  // synchronously (as we don't have anything to wait for).
  void SendScrubSequence(Browser* browser, float x_offset, int index) {
    auto event_generator = CreateEventGenerator(browser);
    browser->tab_strip_model()->AddObserver(this);
    ScrollGenerator scroll_generator(event_generator.get());
    scroll_generator.GenerateScroll(x_offset);
    browser->tab_strip_model()->RemoveObserver(this);
  }

  // Sends alt-tab key press event to start the window cycle list.
  void StartCyclingWindows(Browser* browser) {
    auto event_generator = CreateEventGenerator(browser);
    // Views use VKEY_MENU for both left and right Alt keys.
    event_generator->PressKey(ui::VKEY_MENU, ui::EF_NONE);
    event_generator->PressKey(ui::KeyboardCode::VKEY_TAB, ui::EF_ALT_DOWN);
    event_generator->ReleaseKey(ui::KeyboardCode::VKEY_TAB, ui::EF_ALT_DOWN);
  }

  // Sends alt-tab key release event to start the window cycle list.
  void StopCyclingWindows(Browser* browser) {
    auto event_generator = CreateEventGenerator(browser);
    event_generator->ReleaseKey(ui::VKEY_MENU, ui::EF_NONE);
  }

  bool IsTabScrubberEnabled() {
    return TabScrubber::GetInstance()->GetEnabledForTesting();
  }

  void AddTabs(Browser* browser, int num_tabs) {
    TabStrip* tab_strip = GetTabStrip(browser);
    for (int i = 0; i < num_tabs; ++i) {
      AddBlankTabAndShow(browser);
    }
    ASSERT_EQ(num_tabs + 1, browser->tab_strip_model()->count());
    ASSERT_EQ(num_tabs, browser->tab_strip_model()->active_index());
    tab_strip->StopAnimating(true);
    ASSERT_FALSE(tab_strip->IsAnimating());
    // Perform any scheduled layouts so the tabstrip is in a steady state.
    BrowserView::GetBrowserViewForBrowser(browser)
        ->GetWidget()
        ->LayoutRootViewIfNecessary();
  }

  // TabStripModelObserver overrides.
  void OnTabStripModelChanged(
      TabStripModel* tab_strip_model,
      const TabStripModelChange& change,
      const TabStripSelectionChange& selection) override {
    if (tab_strip_model->empty() || !selection.active_tab_changed()) {
      return;
    }

    ASSERT_TRUE(selection.new_model.active().has_value());
    activation_order_.push_back(selection.new_model.active().value());
  }

  std::unique_ptr<ui::test::EventGenerator> CreateEventGenerator(
      Browser* browser) {
    aura::Window* window = browser->window()->GetNativeWindow();
    aura::Window* root = window->GetRootWindow();
    return std::make_unique<ui::test::EventGenerator>(root, window);
  }
  // History of tab activation. Scrub() resets it.
  std::vector<size_t> activation_order_;

 private:
  // Used to generate a sequence of scrolls. Starts with a cancel, is followed
  // by any number of scrolls and finally a fling-start. After every event this
  // forces the TabScrubber to complete any pending activation.
  class ScrollGenerator {
   public:
    explicit ScrollGenerator(ui::test::EventGenerator* event_generator)
        : event_generator_(event_generator) {
      ui::ScrollEvent fling_cancel(ui::EventType::kScrollFlingCancel,
                                   gfx::Point(), time_for_next_event_, 0, 0, 0,
                                   0, 0, kScrubbingGestureFingerCount);
      event_generator->Dispatch(&fling_cancel);
      if (TabScrubber::GetInstance()->IsActivationPending()) {
        TabScrubber::GetInstance()->FinishScrub(true);
      }
    }

    ScrollGenerator(const ScrollGenerator&) = delete;
    ScrollGenerator& operator=(const ScrollGenerator&) = delete;

    ~ScrollGenerator() {
      ui::ScrollEvent fling_start(ui::EventType::kScrollFlingStart,
                                  gfx::Point(), time_for_next_event_, 0,
                                  last_x_offset_, 0, last_x_offset_, 0,
                                  kScrubbingGestureFingerCount);
      event_generator_->Dispatch(&fling_start);
      if (TabScrubber::GetInstance()->IsActivationPending()) {
        TabScrubber::GetInstance()->FinishScrub(true);
      }
    }

    void GenerateScroll(int x_offset) {
      time_for_next_event_ += base::Milliseconds(100);
      ui::ScrollEvent scroll(ui::EventType::kScroll, gfx::Point(),
                             time_for_next_event_, 0, x_offset, 0, x_offset, 0,
                             kScrubbingGestureFingerCount);
      last_x_offset_ = x_offset;
      event_generator_->Dispatch(&scroll);
      if (TabScrubber::GetInstance()->IsActivationPending()) {
        TabScrubber::GetInstance()->FinishScrub(true);
      }
    }

    raw_ptr<ui::test::EventGenerator> event_generator_;
    base::TimeTicks time_for_next_event_ = ui::EventTimeForNow();
    int last_x_offset_ = 0;
  };

  std::unique_ptr<exo::WMHelper> wm_helper_;
};

// Swipe a single tab in each direction.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, Single) {
  AddTabs(browser(), 1);

  Scrub(browser(), 0, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Scrub(browser(), 1, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(1));
  EXPECT_EQ(1, browser()->tab_strip_model()->active_index());
}

// Swipe 4 tabs in each direction. Each of the tabs should become active.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, Multi) {
  AddTabs(browser(), 4);

  Scrub(browser(), 0, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(3, 2, 1, 0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Scrub(browser(), 4, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(1, 2, 3, 4));
  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());
}

IN_PROC_BROWSER_TEST_F(TabScrubberTest, MultiBrowser) {
  AddTabs(browser(), 1);
  Scrub(browser(), 0, EACH_TAB);
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Browser* browser2 = CreateBrowser(browser()->profile());
  browser2->window()->Activate();
  ASSERT_TRUE(browser2->window()->IsActive());
  ASSERT_FALSE(browser()->window()->IsActive());
  AddTabs(browser2, 1);

  Scrub(browser2, 0, EACH_TAB);
  EXPECT_EQ(0, browser2->tab_strip_model()->active_index());
}

// Tests that tab scrubbing works correctly for a full-screen browser.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, FullScreenBrowser) {
  // Initializes the position of mouse. Makes the mouse away from the tabstrip
  // to prevent any interference on this test.
  auto event_generator = CreateEventGenerator(browser());
  event_generator->MoveMouseTo(
      gfx::Point(0, browser()->window()->GetBounds().height()));
  AddTabs(browser(), 6);
  browser()->tab_strip_model()->ActivateTabAt(4);

  chrome::ToggleFullscreenMode(browser());
  BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
      browser()->window()->GetNativeWindow());
  ImmersiveModeController* immersive_controller =
      browser_view->immersive_mode_controller();
  EXPECT_TRUE(immersive_controller->IsEnabled());

  ImmersiveRevealEndedWaiter waiter(immersive_controller);
  waiter.Wait();

  EXPECT_FALSE(immersive_controller->IsRevealed());

  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());
  Scrub(browser(), 0, EACH_TAB);
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());
  EXPECT_THAT(activation_order_, testing::ElementsAre(3, 2, 1, 0));
}

// Swipe 4 tabs in each direction with an extra swipe within each. The same
// 4 tabs should become active.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, Repeated) {
  AddTabs(browser(), 4);

  Scrub(browser(), 0, REPEAT_TABS);
  EXPECT_THAT(activation_order_, testing::ElementsAre(3, 2, 1, 0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Scrub(browser(), 4, REPEAT_TABS);
  EXPECT_THAT(activation_order_, testing::ElementsAre(1, 2, 3, 4));
  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());
}

// Confirm that we get the last tab made active when we skip tabs.
// These tests have 5 total tabs. We will only received scroll events
// on tabs 0, 2 and 4.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, Skipped) {
  AddTabs(browser(), 4);

  Scrub(browser(), 0, SKIP_TABS);
  EXPECT_THAT(activation_order_, testing::ElementsAre(2, 0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Scrub(browser(), 4, SKIP_TABS);
  EXPECT_THAT(activation_order_, testing::ElementsAre(2, 4));
  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());
}

// Confirm that nothing happens when the swipe is small.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, NoChange) {
  AddTabs(browser(), 1);

  SendScrubSequence(browser(), -1, 1);
  EXPECT_EQ(1, browser()->tab_strip_model()->active_index());

  SendScrubSequence(browser(), 1, 1);
  EXPECT_EQ(1, browser()->tab_strip_model()->active_index());
}

// Confirm that very large swipes go to the beginning and and of the tabstrip.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, Bounds) {
  AddTabs(browser(), 1);

  SendScrubSequence(browser(), -10000, 0);
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  SendScrubSequence(browser(), 10000, 1);
  EXPECT_EQ(1, browser()->tab_strip_model()->active_index());
}

IN_PROC_BROWSER_TEST_F(TabScrubberTest, DeleteHighlighted) {
  AddTabs(browser(), 1);

  SendScrubEvent(browser(), 0);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->tab_strip_model()->CloseWebContentsAt(0,
                                                   TabCloseTypes::CLOSE_NONE);
  EXPECT_FALSE(TabScrubber::GetInstance()->IsActivationPending());
}

// Delete the currently highlighted tab. Make sure the TabScrubber is
// aware.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, DeleteBeforeHighlighted) {
  AddTabs(browser(), 2);

  SendScrubEvent(browser(), 1);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->tab_strip_model()->CloseWebContentsAt(0,
                                                   TabCloseTypes::CLOSE_NONE);
  EXPECT_EQ(0, TabScrubber::GetInstance()->highlighted_tab());
}

// Move the currently highlighted tab and confirm it gets tracked.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, MoveHighlighted) {
  AddTabs(browser(), 1);

  SendScrubEvent(browser(), 0);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->tab_strip_model()->SelectTabAt(0);
  browser()->tab_strip_model()->DeselectTabAt(1);
  browser()->tab_strip_model()->MoveSelectedTabsTo(1, std::nullopt);
  EXPECT_EQ(1, TabScrubber::GetInstance()->highlighted_tab());
}

// Move a tab to before the highlighted one. Make sure that the highlighted tab
// index is updated correctly.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, MoveBefore) {
  AddTabs(browser(), 2);

  SendScrubEvent(browser(), 1);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->tab_strip_model()->SelectTabAt(0);
  browser()->tab_strip_model()->SelectTabAt(2);
  browser()->tab_strip_model()->MoveSelectedTabsTo(2, std::nullopt);
  EXPECT_EQ(0, TabScrubber::GetInstance()->highlighted_tab());
}

// Move a tab to after the highlighted one. Make sure that the highlighted tab
// index is updated correctly.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, MoveAfter) {
  AddTabs(browser(), 2);

  SendScrubEvent(browser(), 1);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->tab_strip_model()->MoveSelectedTabsTo(0, std::nullopt);
  EXPECT_EQ(2, TabScrubber::GetInstance()->highlighted_tab());
}

// Close the browser while an activation is pending.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, CloseBrowser) {
  AddTabs(browser(), 1);

  SendScrubEvent(browser(), 0);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->window()->Close();
  EXPECT_FALSE(TabScrubber::GetInstance()->IsActivationPending());
}

// In an RTL layout, swipe 4 tabs in each direction. Each of the tabs should
// become active.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, RTLMulti) {
  base::i18n::SetICUDefaultLocale("ar");
  ASSERT_TRUE(base::i18n::IsRTL());

  AddTabs(browser(), 4);

  Scrub(browser(), 0, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(3, 2, 1, 0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Scrub(browser(), 4, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(1, 2, 3, 4));
  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());
}

// In an RTL layout, confirm that we get the last tab made active when we skip
// tabs. These tests have 5 total tabs. We will only received scroll events
// on tabs 0, 2 and 4.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, RTLSkipped) {
  base::i18n::SetICUDefaultLocale("ar");
  ASSERT_TRUE(base::i18n::IsRTL());

  AddTabs(browser(), 4);

  Scrub(browser(), 0, SKIP_TABS);
  EXPECT_THAT(activation_order_, testing::ElementsAre(2, 0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());

  Scrub(browser(), 4, SKIP_TABS);
  EXPECT_THAT(activation_order_, testing::ElementsAre(2, 4));
  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());
}

// In an RTL layout, move a tab to before the highlighted one. Make sure that
// the highlighted tab index is updated correctly.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, RTLMoveBefore) {
  base::i18n::SetICUDefaultLocale("ar");
  ASSERT_TRUE(base::i18n::IsRTL());

  AddTabs(browser(), 2);

  SendScrubEvent(browser(), 1);
  EXPECT_TRUE(TabScrubber::GetInstance()->IsActivationPending());
  browser()->tab_strip_model()->SelectTabAt(0);
  browser()->tab_strip_model()->SelectTabAt(2);
  browser()->tab_strip_model()->MoveSelectedTabsTo(2, std::nullopt);
  EXPECT_EQ(0, TabScrubber::GetInstance()->highlighted_tab());
}

// If the window cycle list is open, the tab scrubber should be disabled.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, DisabledIfWindowCycleListOpen) {
  AddTabs(browser(), 4);

  // Create a second browser, but don't make it active.
  Browser* browser2 = CreateBrowser(browser()->profile());
  browser()->window()->Activate();
  ASSERT_FALSE(browser2->window()->IsActive());
  ASSERT_TRUE(browser()->window()->IsActive());

  // Open window cycle list. It should be open now so tab scrubber should be
  // disabled.
  StartCyclingWindows(browser());
  EXPECT_FALSE(IsTabScrubberEnabled());
  Scrub(browser(), 0, EACH_TAB);
  EXPECT_EQ(0u, activation_order_.size());
  EXPECT_EQ(4, browser()->tab_strip_model()->active_index());

  // Stop cycling. Scrub should work again.
  StopCyclingWindows(browser());
  EXPECT_TRUE(IsTabScrubberEnabled());
  Scrub(browser(), 0, EACH_TAB);
  EXPECT_THAT(activation_order_, testing::ElementsAre(3, 2, 1, 0));
  EXPECT_EQ(0, browser()->tab_strip_model()->active_index());
}

IN_PROC_BROWSER_TEST_F(TabScrubberTest, VerticalAndHorizontalScroll) {
  auto event_generator = CreateEventGenerator(browser());
  constexpr int kOffset = 100;

  {
    // If y offset is larger than x offset, the event should be recognized as a
    // vertical scroll and should not begin scrubbing.
    ui::ScrollEvent vertical_scroll_event(
        ui::EventType::kScroll, gfx::Point(0, 0), ui::EventTimeForNow(), 0,
        /*x_offset=*/0, /*y_offset=*/kOffset,
        /*x_offset_ordinal_=*/0, /*y_offset=*/kOffset,
        kScrubbingGestureFingerCount);
    event_generator->Dispatch(&vertical_scroll_event);
    EXPECT_FALSE(vertical_scroll_event.handled());
  }

  {
    // If x offset is larger than y offset, the event should be recognized as a
    // horizontal scroll and should begin scrubbing.
    ui::ScrollEvent horizontal_scroll_event(
        ui::EventType::kScroll, gfx::Point(0, 0), ui::EventTimeForNow(), 0,
        /*x_offset=*/kOffset, /*y_offset=*/0,
        /*x_offset_ordinal_=*/kOffset, /*y_offset=*/0,
        kScrubbingGestureFingerCount);
    event_generator->Dispatch(&horizontal_scroll_event);
    EXPECT_TRUE(horizontal_scroll_event.handled());
  }

  {
    // Finish scrubbing by dispatching fling scroll event. For finishing the
    // event, it is not required to be horizontal scroll. This happens for
    // example when the user start scrubbing with a horizontal scroll and the
    // fingers go up at the end of the scroll.
    ui::ScrollEvent fling_scroll_event(
        ui::EventType::kScrollFlingStart, gfx::Point(0, 0),
        ui::EventTimeForNow(), 0,
        /*x_offset=*/0, /*y_offset=*/kOffset,
        /*x_offset_ordinal_=*/0, /*y_offset=*/kOffset, 0);
    event_generator->Dispatch(&fling_scroll_event);
    EXPECT_TRUE(fling_scroll_event.handled());
  }
}

// Check scroll events other than 3-fingers scroll are not handled by
// TabScrubber.
IN_PROC_BROWSER_TEST_F(TabScrubberTest, EventHandling) {
  auto event_generator = CreateEventGenerator(browser());
  constexpr int kOffset = 100;

  {
    // Begin scrubbing and mark the event as handled for 3-fingers scroll event.
    ui::ScrollEvent scroll_event_with_3_fingers(
        ui::EventType::kScroll, gfx::Point(0, 0), ui::EventTimeForNow(), 0,
        kOffset, 0, kOffset, 0, kScrubbingGestureFingerCount);
    event_generator->Dispatch(&scroll_event_with_3_fingers);
    EXPECT_TRUE(scroll_event_with_3_fingers.handled());
  }

  {
    // Fling scroll event which is called during the scrubbing should be
    // consumed here.
    ui::ScrollEvent fling_scroll_event(ui::EventType::kScrollFlingStart,
                                       gfx::Point(0, 0), ui::EventTimeForNow(),
                                       0, kOffset, 0, kOffset, 0, 0);
    event_generator->Dispatch(&fling_scroll_event);
    EXPECT_TRUE(fling_scroll_event.handled());
  }

  {
    // Fling scroll event should NOT be consumed here if the scrubbing is not
    // ongoing. Do NOT handle the event for this scenario.
    ui::ScrollEvent fling_scroll_event(ui::EventType::kScrollFlingStart,
                                       gfx::Point(0, 0), ui::EventTimeForNow(),
                                       0, kOffset, 0, kOffset, 0, 0);
    event_generator->Dispatch(&fling_scroll_event);
    EXPECT_FALSE(fling_scroll_event.handled());
  }

  {
    // Other scroll events should be not handled by TabScrubber.
    ui::ScrollEvent scroll_event_with_2_fingers(
        ui::EventType::kScroll, gfx::Point(0, 0), ui::EventTimeForNow(), 0,
        kOffset, 0, kOffset, 0,
        /*finger_count=*/2);
    event_generator->Dispatch(&scroll_event_with_2_fingers);
    EXPECT_FALSE(scroll_event_with_2_fingers.handled());
  }
}

}  // namespace ash