summaryrefslogtreecommitdiffstats
path: root/chrome/browser/gtk/tabs/tab_strip_gtk.cc
blob: c9b12e3ce70c2581dc41b86a57c310375872a6d0 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
// Copyright (c) 2009 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.

#include "chrome/browser/gtk/tabs/tab_strip_gtk.h"

#include "base/gfx/gtk_util.h"
#include "base/gfx/point.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/tabs/tab_button_gtk.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/gfx/chrome_canvas.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/common/slide_animation.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

namespace {

const int kDefaultAnimationDurationMs = 100;
const int kResizeLayoutAnimationDurationMs = 166;
const int kReorderAnimationDurationMs = 166;
const int kAnimateToBoundsDurationMs = 150;

const int kNewTabButtonHOffset = -5;
const int kNewTabButtonVOffset = 5;

const int kHorizontalMoveThreshold = 16;  // pixels

// The horizontal offset from one tab to the next,
// which results in overlapping tabs.
const int kTabHOffset = -16;

SkBitmap* background = NULL;

// The targets available for drag n' drop.
GtkTargetEntry target_table[] = {
  { const_cast<char*>("application/x-tabstrip-tab"), GTK_TARGET_SAME_APP, 0 }
};

inline int Round(double x) {
  return static_cast<int>(x + 0.5);
}

bool IsButtonPressed(guint state) {
  return (state & GDK_BUTTON1_MASK);
}

// widget->allocation is not guaranteed to be set.  After window creation,
// we pick up the normal bounds by connecting to the configure-event signal.
gfx::Rect GetInitialWidgetBounds(GtkWidget* widget) {
  GtkRequisition request;
  gtk_widget_size_request(widget, &request);
  return gfx::Rect(0, 0, request.width, request.height);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
//
// TabAnimation
//
//  A base class for all TabStrip animations.
//
class TabStripGtk::TabAnimation : public AnimationDelegate {
 public:
  friend class TabStripGtk;

  // Possible types of animation.
  enum Type {
    INSERT,
    REMOVE,
    MOVE,
    RESIZE,
    SNAP
  };

  TabAnimation(TabStripGtk* tabstrip, Type type)
      : tabstrip_(tabstrip),
        animation_(this),
        start_selected_width_(0),
        start_unselected_width_(0),
        end_selected_width_(0),
        end_unselected_width_(0),
        layout_on_completion_(false),
        type_(type) {
  }
  virtual ~TabAnimation() {}

  Type type() const { return type_; }

  void Start() {
    animation_.SetSlideDuration(GetDuration());
    animation_.SetTweenType(SlideAnimation::EASE_OUT);
    if (!animation_.IsShowing()) {
      animation_.Reset();
      animation_.Show();
    }
  }

  void Stop() {
    animation_.Stop();
  }

  void set_layout_on_completion(bool layout_on_completion) {
    layout_on_completion_ = layout_on_completion;
  }

  // Retrieves the width for the Tab at the specified index if an animation is
  // active.
  static double GetCurrentTabWidth(TabStripGtk* tabstrip,
                                   TabStripGtk::TabAnimation* animation,
                                   int index) {
    double unselected, selected;
    tabstrip->GetCurrentTabWidths(&unselected, &selected);
    TabGtk* tab = tabstrip->GetTabAt(index);
    double tab_width = tab->IsSelected() ? selected : unselected;

    if (animation) {
      double specified_tab_width = animation->GetWidthForTab(index);
      if (specified_tab_width != -1)
        tab_width = specified_tab_width;
    }

    return tab_width;
  }

  // Overridden from AnimationDelegate:
  virtual void AnimationProgressed(const Animation* animation) {
    tabstrip_->AnimationLayout(end_unselected_width_);
  }

  virtual void AnimationEnded(const Animation* animation) {
    tabstrip_->FinishAnimation(this, layout_on_completion_);
    // TODO(jhawkins): Remove this once each tab is its own widget.
    SimulateMouseMotion();
    // This object is destroyed now, so we can't do anything else after this.
  }

  virtual void AnimationCanceled(const Animation* animation) {
    AnimationEnded(animation);
  }

 protected:
  // Returns the duration of the animation.
  virtual int GetDuration() const {
    return kDefaultAnimationDurationMs;
  }

  // Subclasses override to return the width of the Tab at the specified index
  // at the current animation frame. -1 indicates the default width should be
  // used for the Tab.
  virtual double GetWidthForTab(int index) const {
    return -1;  // Use default.
  }

  // Figure out the desired start and end widths for the specified pre- and
  // post- animation tab counts.
  void GenerateStartAndEndWidths(int start_tab_count, int end_tab_count) {
    tabstrip_->GetDesiredTabWidths(start_tab_count, &start_unselected_width_,
                                   &start_selected_width_);
    double standard_tab_width =
        static_cast<double>(TabRendererGtk::GetStandardSize().width());

    if ((end_tab_count - start_tab_count) > 0 &&
        start_unselected_width_ < standard_tab_width) {
      double minimum_tab_width = static_cast<double>(
          TabRendererGtk::GetMinimumUnselectedSize().width());
      start_unselected_width_ -= minimum_tab_width / start_tab_count;
    }

    tabstrip_->GenerateIdealBounds();
    tabstrip_->GetDesiredTabWidths(end_tab_count,
                                   &end_unselected_width_,
                                   &end_selected_width_);
  }

  TabStripGtk* tabstrip_;
  SlideAnimation animation_;

  double start_selected_width_;
  double start_unselected_width_;
  double end_selected_width_;
  double end_unselected_width_;

 private:
  // When the animation completes, we send the Container a message to simulate
  // a mouse moved event at the current mouse position. This tickles the Tab
  // the mouse is currently over to show the "hot" state of the close button, or
  // resets the hover index if it's now stale.
  void SimulateMouseMotion() {
    // Get default display and screen.
    GdkDisplay* display = gdk_display_get_default();
    GdkScreen* screen = gdk_display_get_default_screen(display);

    // Get cursor position.
    int x, y;
    gdk_display_get_pointer(display, NULL, &x, &y, NULL);

    // Reset cursor position.
    gdk_display_warp_pointer(display, screen, x, y);
  }

  // True if a complete re-layout is required upon completion of the animation.
  // Subclasses set this if they don't perform a complete layout
  // themselves and canceling the animation may leave the strip in an
  // inconsistent state.
  bool layout_on_completion_;

  const Type type_;

  DISALLOW_COPY_AND_ASSIGN(TabAnimation);
};

////////////////////////////////////////////////////////////////////////////////

// Handles insertion of a Tab at |index|.
class InsertTabAnimation : public TabStripGtk::TabAnimation {
 public:
  explicit InsertTabAnimation(TabStripGtk* tabstrip, int index)
      : TabAnimation(tabstrip, INSERT),
        index_(index) {
    int tab_count = tabstrip->GetTabCount();
    GenerateStartAndEndWidths(tab_count - 1, tab_count);
  }
  virtual ~InsertTabAnimation() {}

 protected:
  // Overridden from TabStripGtk::TabAnimation:
  virtual double GetWidthForTab(int index) const {
    if (index == index_) {
      bool is_selected = tabstrip_->model()->selected_index() == index;
      double target_width =
          is_selected ? end_unselected_width_ : end_selected_width_;
      double start_width =
          is_selected ? TabGtk::GetMinimumSelectedSize().width() :
                        TabGtk::GetMinimumUnselectedSize().width();

      double delta = target_width - start_width;
      if (delta > 0)
        return start_width + (delta * animation_.GetCurrentValue());

      return start_width;
    }

    if (tabstrip_->GetTabAt(index)->IsSelected()) {
      double delta = end_selected_width_ - start_selected_width_;
      return start_selected_width_ + (delta * animation_.GetCurrentValue());
    }

    double delta = end_unselected_width_ - start_unselected_width_;
    return start_unselected_width_ + (delta * animation_.GetCurrentValue());
  }

 private:
  int index_;

  DISALLOW_COPY_AND_ASSIGN(InsertTabAnimation);
};

////////////////////////////////////////////////////////////////////////////////

// Handles removal of a Tab from |index|
class RemoveTabAnimation : public TabStripGtk::TabAnimation {
 public:
  RemoveTabAnimation(TabStripGtk* tabstrip, int index, TabContents* contents)
      : TabAnimation(tabstrip, REMOVE),
        index_(index) {
    int tab_count = tabstrip->GetTabCount();
    GenerateStartAndEndWidths(tab_count, tab_count - 1);
  }

  virtual ~RemoveTabAnimation() {}

  // Returns the index of the tab being removed.
  int index() const { return index_; }

 protected:
  // Overridden from TabStripGtk::TabAnimation:
  virtual double GetWidthForTab(int index) const {
    TabGtk* tab = tabstrip_->GetTabAt(index);

    if (index == index_) {
      // The tab(s) being removed are gradually shrunken depending on the state
      // of the animation.
      // Removed animated Tabs are never selected.
      double start_width = start_unselected_width_;
      // Make sure target_width is at least abs(kTabHOffset), otherwise if
      // less than kTabHOffset during layout tabs get negatively offset.
      double target_width =
          std::max(abs(kTabHOffset),
                   TabGtk::GetMinimumUnselectedSize().width() + kTabHOffset);
      double delta = start_width - target_width;
      return start_width - (delta * animation_.GetCurrentValue());
    }

    if (tabstrip_->available_width_for_tabs_ != -1 &&
        index_ != tabstrip_->GetTabCount() - 1) {
      return TabStripGtk::TabAnimation::GetWidthForTab(index);
    }

    // All other tabs are sized according to the start/end widths specified at
    // the start of the animation.
    if (tab->IsSelected()) {
      double delta = end_selected_width_ - start_selected_width_;
      return start_selected_width_ + (delta * animation_.GetCurrentValue());
    }

    double delta = end_unselected_width_ - start_unselected_width_;
    return start_unselected_width_ + (delta * animation_.GetCurrentValue());
  }

  virtual void AnimationEnded(const Animation* animation) {
    tabstrip_->RemoveTabAt(index_);
    TabStripGtk::TabAnimation::AnimationEnded(animation);
  }

 private:
  int index_;

  DISALLOW_COPY_AND_ASSIGN(RemoveTabAnimation);
};

////////////////////////////////////////////////////////////////////////////////

// Handles the movement of a Tab from one position to another.
class MoveTabAnimation : public TabStripGtk::TabAnimation {
 public:
  MoveTabAnimation(TabStripGtk* tabstrip, int tab_a_index, int tab_b_index)
      : TabAnimation(tabstrip, MOVE),
        start_tab_a_bounds_(tabstrip_->GetIdealBounds(tab_b_index)),
        start_tab_b_bounds_(tabstrip_->GetIdealBounds(tab_a_index)) {
    tab_a_ = tabstrip_->GetTabAt(tab_a_index);
    tab_b_ = tabstrip_->GetTabAt(tab_b_index);

    // Since we don't do a full TabStrip re-layout, we need to force a full
    // layout upon completion since we're not guaranteed to be in a good state
    // if for example the animation is canceled.
    set_layout_on_completion(true);
  }
  virtual ~MoveTabAnimation() {}

  // Overridden from AnimationDelegate:
  virtual void AnimationProgressed(const Animation* animation) {
    // Position Tab A
    double distance = start_tab_b_bounds_.x() - start_tab_a_bounds_.x();
    double delta = distance * animation_.GetCurrentValue();
    double new_x = start_tab_a_bounds_.x() + delta;
    gfx::Rect bounds(Round(new_x), tab_a_->y(), tab_a_->width(),
        tab_a_->height());
    tab_a_->SetBounds(bounds);

    // Position Tab B
    distance = start_tab_a_bounds_.x() - start_tab_b_bounds_.x();
    delta = distance * animation_.GetCurrentValue();
    new_x = start_tab_b_bounds_.x() + delta;
    bounds = gfx::Rect(Round(new_x), tab_b_->y(), tab_b_->width(),
        tab_b_->height());
    tab_b_->SetBounds(bounds);
  }

 protected:
  // Overridden from TabStrip::TabAnimation:
  virtual int GetDuration() const { return kReorderAnimationDurationMs; }

 private:
  // The two tabs being exchanged.
  TabGtk* tab_a_;
  TabGtk* tab_b_;

  // ...and their bounds.
  gfx::Rect start_tab_a_bounds_;
  gfx::Rect start_tab_b_bounds_;

  DISALLOW_COPY_AND_ASSIGN(MoveTabAnimation);
};

////////////////////////////////////////////////////////////////////////////////

// Handles the animated resize layout of the entire TabStrip from one width
// to another.
class ResizeLayoutAnimation : public TabStripGtk::TabAnimation {
 public:
  explicit ResizeLayoutAnimation(TabStripGtk* tabstrip)
      : TabAnimation(tabstrip, RESIZE) {
    int tab_count = tabstrip->GetTabCount();
    GenerateStartAndEndWidths(tab_count, tab_count);
    InitStartState();
  }
  virtual ~ResizeLayoutAnimation() {}

  // Overridden from AnimationDelegate:
  virtual void AnimationEnded(const Animation* animation) {
    tabstrip_->resize_layout_scheduled_ = false;
    TabStripGtk::TabAnimation::AnimationEnded(animation);
  }

 protected:
  // Overridden from TabStripGtk::TabAnimation:
  virtual int GetDuration() const {
    return kResizeLayoutAnimationDurationMs;
  }

  virtual double GetWidthForTab(int index) const {
    if (tabstrip_->GetTabAt(index)->IsSelected()) {
      double delta = end_selected_width_ - start_selected_width_;
      return start_selected_width_ + (delta * animation_.GetCurrentValue());
    }

    double delta = end_unselected_width_ - start_unselected_width_;
    return start_unselected_width_ + (delta * animation_.GetCurrentValue());
  }

 private:
  // We need to start from the current widths of the Tabs as they were last
  // laid out, _not_ the last known good state, which is what'll be done if we
  // don't measure the Tab sizes here and just go with the default TabAnimation
  // behavior...
  void InitStartState() {
    for (int i = 0; i < tabstrip_->GetTabCount(); ++i) {
      TabGtk* current_tab = tabstrip_->GetTabAt(i);
      if (current_tab->IsSelected()) {
        start_selected_width_ = current_tab->width();
      } else {
        start_unselected_width_ = current_tab->width();
      }
    }
  }

  DISALLOW_COPY_AND_ASSIGN(ResizeLayoutAnimation);
};

////////////////////////////////////////////////////////////////////////////////

// Handles the movement of a Tab to it's snapped tab index.
class SnapTabAnimation : public TabStripGtk::TabAnimation {
 public:
  SnapTabAnimation(TabStripGtk* tabstrip, const gfx::Rect& bounds)
      : TabAnimation(tabstrip, SNAP),
        tabstrip_(tabstrip) {
    tab_ = tabstrip->GetTabAt(tabstrip->hover_index_);
    animation_start_bounds_ = tab_->bounds();
    animation_end_bounds_ = bounds;
  }
  virtual ~SnapTabAnimation() {}

  // Overridden from AnimationDelegate:
  virtual void AnimationProgressed(const Animation* animation) {
    int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
    int x = animation_start_bounds_.x() +
        static_cast<int>(delta_x * animation->GetCurrentValue());
    int y = animation_end_bounds_.y();
    gfx::Rect rect = tab_->bounds();
    rect.set_x(x);
    rect.set_y(y);
    tab_->SetBounds(rect);

    gtk_widget_queue_draw(tabstrip_->tabstrip_.get());
  }

 protected:
  // Overridden from TabStrip::TabAnimation:
  virtual int GetDuration() const { return kReorderAnimationDurationMs; }

 private:
  TabStripGtk* tabstrip_;
  // The tab being snapped.
  TabGtk* tab_;

  // The start and end bounds of the animation sequence.
  gfx::Rect animation_start_bounds_;
  gfx::Rect animation_end_bounds_;

  DISALLOW_COPY_AND_ASSIGN(SnapTabAnimation);
};

////////////////////////////////////////////////////////////////////////////////
// TabStripGtk, public:

TabStripGtk::TabStripGtk(TabStripModel* model)
    : current_unselected_width_(TabGtk::GetStandardSize().width()),
      current_selected_width_(TabGtk::GetStandardSize().width()),
      available_width_for_tabs_(-1),
      resize_layout_scheduled_(false),
      model_(model),
      hover_index_(0),
      mouse_offset_(-1, -1),
      last_move_x_(0),
      is_dragging_(false) {
}

TabStripGtk::~TabStripGtk() {
  model_->RemoveObserver(this);
  tabstrip_.Destroy();

  // Free any remaining tabs.  This is needed to free the very last tab,
  // because it is not animated on close.  This also happens when all of the
  // tabs are closed at once.
  std::vector<TabData>::iterator iterator = tab_data_.begin();
  for (; iterator < tab_data_.end(); iterator++) {
    delete iterator->tab;
  }

  tab_data_.clear();
}

void TabStripGtk::Init() {
  ResourceBundle &rb = ResourceBundle::GetSharedInstance();

  model_->AddObserver(this);

  if (!background) {
    background = rb.GetBitmapNamed(IDR_WINDOW_TOP_CENTER);
  }

  tabstrip_.Own(gtk_drawing_area_new());
  gtk_widget_set_size_request(tabstrip_.get(), -1,
                              TabGtk::GetMinimumUnselectedSize().height());
  gtk_widget_set_app_paintable(tabstrip_.get(), TRUE);
  // ChromeCanvasPaint already effectively double buffers.
  gtk_widget_set_double_buffered(tabstrip_.get(), FALSE);
  gtk_drag_source_set(tabstrip_.get(), GDK_BUTTON1_MASK,
                      target_table, G_N_ELEMENTS(target_table),
                      GDK_ACTION_MOVE);
  gtk_drag_dest_set(tabstrip_.get(), GTK_DEST_DEFAULT_DROP,
                    target_table, G_N_ELEMENTS(target_table),
                    GDK_ACTION_MOVE);
  gtk_drag_dest_set_track_motion(tabstrip_.get(), true);
  g_signal_connect(G_OBJECT(tabstrip_.get()), "expose-event",
                   G_CALLBACK(OnExpose), this);
  g_signal_connect(G_OBJECT(tabstrip_.get()), "configure-event",
                   G_CALLBACK(OnConfigure), this);
  g_signal_connect(G_OBJECT(tabstrip_.get()), "motion-notify-event",
                   G_CALLBACK(OnMotionNotify), this);
  g_signal_connect(G_OBJECT(tabstrip_.get()), "button-press-event",
                   G_CALLBACK(OnMousePress), this);
  g_signal_connect(G_OBJECT(tabstrip_.get()), "button-release-event",
                   G_CALLBACK(OnMouseRelease), this);
  g_signal_connect(G_OBJECT(tabstrip_.get()), "leave-notify-event",
                   G_CALLBACK(OnLeaveNotify), this);
  g_signal_connect_after(G_OBJECT(tabstrip_.get()), "drag-begin",
                         G_CALLBACK(&OnDragBegin), this);
  g_signal_connect_after(G_OBJECT(tabstrip_.get()), "drag-end",
                         G_CALLBACK(&OnDragEnd), this);
  g_signal_connect_after(G_OBJECT(tabstrip_.get()), "drag-failed",
                           G_CALLBACK(&OnDragFailed), this);
  g_signal_connect_after(G_OBJECT(tabstrip_.get()), "drag-motion",
                         G_CALLBACK(&OnDragMotion), this);
  gtk_widget_add_events(tabstrip_.get(),
      GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
      GDK_BUTTON_RELEASE_MASK |GDK_LEAVE_NOTIFY_MASK);
  gtk_widget_show_all(tabstrip_.get());

  bounds_ = GetInitialWidgetBounds(tabstrip_.get());

  SkBitmap* bitmap = rb.GetBitmapNamed(IDR_NEWTAB_BUTTON);
  newtab_button_.reset(new TabButtonGtk(this));
  newtab_button_.get()->SetImage(TabButtonGtk::BS_NORMAL, bitmap);
  newtab_button_.get()->SetImage(TabButtonGtk::BS_HOT,
                           rb.GetBitmapNamed(IDR_NEWTAB_BUTTON_H));
  newtab_button_.get()->SetImage(TabButtonGtk::BS_PUSHED,
                           rb.GetBitmapNamed(IDR_NEWTAB_BUTTON_P));
  newtab_button_.get()->set_bounds(
      gfx::Rect(0, 0, bitmap->width(), bitmap->height()));
}

void TabStripGtk::AddTabStripToBox(GtkWidget* box) {
  gtk_box_pack_start(GTK_BOX(box), tabstrip_.get(), FALSE, FALSE, 0);
}

void TabStripGtk::Show() {
  gtk_widget_show(tabstrip_.get());
}

void TabStripGtk::Hide() {
  gtk_widget_hide(tabstrip_.get());
}

void TabStripGtk::Layout() {
  // Called from:
  // - window resize
  // - animation completion
  if (active_animation_.get())
    active_animation_->Stop();

  GenerateIdealBounds();
  int tab_count = GetTabCount();
  int tab_right = 0;
  for (int i = 0; i < tab_count; ++i) {
    const gfx::Rect& bounds = tab_data_.at(i).ideal_bounds;
    GetTabAt(i)->SetBounds(bounds);
    tab_right = bounds.right() + kTabHOffset;
  }

  LayoutNewTabButton(static_cast<double>(tab_right), current_unselected_width_);
  gtk_widget_queue_draw(tabstrip_.get());
}

void TabStripGtk::UpdateLoadingAnimations() {
  for (int i = 0, index = 0; i < GetTabCount(); ++i, ++index) {
    TabGtk* current_tab = GetTabAt(i);
    if (current_tab->closing()) {
      --index;
    } else {
      TabContents* contents = model_->GetTabContentsAt(index);
      if (!contents || !contents->is_loading()) {
        current_tab->ValidateLoadingAnimation(TabGtk::ANIMATION_NONE);
      } else if (contents->waiting_for_response()) {
        current_tab->ValidateLoadingAnimation(TabGtk::ANIMATION_WAITING);
      } else {
        current_tab->ValidateLoadingAnimation(TabGtk::ANIMATION_LOADING);
      }
    }
  }

  gtk_widget_queue_draw(tabstrip_.get());
}

bool TabStripGtk::IsAnimating() const {
  return active_animation_.get() != NULL;
}

gfx::Rect TabStripGtk::GetIdealBounds(int index) {
  DCHECK(index >= 0 && index < GetTabCount());
  return tab_data_.at(index).ideal_bounds;
}

////////////////////////////////////////////////////////////////////////////////
// TabStripGtk, TabStripModelObserver implementation:

void TabStripGtk::TabInsertedAt(TabContents* contents,
                                int index,
                                bool foreground) {
  DCHECK(contents);
  DCHECK(index == TabStripModel::kNoTab || model_->ContainsIndex(index));

  if (active_animation_.get())
    active_animation_->Stop();

  TabGtk* tab = new TabGtk(this);

  // Only insert if we're not already in the list.
  if (index == TabStripModel::kNoTab) {
    TabData d = { tab, gfx::Rect() };
    tab_data_.push_back(d);
    tab->UpdateData(contents, false);
  } else {
    TabData d = { tab, gfx::Rect() };
    tab_data_.insert(tab_data_.begin() + index, d);
    tab->UpdateData(contents, false);
  }

  // Don't animate the first tab; it looks weird.
  if (GetTabCount() > 1) {
    StartInsertTabAnimation(index);
  } else {
    Layout();
  }
}

void TabStripGtk::TabDetachedAt(TabContents* contents, int index) {
  if (CanUpdateDisplay()) {
    GenerateIdealBounds();
    StartRemoveTabAnimation(index, contents);
    // Have to do this _after_ calling StartRemoveTabAnimation, so that any
    // previous remove is completed fully and index is valid in sync with the
    // model index.
    GetTabAt(index)->set_closing(true);
  }
}

void TabStripGtk::TabSelectedAt(TabContents* old_contents,
                                TabContents* new_contents,
                                int index,
                                bool user_gesture) {
  DCHECK(index >= 0 && index < static_cast<int>(GetTabCount()));

  if (CanUpdateDisplay()) {
    // We have "tiny tabs" if the tabs are so tiny that the unselected ones are
    // a different size to the selected ones.
    bool tiny_tabs = current_unselected_width_ != current_selected_width_;
    if (!IsAnimating() && (!resize_layout_scheduled_ || tiny_tabs)) {
      Layout();
    } else {
      gtk_widget_queue_draw(tabstrip_.get());
    }
  }
}

void TabStripGtk::TabMoved(TabContents* contents,
                           int from_index,
                           int to_index) {
  TabGtk* tab = GetTabAt(from_index);
  tab_data_.erase(tab_data_.begin() + from_index);
  TabData data = {tab, gfx::Rect()};
  tab_data_.insert(tab_data_.begin() + to_index, data);
  GenerateIdealBounds();
  StartMoveTabAnimation(from_index, to_index);
}

void TabStripGtk::TabChangedAt(TabContents* contents, int index,
                               bool loading_only) {
  // Index is in terms of the model. Need to make sure we adjust that index in
  // case we have an animation going.
  TabGtk* tab = GetTabAt(index);
  tab->UpdateData(contents, loading_only);
  tab->UpdateFromModel();
  gtk_widget_queue_draw(tabstrip_.get());
}

////////////////////////////////////////////////////////////////////////////////
// TabStripGtk, TabGtk::TabDelegate implementation:

bool TabStripGtk::IsTabSelected(const TabGtk* tab) const {
  if (tab->closing())
    return false;

  return GetIndexOfTab(tab) == model_->selected_index();
}

void TabStripGtk::GetCurrentTabWidths(double* unselected_width,
                                      double* selected_width) const {
  *unselected_width = current_unselected_width_;
  *selected_width = current_selected_width_;
}

void TabStripGtk::SelectTab(TabGtk* tab) {
  int index = GetIndexOfTab(tab);
  if (model_->ContainsIndex(index))
    model_->SelectTabContentsAt(index, true);
}

void TabStripGtk::CloseTab(TabGtk* tab) {
  int tab_index = GetIndexOfTab(tab);
  if (model_->ContainsIndex(tab_index)) {
    TabGtk* last_tab = GetTabAt(GetTabCount() - 1);
    // Limit the width available to the TabStrip for laying out Tabs, so that
    // Tabs are not resized until a later time (when the mouse pointer leaves
    // the TabStrip).
    available_width_for_tabs_ = GetAvailableWidthForTabs(last_tab);
    resize_layout_scheduled_ = true;
    model_->CloseTabContentsAt(tab_index);
  }
}

bool TabStripGtk::IsCommandEnabledForTab(
    TabStripModel::ContextMenuCommand command_id, const TabGtk* tab) const {
  int index = GetIndexOfTab(tab);
  if (model_->ContainsIndex(index))
    return model_->IsContextMenuCommandEnabled(index, command_id);
  return false;
}

void TabStripGtk::ExecuteCommandForTab(
    TabStripModel::ContextMenuCommand command_id, TabGtk* tab) {
  int index = GetIndexOfTab(tab);
  if (model_->ContainsIndex(index))
    model_->ExecuteContextMenuCommand(index, command_id);
}

void TabStripGtk::StartHighlightTabsForCommand(
    TabStripModel::ContextMenuCommand command_id, TabGtk* tab) {
  if (command_id == TabStripModel::CommandCloseTabsOpenedBy) {
    int index = GetIndexOfTab(tab);
    if (model_->ContainsIndex(index)) {
      std::vector<int> indices = model_->GetIndexesOpenedBy(index);
      std::vector<int>::const_iterator iter = indices.begin();
      for (; iter != indices.end(); ++iter) {
        int current_index = *iter;
        DCHECK(current_index >= 0 && current_index < GetTabCount());
      }
    }
  }
}

void TabStripGtk::StopHighlightTabsForCommand(
    TabStripModel::ContextMenuCommand command_id, TabGtk* tab) {
  if (command_id == TabStripModel::CommandCloseTabsOpenedBy ||
      command_id == TabStripModel::CommandCloseTabsToRight ||
      command_id == TabStripModel::CommandCloseOtherTabs) {
    // Just tell all Tabs to stop pulsing - it's safe.
    StopAllHighlighting();
  }
}

void TabStripGtk::StopAllHighlighting() {
  // TODO(jhawkins): Hook up animations.
}

bool TabStripGtk::EndDrag(bool canceled) {
  // TODO(jhawkins): Tab dragging.
  return true;
}

bool TabStripGtk::HasAvailableDragActions() const {
  return model_->delegate()->GetDragActions() != 0;
}

////////////////////////////////////////////////////////////////////////////////
// TabStripGtk, TabButtonGtk::Delegate implementation:

GdkRegion* TabStripGtk::MakeRegionForButton(const TabButtonGtk* button) const {
  const int w = button->width();
  const int kNumRegionPoints = 8;

  // These values are defined by the shape of the new tab bitmap. Should that
  // bitmap ever change, these values will need to be updated. They're so
  // custom it's not really worth defining constants for.
  GdkPoint polygon[kNumRegionPoints] = {
    { 0, 1 },
    { w - 7, 1 },
    { w - 4, 4 },
    { w, 16 },
    { w - 1, 17 },
    { 7, 17 },
    { 4, 13 },
    { 0, 1 },
  };

  GdkRegion* region = gdk_region_polygon(polygon, kNumRegionPoints,
                                         GDK_WINDING_RULE);
  gdk_region_offset(region, button->x(), button->y());
  return region;
}

void TabStripGtk::OnButtonActivate(const TabButtonGtk* button) {
  model_->delegate()->AddBlankTab(true);
}

////////////////////////////////////////////////////////////////////////////////
// TabStripGtk, private:

int TabStripGtk::GetTabCount() const {
  return static_cast<int>(tab_data_.size());
}

int TabStripGtk::GetAvailableWidthForTabs(TabGtk* last_tab) const {
  return last_tab->x() + last_tab->width();
}

int TabStripGtk::GetIndexOfTab(const TabGtk* tab) const {
  for (int i = 0, index = 0; i < GetTabCount(); ++i, ++index) {
    TabGtk* current_tab = GetTabAt(i);
    if (current_tab->closing()) {
      --index;
    } else if (current_tab == tab) {
      return index;
    }
  }
  return -1;
}

TabGtk* TabStripGtk::GetTabAt(int index) const {
  DCHECK_GE(index, 0);
  DCHECK_LT(index, GetTabCount());
  return tab_data_.at(index).tab;
}

void TabStripGtk::RemoveTabAt(int index) {
  TabGtk* removed = tab_data_.at(index).tab;

  // Remove the Tab from the TabStrip's list.
  tab_data_.erase(tab_data_.begin() + index);

  delete removed;
}

void TabStripGtk::GenerateIdealBounds() {
  int tab_count = GetTabCount();
  double unselected, selected;
  GetDesiredTabWidths(tab_count, &unselected, &selected);

  current_unselected_width_ = unselected;
  current_selected_width_ = selected;

  // NOTE: This currently assumes a tab's height doesn't differ based on
  // selected state or the number of tabs in the strip!
  int tab_height = TabGtk::GetStandardSize().height();
  double tab_x = 0;
  for (int i = 0; i < tab_count; ++i) {
    TabGtk* tab = GetTabAt(i);
    double tab_width = unselected;
    if (tab->IsSelected())
      tab_width = selected;
    double end_of_tab = tab_x + tab_width;
    int rounded_tab_x = Round(tab_x);
    gfx::Rect state(rounded_tab_x, 0, Round(end_of_tab) - rounded_tab_x,
                    tab_height);
    tab_data_.at(i).ideal_bounds = state;
    tab_x = end_of_tab + kTabHOffset;
  }
}

void TabStripGtk::LayoutNewTabButton(double last_tab_right,
                                     double unselected_width) {
  int delta = abs(Round(unselected_width) - TabGtk::GetStandardSize().width());
  if (delta > 1 && !resize_layout_scheduled_) {
    // We're shrinking tabs, so we need to anchor the New Tab button to the
    // right edge of the TabStrip's bounds, rather than the right edge of the
    // right-most Tab, otherwise it'll bounce when animating.
    newtab_button_.get()->set_bounds(
        gfx::Rect(bounds_.width() - newtab_button_.get()->bounds().width(),
                  kNewTabButtonVOffset,
                  newtab_button_.get()->bounds().width(),
                  newtab_button_.get()->bounds().height()));
  } else {
    newtab_button_.get()->set_bounds(
        gfx::Rect(Round(last_tab_right - kTabHOffset) + kNewTabButtonHOffset,
                  kNewTabButtonVOffset, newtab_button_.get()->bounds().width(),
                  newtab_button_.get()->bounds().height()));
  }
}

void TabStripGtk::GetDesiredTabWidths(int tab_count,
                                      double* unselected_width,
                                      double* selected_width) const {
  const double min_unselected_width =
      TabGtk::GetMinimumUnselectedSize().width();
  const double min_selected_width =
      TabGtk::GetMinimumSelectedSize().width();

  if (tab_count == 0) {
    // Return immediately to avoid divide-by-zero below.
    *unselected_width = min_unselected_width;
    *selected_width = min_selected_width;
    return;
  }

  // Determine how much space we can actually allocate to tabs.
  int available_width = tabstrip_.get()->allocation.width;
  if (available_width_for_tabs_ < 0) {
    available_width = bounds_.width();
    available_width -=
        (kNewTabButtonHOffset + newtab_button_.get()->bounds().width());
  } else {
    // Interesting corner case: if |available_width_for_tabs_| > the result
    // of the calculation in the conditional arm above, the strip is in
    // overflow.  We can either use the specified width or the true available
    // width here; the first preserves the consistent "leave the last tab under
    // the user's mouse so they can close many tabs" behavior at the cost of
    // prolonging the glitchy appearance of the overflow state, while the second
    // gets us out of overflow as soon as possible but forces the user to move
    // their mouse for a few tabs' worth of closing.  We choose visual
    // imperfection over behavioral imperfection and select the first option.
    available_width = available_width_for_tabs_;
  }

  // Calculate the desired tab widths by dividing the available space into equal
  // portions.  Don't let tabs get larger than the "standard width" or smaller
  // than the minimum width for each type, respectively.
  const int total_offset = kTabHOffset * (tab_count - 1);
  const double desired_tab_width = std::min(
      (static_cast<double>(available_width - total_offset) /
       static_cast<double>(tab_count)),
      static_cast<double>(TabGtk::GetStandardSize().width()));
  *unselected_width = std::max(desired_tab_width, min_unselected_width);
  *selected_width = std::max(desired_tab_width, min_selected_width);

  // When there are multiple tabs, we'll have one selected and some unselected
  // tabs.  If the desired width was between the minimum sizes of these types,
  // try to shrink the tabs with the smaller minimum.  For example, if we have
  // a strip of width 10 with 4 tabs, the desired width per tab will be 2.5.  If
  // selected tabs have a minimum width of 4 and unselected tabs have a minimum
  // width of 1, the above code would set *unselected_width = 2.5,
  // *selected_width = 4, which results in a total width of 11.5.  Instead, we
  // want to set *unselected_width = 2, *selected_width = 4, for a total width
  // of 10.
  if (tab_count > 1) {
    if ((min_unselected_width < min_selected_width) &&
        (desired_tab_width < min_selected_width)) {
      double calc_width =
          static_cast<double>(
              available_width - total_offset - min_selected_width) /
          static_cast<double>(tab_count - 1);
      *unselected_width = std::max(calc_width, min_unselected_width);
    } else if ((min_unselected_width > min_selected_width) &&
               (desired_tab_width < min_unselected_width)) {
      *selected_width = std::max(available_width - total_offset -
          (min_unselected_width * (tab_count - 1)), min_selected_width);
    }
  }
}

void TabStripGtk::ResizeLayoutTabs() {
  available_width_for_tabs_ = -1;
  double unselected, selected;
  GetDesiredTabWidths(GetTabCount(), &unselected, &selected);
  TabGtk* first_tab = GetTabAt(0);
  int w = Round(first_tab->IsSelected() ? selected : selected);

  // We only want to run the animation if we're not already at the desired
  // size.
  if (abs(first_tab->width() - w) > 1)
    StartResizeLayoutAnimation();
}

// Called from:
// - animation tick
void TabStripGtk::AnimationLayout(double unselected_width) {
  int tab_height = TabGtk::GetStandardSize().height();
  double tab_x = 0;
  for (int i = 0; i < GetTabCount(); ++i) {
    TabAnimation* animation = active_animation_.get();
    double tab_width = TabAnimation::GetCurrentTabWidth(this, animation, i);
    double end_of_tab = tab_x + tab_width;
    int rounded_tab_x = Round(tab_x);
    TabGtk* tab = GetTabAt(i);
    gfx::Rect bounds(rounded_tab_x, 0, Round(end_of_tab) - rounded_tab_x,
                     tab_height);
    tab->SetBounds(bounds);
    tab_x = end_of_tab + kTabHOffset;
  }
  LayoutNewTabButton(tab_x, unselected_width);
  gtk_widget_queue_draw(tabstrip_.get());
}

void TabStripGtk::StartInsertTabAnimation(int index) {
  // The TabStrip can now use its entire width to lay out Tabs.
  available_width_for_tabs_ = -1;
  if (active_animation_.get())
    active_animation_->Stop();
  active_animation_.reset(new InsertTabAnimation(this, index));
  active_animation_->Start();
}

void TabStripGtk::StartRemoveTabAnimation(int index, TabContents* contents) {
  if (active_animation_.get()) {
    // Some animations (e.g. MoveTabAnimation) cause there to be a Layout when
    // they're completed (which includes canceled). Since |tab_data_| is now
    // inconsistent with TabStripModel, doing this Layout will crash now, so
    // we ask the MoveTabAnimation to skip its Layout (the state will be
    // corrected by the RemoveTabAnimation we're about to initiate).
    active_animation_->set_layout_on_completion(false);
    active_animation_->Stop();
  }

  active_animation_.reset(new RemoveTabAnimation(this, index, contents));
  active_animation_->Start();
}

void TabStripGtk::StartMoveTabAnimation(int from_index, int to_index) {
  if (active_animation_.get())
    active_animation_->Stop();
  active_animation_.reset(new MoveTabAnimation(this, from_index, to_index));
  active_animation_->Start();
}

void TabStripGtk::StartResizeLayoutAnimation() {
  if (active_animation_.get())
    active_animation_->Stop();
  active_animation_.reset(new ResizeLayoutAnimation(this));
  active_animation_->Start();
}

void TabStripGtk::StartSnapTabAnimation(const gfx::Rect& bounds) {
  if (active_animation_.get())
    active_animation_->Stop();
  active_animation_.reset(new SnapTabAnimation(this, bounds));
  active_animation_->Start();
}

bool TabStripGtk::CanUpdateDisplay() {
  // Don't bother laying out/painting when we're closing all tabs.
  if (model_->closing_all()) {
    // Make sure any active animation is ended, too.
    if (active_animation_.get())
      active_animation_->Stop();
    return false;
  }
  return true;
}

void TabStripGtk::FinishAnimation(TabStripGtk::TabAnimation* animation,
                                  bool layout) {
  active_animation_.reset(NULL);
  if (layout)
    Layout();
}

// static
gboolean TabStripGtk::OnExpose(GtkWidget* widget, GdkEventExpose* event,
                               TabStripGtk* tabstrip) {
  ChromeCanvasPaint canvas(event);
  if (canvas.isEmpty())
    return TRUE;

  canvas.TileImageInt(*background, 0, 0, tabstrip->bounds_.width(),
                      tabstrip->bounds_.height());

  // Paint the New Tab button.  This is painted first because a dragged tab
  // should be at the bottom of the z-order.
  tabstrip->newtab_button_.get()->Paint(&canvas);

  // Paint the tabs in reverse order, so they stack to the left.
  TabGtk* selected_tab = NULL;
  int tab_count = tabstrip->GetTabCount();
  for (int i = tab_count - 1; i >= 0; --i) {
    TabGtk* tab = tabstrip->GetTabAt(i);
    // We must ask the _Tab's_ model, not ourselves, because in some situations
    // the model will be different to this object, e.g. when a Tab is being
    // removed after its TabContents has been destroyed.
    if (!tab->IsSelected()) {
      tab->Paint(&canvas);
    } else {
      selected_tab = tab;
    }
  }

  // Paint the selected tab last, so it overlaps all the others.
  if (selected_tab)
    selected_tab->Paint(&canvas);

  return TRUE;
}

// static
gboolean TabStripGtk::OnConfigure(GtkWidget* widget, GdkEventConfigure* event,
                                  TabStripGtk* tabstrip) {
  gfx::Rect bounds = gfx::Rect(event->x, event->y, event->width, event->height);
  tabstrip->SetBounds(bounds);

  // No tabs, nothing to layout.  This happens when a browser window is created
  // and shown before tabs are added (as in a popup window).
  if (tabstrip->GetTabCount() == 0)
    return TRUE;

  // Do a regular layout on the first configure-event so we don't animate
  // the first tab.
  // TODO(jhawkins): Windows resizes the layout tabs continuously during
  // a resize.  I need to investigate which signal to watch in order to
  // reproduce this behavior.
  if (tabstrip->GetTabCount() == 1)
    tabstrip->Layout();
  else
    tabstrip->ResizeLayoutTabs();

  return TRUE;
}

// static
gboolean TabStripGtk::OnMotionNotify(GtkWidget* widget, GdkEventMotion* event,
                                     TabStripGtk* tabstrip) {
  // The dragging code handles moving the tab while the tab is being dragged.
  if (tabstrip->is_dragging_)
    return TRUE;

  int old_hover_index = tabstrip->hover_index_;
  gfx::Point point(event->x, event->y);

  int index;
  TabAnimation* animation = tabstrip->active_animation_.get();
  if (animation && animation->type() == TabAnimation::SNAP) {
    index = tabstrip->FindTabHoverIndexIterative(point);
  } else {
    index = tabstrip->FindTabHoverIndexFast(point);
  }

  // Hovering does not take place outside of the currently highlighted tab if
  // the button is pressed.
  if (IsButtonPressed(event->state) && index != tabstrip->hover_index_)
    return TRUE;

  tabstrip->hover_index_ = index;

  bool paint = false;
  if (old_hover_index != -1 && old_hover_index != index &&
      old_hover_index < tabstrip->GetTabCount()) {
    // Notify the previously highlighted tab that the mouse has left.
    paint = tabstrip->GetTabAt(old_hover_index)->OnLeaveNotify();
  }

  if (tabstrip->hover_index_ == -1) {
    // If the hover index is out of bounds, try the new tab button.
    paint |= tabstrip->newtab_button_.get()->OnMotionNotify(event);
  } else {
    // Notify the currently highlighted tab where the mouse is.
    paint |= tabstrip->GetTabAt(tabstrip->hover_index_)->OnMotionNotify(event);
  }

  if (paint)
    gtk_widget_queue_draw(tabstrip->tabstrip_.get());

  return TRUE;
}

// static
gboolean TabStripGtk::OnMousePress(GtkWidget* widget, GdkEventButton* event,
                                   TabStripGtk* tabstrip) {
  gfx::Point point(event->x, event->y);

  // Nothing happens on mouse press for middle and right click.
  if (event->button != 1)
    return TRUE;

  // The hover index is stale if we're in the middle of an animation and the
  // mouse is pressed without any movement.
  if (tabstrip->active_animation_.get())
    tabstrip->hover_index_ = tabstrip->FindTabHoverIndexIterative(point);

  if (tabstrip->hover_index_ == -1) {
    if (tabstrip->newtab_button_.get()->IsPointInBounds(point) &&
        tabstrip->newtab_button_.get()->OnMousePress())
      gtk_widget_queue_draw(tabstrip->tabstrip_.get());

    return TRUE;
  }

  TabGtk* tab = tabstrip->GetTabAt(tabstrip->hover_index_);

  // If a previous tab is closing, the hover index does not match the model
  // index.
  tabstrip->hover_index_ = tabstrip->GetIndexOfTab(tab);

  if (tab->OnMousePress(point)) {
    gtk_widget_queue_draw(tabstrip->tabstrip_.get());
  } else if (tabstrip->hover_index_ != tabstrip->model()->selected_index() &&
             !tab->closing()) {
    tabstrip->model()->SelectTabContentsAt(tabstrip->hover_index_, true);
  }

  return TRUE;
}

// static
gboolean TabStripGtk::OnMouseRelease(GtkWidget* widget, GdkEventButton* event,
                                     TabStripGtk* tabstrip) {
  gfx::Point point(event->x, event->y);
  if (tabstrip->hover_index_ != -1) {
    tabstrip->GetTabAt(tabstrip->hover_index_)->OnMouseRelease(event);
  } else {
    tabstrip->newtab_button_.get()->OnMouseRelease();
  }

  return TRUE;
}

// static
gboolean TabStripGtk::OnEnterNotify(GtkWidget* widget, GdkEventCrossing* event,
                                    TabStripGtk* tabstrip) {
  if (tabstrip->is_dragging_) {
    TabGtk* tab = tabstrip->GetTabAt(tabstrip->hover_index_);
    tabstrip->MoveTab(tab, gfx::Point(event->x, event->y));
    gtk_widget_queue_draw(tabstrip->tabstrip_.get());
  }

  return TRUE;
}

// static
gboolean TabStripGtk::OnLeaveNotify(GtkWidget* widget, GdkEventCrossing* event,
                                    TabStripGtk* tabstrip) {
  // No leave notification if the mouse button is pressed.
  if (IsButtonPressed(event->state))
    return TRUE;

  // gtk does not set the button pressed state when a drag is occurring, so
  // bail out if we're dragging.  Otherwise, the SnapTabAnimation will have
  // the wrong tab index (-1) when initiating the snap.
  if (tabstrip->is_dragging_)
    return TRUE;

  // A leave-notify-event is generated on mouse click, which sets the mode to
  // GDK_CROSSING_GRAB.  Ignore this event because it doesn't meant the mouse
  // has left the tabstrip.
  if (event->mode == GDK_CROSSING_GRAB)
    return TRUE;

  // There is a race between the remove tab animation and the hover index
  // handling in OnMotionNotify.  As the mouse leaves the tabstrip,
  // OnMotionNotify figures out the hover index, the remove tab animation moves
  // a frame, and the hover index becomes stale as OnLeaveNotify is called.
  // The check against GetTabCount avoids this scenario.
  if (tabstrip->hover_index_ != -1 &&
      tabstrip->hover_index_ < tabstrip->GetTabCount()) {
    tabstrip->GetTabAt(tabstrip->hover_index_)->OnLeaveNotify();
    tabstrip->hover_index_ = -1;
    gtk_widget_queue_draw(tabstrip->tabstrip_.get());
  }

  return TRUE;
}

// static
void TabStripGtk::OnDragBegin(GtkWidget* widget, GdkDragContext* context,
                              TabStripGtk* tabstrip) {
  // No dragging should happen if the tab is closing.
  if (tabstrip->hover_index_ == -1 ||
      tabstrip->GetTabAt(tabstrip->hover_index_)->closing()) {
    gdk_drop_finish(context, FALSE, 0);
    return;
  }

  // If we're in the middle of a snap animation, stop the animation.  We only
  // set the snap bounds if the tab is snapped into a proper index, which is not
  // the case if it's being snapped.
  if (tabstrip->active_animation_.get()) {
    tabstrip->active_animation_->Stop();
  } else {
    tabstrip->snap_bounds_ =
      tabstrip->GetTabAt(tabstrip->hover_index_)->bounds();
  }

  tabstrip->is_dragging_ = true;
}

// static
void TabStripGtk::OnDragEnd(GtkWidget* widget, GdkDragContext* context,
                            TabStripGtk* tabstrip) {
  if (tabstrip->is_dragging_) {
    tabstrip->StartSnapTabAnimation(tabstrip->snap_bounds_);
    tabstrip->mouse_offset_ = gfx::Point(-1, -1);
    tabstrip->is_dragging_ = false;
  }
}

// static
gboolean TabStripGtk::OnDragFailed(GtkWidget* widget, GdkDragContext* context,
                                   GtkDragResult result,
                                   TabStripGtk* tabstrip) {
  tabstrip->mouse_offset_ = gfx::Point(-1, -1);
  tabstrip->is_dragging_ = false;
  return TRUE;
}

// static
gboolean TabStripGtk::OnDragMotion(GtkWidget* widget,
                                   GdkDragContext* drag_context,
                                   guint x, guint y,
                                   guint time,
                                   TabStripGtk* tabstrip) {
  // gtk sends drag-motion signals even after the drag has failed, but before
  // the drag-end signal is emitted.
  if (!tabstrip->is_dragging_)
      return TRUE;

  TabGtk* tab = tabstrip->GetTabAt(tabstrip->hover_index_);
  gfx::Rect bounds = tab->bounds();

  // For whatever reason, gtk does not give us the coordinates of the mouse in
  // the drag-begin event, so set them here once.
  if (tabstrip->mouse_offset_ == gfx::Point(-1, -1))
    tabstrip->mouse_offset_.SetPoint(x - bounds.x(), y - bounds.y());

  tabstrip->MoveTab(tab, gfx::Point(x, y));
  gtk_widget_queue_draw(tabstrip->tabstrip_.get());

  return TRUE;
}

int TabStripGtk::FindTabHoverIndexIterative(const gfx::Point& point) {
  for (int i = 0; i < GetTabCount(); i++) {
    if (GetTabAt(i)->IsPointInBounds(point))
      return i;
  }

  return -1;
}

int TabStripGtk::FindTabHoverIndexFast(const gfx::Point& point) {
  // Get a rough estimate for which tab the mouse is over.
  int index = point.x() / (current_unselected_width_ + kTabHOffset);

  // Tab hovering calcuation.
  // Using the rough estimate tab index, we check the tab bounds in a smart
  // order to reduce the number of tabs we need to check.  If the tab at the
  // estimated index is selected, check it first as it covers both tabs below
  // it.  Otherwise, check the tab to the left, then the estimated tab, and
  // finally the tab to the right (tabs stack to the left.)

  int tab_count = GetTabCount();
  if (index == tab_count &&
      GetTabAt(index - 1)->IsPointInBounds(point)) {
    index--;
  } else if (index >= tab_count) {
    index = -1;
  } else if (index > 0 &&
             GetTabAt(index - 1)->IsPointInBounds(point)) {
    index--;
  } else if (index < tab_count - 1 &&
             GetTabAt(index + 1)->IsPointInBounds(point)) {
    index++;
  }

  return index;
}

void TabStripGtk::MoveTab(TabGtk* tab, const gfx::Point& point) {
  // Determine the horizontal move threshold. This is dependent on the width
  // of tabs. The smaller the tabs compared to the standard size, the smaller
  // the threshold.
  double unselected, selected;
  GetCurrentTabWidths(&unselected, &selected);

  double ratio = unselected / TabGtk::GetStandardSize().width();
  int threshold = static_cast<int>(ratio * kHorizontalMoveThreshold);

  // Update the model, moving the TabContents from one index to another. Do
  // this only if we have moved a minimum distance since the last reorder (to
  // prevent jitter).
  if (abs(point.x() - last_move_x_) > threshold) {
    TabStripModel* attached_model = model();
    int from_index = hover_index_;
    gfx::Rect bounds = GetTabAt(hover_index_)->bounds();

    int to_index = GetInsertionIndexForDraggedBounds(bounds);
    to_index = NormalizeIndexToAttachedTabStrip(to_index);
    if (from_index != to_index) {
      last_move_x_ = point.x();
      hover_index_ = to_index;
      snap_bounds_ = GetTabAt(to_index)->bounds();
      attached_model->MoveTabContentsAt(from_index, to_index, true);
    }
  }

  // Move the tab.
  gfx::Point dragged_point = GetDraggedPoint(tab, point);
  gfx::Rect bounds = tab->bounds();
  bounds.set_x(dragged_point.x());
  tab->SetBounds(bounds);
}

gfx::Point TabStripGtk::GetDraggedPoint(TabGtk* tab, const gfx::Point& point) {
  int x = point.x() - mouse_offset_.x();
  int y = point.y() - mouse_offset_.y();

  // Snap the dragged tab to the tab strip.
  if (x < 0)
    x = 0;

  // Make sure the tab can't be dragged off the right side of the tab strip.
  int max_x = bounds_.right() - tab->width();
  if (x > max_x)
    x = max_x;

  return gfx::Point(x, y);
}

int TabStripGtk::GetInsertionIndexForDraggedBounds(
    const gfx::Rect& dragged_bounds) {
  int right_tab_x = 0;

  // TODO(jhawkins): Handle RTL layout.

  // Divides each tab into two halves to see if the dragged tab has crossed
  // the halfway boundary necessary to move past the next tab.
  for (int i = 0; i < GetTabCount(); i++) {
    gfx::Rect ideal_bounds = GetIdealBounds(i);

    gfx::Rect left_half = ideal_bounds;
    left_half.set_width(left_half.width() / 2);

    gfx::Rect right_half = ideal_bounds;
    right_half.set_width(ideal_bounds.width() - left_half.width());
    right_half.set_x(left_half.right());

    right_tab_x = right_half.right();

    if (dragged_bounds.x() >= right_half.x() &&
        dragged_bounds.x() < right_half.right()) {
      return i + 1;
    } else if (dragged_bounds.x() >= left_half.x() &&
               dragged_bounds.x() < left_half.right()) {
      return i;
    }
  }

  if (dragged_bounds.right() > right_tab_x)
    return model()->count();

  return TabStripModel::kNoTab;
}

int TabStripGtk::NormalizeIndexToAttachedTabStrip(int index) {
  if (index >= model_->count())
    return model_->count() - 1;
  if (index == TabStripModel::kNoTab)
    return 0;
  return index;
}