summaryrefslogtreecommitdiffstats
path: root/chrome/browser/views/constrained_window_impl.cc
blob: 85d9e582465ab2ac6c73296c102e8f7626b1f9a2 (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
// Copyright (c) 2006-2008 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/views/constrained_window_impl.h"

#include "base/gfx/rect.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/tab_contents.h"
#include "chrome/browser/views/constrained_window_animation.h"
#include "chrome/browser/views/location_bar_view.h"
#include "chrome/browser/views/window_resources.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/toolbar_model.h"
#include "chrome/browser/web_app.h"
#include "chrome/browser/web_contents.h"
#include "chrome/browser/window_sizer.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/gfx/chrome_canvas.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/gfx/path.h"
#include "chrome/common/gfx/url_elider.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/common/win_util.h"
#include "chrome/views/client_view.h"
#include "chrome/views/button.h"
#include "chrome/views/focus_manager.h"
#include "chrome/views/hwnd_view.h"
#include "chrome/views/non_client_view.h"
#include "net/base/net_util.h"

#include "chromium_strings.h"
#include "generated_resources.h"

namespace ChromeViews {
class ClientView;
}

// An enumeration of bitmap resources used by this window.
enum {
  FRAME_PART_BITMAP_FIRST = 0,  // Must be first.

  FRAME_BOTTOM_CENTER,
  FRAME_BOTTOM_LEFT_CORNER,
  FRAME_BOTTOM_RIGHT_CORNER,
  FRAME_LEFT_SIDE,
  FRAME_RIGHT_SIDE,
  FRAME_TOP_CENTER,
  FRAME_TOP_LEFT_CORNER,
  FRAME_TOP_RIGHT_CORNER,

  FRAME_CLOSE_BUTTON_ICON,
  FRAME_CLOSE_BUTTON_ICON_H,
  FRAME_CLOSE_BUTTON_ICON_P,

  FRAME_PART_BITMAP_COUNT  // Must be last.
};

static const int kXPFramePartIDs[] = {
    0, IDR_CONSTRAINED_BOTTOM_CENTER, IDR_CONSTRAINED_BOTTOM_LEFT_CORNER,
    IDR_CONSTRAINED_BOTTOM_RIGHT_CORNER, IDR_CONSTRAINED_LEFT_SIDE,
    IDR_CONSTRAINED_RIGHT_SIDE, IDR_CONSTRAINED_TOP_CENTER,
    IDR_CONSTRAINED_TOP_LEFT_CORNER, IDR_CONSTRAINED_TOP_RIGHT_CORNER,
    IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P, 0 };
static const int kVistaFramePartIDs[] = {
    0, IDR_CONSTRAINED_BOTTOM_CENTER_V, IDR_CONSTRAINED_BOTTOM_LEFT_CORNER_V,
    IDR_CONSTRAINED_BOTTOM_RIGHT_CORNER_V, IDR_CONSTRAINED_LEFT_SIDE_V,
    IDR_CONSTRAINED_RIGHT_SIDE_V, IDR_CONSTRAINED_TOP_CENTER_V,
    IDR_CONSTRAINED_TOP_LEFT_CORNER_V, IDR_CONSTRAINED_TOP_RIGHT_CORNER_V,
    IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P, 0 };
static const int kOTRFramePartIDs[] = {
    0, IDR_WINDOW_BOTTOM_CENTER_OTR, IDR_WINDOW_BOTTOM_LEFT_CORNER_OTR,
    IDR_WINDOW_BOTTOM_RIGHT_CORNER_OTR, IDR_WINDOW_LEFT_SIDE_OTR,
    IDR_WINDOW_RIGHT_SIDE_OTR, IDR_WINDOW_TOP_CENTER_OTR,
    IDR_WINDOW_TOP_LEFT_CORNER_OTR, IDR_WINDOW_TOP_RIGHT_CORNER_OTR,
    IDR_CLOSE_SA, IDR_CLOSE_SA_H, IDR_CLOSE_SA_P, 0 };

class XPWindowResources : public WindowResources {
 public:
  XPWindowResources() {
    InitClass();
  }
  virtual ~XPWindowResources() {}

  virtual SkBitmap* GetPartBitmap(FramePartBitmap part_id) const {
    return bitmaps_[part_id];
  }
  virtual const ChromeFont& GetTitleFont() const { return title_font_; }
  virtual SkColor GetTitleColor() const { return SK_ColorWHITE; }

 private:
  static void InitClass() {
    static bool initialized = false;
    if (!initialized) {
      ResourceBundle& rb = ResourceBundle::GetSharedInstance();
      for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
        int id = kXPFramePartIDs[i];
        if (id != 0)
          bitmaps_[i] = rb.GetBitmapNamed(id);
      }
      title_font_ =
          rb.GetFont(ResourceBundle::BaseFont).DeriveFont(1);
      initialized = true;
    }
  }

  static SkBitmap* bitmaps_[FRAME_PART_BITMAP_COUNT];
  static ChromeFont title_font_;

  DISALLOW_EVIL_CONSTRUCTORS(XPWindowResources);
};

class VistaWindowResources : public WindowResources {
 public:
  VistaWindowResources() {
    InitClass();
  }
  virtual ~VistaWindowResources() {}

  virtual SkBitmap* GetPartBitmap(FramePartBitmap part_id) const {
    return bitmaps_[part_id];
  }
  virtual const ChromeFont& GetTitleFont() const { return title_font_; }
  virtual SkColor GetTitleColor() const { return SK_ColorBLACK; }

 private:
  static void InitClass() {
    static bool initialized = false;
    if (!initialized) {
      ResourceBundle& rb = ResourceBundle::GetSharedInstance();
      for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
        int id = kVistaFramePartIDs[i];
        if (id != 0)
          bitmaps_[i] = rb.GetBitmapNamed(id);
      }
      title_font_ =
          rb.GetFont(ResourceBundle::BaseFont).DeriveFont(1);
      initialized = true;
    }
  }

  static SkBitmap* bitmaps_[FRAME_PART_BITMAP_COUNT];
  static ChromeFont title_font_;

  DISALLOW_EVIL_CONSTRUCTORS(VistaWindowResources);
};

class OTRWindowResources : public WindowResources {
 public:
  OTRWindowResources() {
    InitClass();
  }
  virtual ~OTRWindowResources() {}

  virtual SkBitmap* GetPartBitmap(FramePartBitmap part_id) const {
    return bitmaps_[part_id];
  }
  virtual const ChromeFont& GetTitleFont() const { return title_font_; }
  virtual SkColor GetTitleColor() const { return SK_ColorWHITE; }

 private:
  static void InitClass() {
    static bool initialized = false;
    if (!initialized) {
      ResourceBundle& rb = ResourceBundle::GetSharedInstance();
      for (int i = 0; i < FRAME_PART_BITMAP_COUNT; ++i) {
        int id = kOTRFramePartIDs[i];
        if (id != 0)
          bitmaps_[i] = rb.GetBitmapNamed(id);
      }
      title_font_ =
          rb.GetFont(ResourceBundle::BaseFont).DeriveFont(1);
      initialized = true;
    }
  }

  static SkBitmap* bitmaps_[FRAME_PART_BITMAP_COUNT];
  static ChromeFont title_font_;

  DISALLOW_EVIL_CONSTRUCTORS(OTRWindowResources);
};

SkBitmap* XPWindowResources::bitmaps_[];
ChromeFont XPWindowResources::title_font_;
SkBitmap* VistaWindowResources::bitmaps_[];
ChromeFont VistaWindowResources::title_font_;
SkBitmap* OTRWindowResources::bitmaps_[];
ChromeFont OTRWindowResources::title_font_;

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView

class ConstrainedWindowNonClientView
    : public ChromeViews::NonClientView,
      public ChromeViews::BaseButton::ButtonListener,
      public LocationBarView::Delegate {
 public:
  ConstrainedWindowNonClientView(ConstrainedWindowImpl* container,
                                 TabContents* owner);
  virtual ~ConstrainedWindowNonClientView();

  // Calculates the pixel height of the titlebar
  int CalculateTitlebarHeight() const;

  // Calculates the pixel height of all pieces of a window that are
  // not part of the webcontent display area.
  int CalculateNonClientHeight(bool with_url_field) const;
  gfx::Rect CalculateWindowBoundsForClientBounds(
      const gfx::Rect& client_bounds,
      bool with_url_field) const;
  void UpdateWindowTitle();

  void set_window_delegate(ChromeViews::WindowDelegate* window_delegate) {
    window_delegate_ = window_delegate;
  }

  // Changes whether we display a throbber or the current favicon and
  // forces a repaint of the titlebar.
  void SetShowThrobber(bool show_throbber);

  // Overridden from ChromeViews::NonClientView:
  virtual gfx::Rect CalculateClientAreaBounds(int width, int height) const;
  virtual gfx::Size CalculateWindowSizeForClientSize(int width,
                                                     int height) const;
  virtual CPoint GetSystemMenuPoint() const;
  virtual int NonClientHitTest(const gfx::Point& point);
  virtual void GetWindowMask(const gfx::Size& size, gfx::Path* window_mask);
  virtual void EnableClose(bool enable);

  // Overridden from ChromeViews::View:
  virtual void Paint(ChromeCanvas* canvas);
  virtual void Layout();
  virtual void GetPreferredSize(CSize* out);
  virtual void ViewHierarchyChanged(bool is_add, View *parent, View *child);

  // Overridden from ChromeViews::BaseButton::ButtonListener:
  virtual void ButtonPressed(ChromeViews::BaseButton* sender);

  // Overridden from LocationBarView::Delegate:
  virtual TabContents* GetTabContents();
  virtual void OnInputInProgress(bool in_progress);

  // Updates the current throbber animation frame; called from the
  // overloaded Run() and from SetShowThrobber().
  void UpdateThrobber();

  // Whether we should display the throbber instead of the favicon.
  bool should_show_throbber() const {
    return show_throbber_ && current_throbber_frame_ != -1;
  }

  // Paints different parts of the window to the incoming canvas.
  void PaintFrameBorder(ChromeCanvas* canvas);
  void PaintTitleBar(ChromeCanvas* canvas);
  void PaintThrobber(ChromeCanvas* canvas);
  void PaintWindowTitle(ChromeCanvas* canvas);

  void UpdateLocationBar();
  bool ShouldDisplayURLField() const;

  ConstrainedWindowImpl* container_;
  ChromeViews::WindowDelegate* window_delegate_;

  scoped_ptr<WindowResources> resources_;

  gfx::Rect title_bounds_;
  gfx::Rect icon_bounds_;
  gfx::Rect client_bounds_;

  ChromeViews::Button* close_button_;

  LocationBarView* location_bar_;

  // Specialization of ToolbarModel to obtain selected NavigationController for
  // a constrained TabContents.
  class ConstrainedWindowToolbarModel : public ToolbarModel {
   public:
    ConstrainedWindowToolbarModel(ConstrainedWindowImpl* constrained_window)
      : constrained_window_(constrained_window) {
    }
    ~ConstrainedWindowToolbarModel() { }

   protected:
    virtual NavigationController* GetNavigationController() {
      TabContents* tab = constrained_window_->constrained_contents();
      return tab ? tab->controller() : NULL;
    }

   private:
    ConstrainedWindowImpl* constrained_window_;

    DISALLOW_EVIL_CONSTRUCTORS(ConstrainedWindowToolbarModel);
  };

  // The model used for the states of the location bar.
  ConstrainedWindowToolbarModel toolbar_model_;

  // Whether we should display the animated throbber instead of the
  // favicon.
  bool show_throbber_;

  // The timer used to update frames for the throbber.
  base::RepeatingTimer<ConstrainedWindowNonClientView> throbber_timer_;

  // The current index into the throbber image strip.
  int current_throbber_frame_;

  static void InitClass();

  // The throbber to display while a constrained window is loading.
  static SkBitmap throbber_frames_;

  // The number of animation frames in throbber_frames_.
  static int throbber_frame_count_;

  DISALLOW_EVIL_CONSTRUCTORS(ConstrainedWindowNonClientView);
};

SkBitmap ConstrainedWindowNonClientView::throbber_frames_;
int ConstrainedWindowNonClientView::throbber_frame_count_ = -1;
static const int kWindowLeftSpacing = 5;
static const int kWindowControlsTopOffset = 1;
static const int kWindowControlsRightOffset = 4;
static const int kTitleTopOffset = 6;
static const int kTitleBottomSpacing = 5;
static const int kNoTitleTopSpacing = 8;
static const int kResizeAreaSize = 5;
static const int kResizeAreaNorthSize = 3;
static const int kResizeAreaCornerSize = 16;
static const int kWindowHorizontalBorderSize = 5;
static const int kWindowVerticalBorderSize = 5;
static const int kWindowIconSize = 16;

// How much wider or shorter the location bar is relative to the client area.
static const int kLocationBarOffset = 2;
// Spacing between the location bar and the content area.
static const int kLocationBarSpacing = 1;

static const SkColor kContentsBorderShadow = SkColorSetARGB(51, 0, 0, 0);
static const SkColor kContentsBorderColor = SkColorSetRGB(219, 235, 255);

static const int kThrobberFrameTimeMs = 30;

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView, public:

ConstrainedWindowNonClientView::ConstrainedWindowNonClientView(
    ConstrainedWindowImpl* container, TabContents* owner)
        : NonClientView(),
          container_(container),
          window_delegate_(NULL),
          close_button_(new ChromeViews::Button),
          location_bar_(NULL),
          show_throbber_(false),
          current_throbber_frame_(-1),
          toolbar_model_(container) {
  InitClass();
  if (owner->profile()->IsOffTheRecord()) {
    resources_.reset(new OTRWindowResources);
  } else {
    if (win_util::ShouldUseVistaFrame()) {
      resources_.reset(new VistaWindowResources);
    } else {
      resources_.reset(new XPWindowResources);
    }
  }

  close_button_->SetImage(ChromeViews::Button::BS_NORMAL,
      resources_->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON));
  close_button_->SetImage(ChromeViews::Button::BS_HOT,
      resources_->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_H));
  close_button_->SetImage(ChromeViews::Button::BS_PUSHED,
      resources_->GetPartBitmap(FRAME_CLOSE_BUTTON_ICON_P));
  close_button_->SetImageAlignment(ChromeViews::Button::ALIGN_CENTER,
                                   ChromeViews::Button::ALIGN_MIDDLE);
  close_button_->SetListener(this, 0);
  AddChildView(close_button_);

  // Note: we don't need for a controller because no input event will be ever
  // processed from a constrained window.
  location_bar_ = new LocationBarView(owner->profile(),
                                      NULL,
                                      &toolbar_model_,
                                      this,
                                      true);
  AddChildView(location_bar_);
}

ConstrainedWindowNonClientView::~ConstrainedWindowNonClientView() {
}

void ConstrainedWindowNonClientView::UpdateLocationBar() {
  if (ShouldDisplayURLField()) {
    std::wstring url_spec;
    TabContents* tab = container_->constrained_contents();
    url_spec = gfx::ElideUrl(tab->GetURL(), 
        ChromeFont(), 
        0,
        tab->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages));
    std::wstring ev_text, ev_tooltip_text;
    tab->GetSSLEVText(&ev_text, &ev_tooltip_text),
    location_bar_->Update(NULL);
  }
}

bool ConstrainedWindowNonClientView::ShouldDisplayURLField() const {
  // If the dialog is not fully initialized, default to showing the URL field.
  if (!container_ || !container_->owner() || !container_->owner()->delegate())
    return true;

  return !container_->is_dialog() &&
      container_->owner()->delegate()->ShouldDisplayURLField();
}

int ConstrainedWindowNonClientView::CalculateTitlebarHeight() const {
  int height;
  if (window_delegate_ && window_delegate_->ShouldShowWindowTitle()) {
    height = kTitleTopOffset + resources_->GetTitleFont().height() +
        kTitleBottomSpacing;
  } else {
    height = kNoTitleTopSpacing;
  }

  return height;
}

int ConstrainedWindowNonClientView::CalculateNonClientHeight(
    bool with_url_field) const {
  int r = CalculateTitlebarHeight();

  if (with_url_field) {
    CSize s;
    location_bar_->GetPreferredSize(&s);
    r += s.cy;
  }
  return r;
}

gfx::Rect ConstrainedWindowNonClientView::CalculateWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds,
    bool with_url_field) const {
  int non_client_height = CalculateNonClientHeight(with_url_field);
  gfx::Rect window_bounds = client_bounds;
  window_bounds.set_width(
      window_bounds.width() + 2 * kWindowHorizontalBorderSize);
  window_bounds.set_height(
      window_bounds.height() + non_client_height + kWindowVerticalBorderSize);
  window_bounds.set_x(
      std::max(0, window_bounds.x() - kWindowHorizontalBorderSize));
  window_bounds.set_y(std::max(0, window_bounds.y() - non_client_height));
  return window_bounds;
}

void ConstrainedWindowNonClientView::UpdateWindowTitle() {
  SchedulePaint(title_bounds_.ToRECT(), false);
  UpdateLocationBar();
}

void ConstrainedWindowNonClientView::SetShowThrobber(bool show_throbber) {
  show_throbber_ = show_throbber;

  if (show_throbber) {
    if (!throbber_timer_.IsRunning())
      throbber_timer_.Start(
          TimeDelta::FromMilliseconds(kThrobberFrameTimeMs), this,
          &ConstrainedWindowNonClientView::UpdateThrobber);
  } else {
    if (throbber_timer_.IsRunning()) {
      throbber_timer_.Stop();
      UpdateThrobber();
    }
  }

  Layout();
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView, ChromeViews::NonClientView implementation:

gfx::Rect ConstrainedWindowNonClientView::CalculateClientAreaBounds(
    int width,
    int height) const {
  int non_client_height = CalculateNonClientHeight(ShouldDisplayURLField());
  return gfx::Rect(kWindowHorizontalBorderSize, non_client_height,
      std::max(0, width - (2 * kWindowHorizontalBorderSize)),
      std::max(0, height - non_client_height - kWindowVerticalBorderSize));
}

gfx::Size ConstrainedWindowNonClientView::CalculateWindowSizeForClientSize(
    int width,
    int height) const {
  // This is only used for truly constrained windows, which does not include
  // popups generated from a user gesture since those are detached immediately.
  gfx::Rect window_bounds =
      CalculateWindowBoundsForClientBounds(gfx::Rect(0, 0, width, height),
                                           ShouldDisplayURLField());
  return window_bounds.size();
}

CPoint ConstrainedWindowNonClientView::GetSystemMenuPoint() const {
  CPoint system_menu_point(icon_bounds_.x(), icon_bounds_.bottom());
  MapWindowPoints(container_->GetHWND(), HWND_DESKTOP, &system_menu_point, 1);
  return system_menu_point;
}

int ConstrainedWindowNonClientView::NonClientHitTest(const gfx::Point& point) {
  CRect bounds;
  CPoint test_point = point.ToPOINT();

  // First see if it's within the grow box area, since that overlaps the client
  // bounds.
  int component = container_->client_view()->NonClientHitTest(point);
  if (component != HTNOWHERE)
    return component;

  // Then see if the point is within any of the window controls.
  close_button_->GetBounds(&bounds);
  if (bounds.PtInRect(test_point))
    return HTCLOSE;
  bounds = icon_bounds_.ToRECT();
  if (bounds.PtInRect(test_point))
    return HTSYSMENU;

  component = GetHTComponentForFrame(point, kResizeAreaSize,
                                     kResizeAreaCornerSize,
                                     kResizeAreaNorthSize,
                                     window_delegate_->CanResize());
  if (component == HTNOWHERE) {
    // Finally fall back to the caption.
    GetBounds(&bounds, APPLY_MIRRORING_TRANSFORMATION);
    if (bounds.PtInRect(test_point))
      component = HTCAPTION;
    // Otherwise, the point is outside the window's bounds.
  }
  return component;
}

void ConstrainedWindowNonClientView::GetWindowMask(const gfx::Size& size,
                                                   gfx::Path* window_mask) {
  DCHECK(window_mask);

  // Redefine the window visible region for the new size.
  window_mask->moveTo(0, 3);
  window_mask->lineTo(1, 2);
  window_mask->lineTo(1, 1);
  window_mask->lineTo(2, 1);
  window_mask->lineTo(3, 0);

  window_mask->lineTo(SkIntToScalar(size.width() - 3), 0);
  window_mask->lineTo(SkIntToScalar(size.width() - 2), 1);
  window_mask->lineTo(SkIntToScalar(size.width() - 1), 1);
  window_mask->lineTo(SkIntToScalar(size.width() - 1), 2);
  window_mask->lineTo(SkIntToScalar(size.width()), 3);

  window_mask->lineTo(SkIntToScalar(size.width()),
                      SkIntToScalar(size.height()));
  window_mask->lineTo(0, SkIntToScalar(size.height()));
  window_mask->close();
}

void ConstrainedWindowNonClientView::EnableClose(bool enable) {
  close_button_->SetEnabled(enable);
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView, ChromeViews::View implementation:

void ConstrainedWindowNonClientView::Paint(ChromeCanvas* canvas) {
  PaintFrameBorder(canvas);
  PaintTitleBar(canvas);
}

void ConstrainedWindowNonClientView::Layout() {
  bool should_display_url_field = false;
  if (location_bar_) {
    should_display_url_field = ShouldDisplayURLField();
    location_bar_->SetVisible(should_display_url_field);
  }

  int location_bar_height = 0;
  CSize ps;
  if (should_display_url_field) {
    location_bar_->GetPreferredSize(&ps);
    location_bar_height = ps.cy;
  }

  close_button_->GetPreferredSize(&ps);
  close_button_->SetBounds(GetWidth() - ps.cx - kWindowControlsRightOffset,
                           kWindowControlsTopOffset, ps.cx, ps.cy);

  int titlebar_height = CalculateTitlebarHeight();
  if (window_delegate_) {
    if (show_throbber_) {
      int icon_y = (titlebar_height - kWindowIconSize) / 2;
      icon_bounds_.SetRect(kWindowLeftSpacing, icon_y, 0, 0);
      icon_bounds_.set_width(kWindowIconSize);
      icon_bounds_.set_height(kWindowIconSize);
    } else {
      icon_bounds_.SetRect(0, 0, 0, 0);
    }

    if (window_delegate_->ShouldShowWindowTitle()) {
      int spacing = kWindowLeftSpacing;
      int title_right = close_button_->GetX() - spacing;
      int title_left = icon_bounds_.right() + spacing;
      title_bounds_.SetRect(title_left, kTitleTopOffset,
                            title_right - title_left,
                            resources_->GetTitleFont().height());
    }
  }

  client_bounds_ = CalculateClientAreaBounds(GetWidth(), GetHeight());
  if (should_display_url_field) {
    location_bar_->SetBounds(client_bounds_.x() - kLocationBarOffset,
                             client_bounds_.y() - location_bar_height - 
                             kLocationBarSpacing,
                             client_bounds_.width() + kLocationBarOffset * 2,
                             location_bar_height);
    location_bar_->Layout();
  }
  container_->client_view()->SetBounds(client_bounds_.ToRECT());
}

void ConstrainedWindowNonClientView::GetPreferredSize(CSize* out) {
  DCHECK(out);
  container_->client_view()->GetPreferredSize(out);
  out->cx += 2 * kWindowHorizontalBorderSize;
  out->cy += CalculateNonClientHeight(ShouldDisplayURLField()) +
      kWindowVerticalBorderSize;
}

void ConstrainedWindowNonClientView::ViewHierarchyChanged(bool is_add,
                                                          View *parent,
                                                          View *child) {
  if (is_add && GetViewContainer()) {
    // Add our Client View as we are added to the ViewContainer so that if we
    // are subsequently resized all the parent-child relationships are
    // established.
    if (is_add && GetViewContainer() && child == this)
      AddChildView(container_->client_view());
    if (location_bar_ && !location_bar_->IsInitialized())
      location_bar_->Init();
  }
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView, ChromeViews::BaseButton::Button
//     implementation:

void ConstrainedWindowNonClientView::ButtonPressed(
    ChromeViews::BaseButton* sender) {
  if (sender == close_button_)
    container_->ExecuteSystemMenuCommand(SC_CLOSE);
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView, LocationBarView::Delegate
//     implementation:
TabContents* ConstrainedWindowNonClientView::GetTabContents() {
  return container_->owner();
}

void ConstrainedWindowNonClientView::OnInputInProgress(bool in_progress) {
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowNonClientView, private:

void ConstrainedWindowNonClientView::UpdateThrobber() {
  if (show_throbber_)
    current_throbber_frame_ = ++current_throbber_frame_ % throbber_frame_count_;
  else
    current_throbber_frame_ = -1;

  SchedulePaint();
}

void ConstrainedWindowNonClientView::PaintFrameBorder(ChromeCanvas* canvas) {
  int width = GetWidth();
  int height = GetHeight();

  SkBitmap* top_left_corner = resources_->GetPartBitmap(FRAME_TOP_LEFT_CORNER);
  SkBitmap* top_right_corner =
      resources_->GetPartBitmap(FRAME_TOP_RIGHT_CORNER);
  SkBitmap* top_edge = resources_->GetPartBitmap(FRAME_TOP_CENTER);
  SkBitmap* right_edge = resources_->GetPartBitmap(FRAME_RIGHT_SIDE);
  SkBitmap* left_edge = resources_->GetPartBitmap(FRAME_LEFT_SIDE);
  SkBitmap* bottom_left_corner =
      resources_->GetPartBitmap(FRAME_BOTTOM_LEFT_CORNER);
  SkBitmap* bottom_right_corner =
      resources_->GetPartBitmap(FRAME_BOTTOM_RIGHT_CORNER);
  SkBitmap* bottom_edge = resources_->GetPartBitmap(FRAME_BOTTOM_CENTER);

  // Top.
  canvas->DrawBitmapInt(*top_left_corner, 0, 0);
  canvas->TileImageInt(*top_edge, top_left_corner->width(), 0,
                       width - top_right_corner->width(), top_edge->height());
  canvas->DrawBitmapInt(
      *top_right_corner, width - top_right_corner->width(), 0);

  // Right.
  int top_stack_height = top_right_corner->height();
  canvas->TileImageInt(*right_edge, width - right_edge->width(),
                       top_stack_height, right_edge->width(),
                       height - top_stack_height -
                           bottom_right_corner->height());

  // Bottom.
  canvas->DrawBitmapInt(*bottom_right_corner,
                        width - bottom_right_corner->width(),
                        height - bottom_right_corner->height());
  canvas->TileImageInt(*bottom_edge, bottom_left_corner->width(),
                       height - bottom_edge->height(),
                       width - bottom_left_corner->width() -
                           bottom_right_corner->width(),
                       bottom_edge->height());
  canvas->DrawBitmapInt(*bottom_left_corner, 0,
                        height - bottom_left_corner->height());

  // Left.
  top_stack_height = top_left_corner->height();
  canvas->TileImageInt(*left_edge, 0, top_stack_height, left_edge->width(),
                       height - top_stack_height -
                           bottom_left_corner->height());

  // Contents Border.
  gfx::Rect border_bounds = client_bounds_;
  border_bounds.Inset(-2, -2);
  canvas->FillRectInt(kContentsBorderShadow, border_bounds.x(),
                      border_bounds.y(), border_bounds.width(),
                      border_bounds.height());

  border_bounds.Inset(1, 1);
  canvas->FillRectInt(kContentsBorderColor, border_bounds.x(),
                      border_bounds.y(), border_bounds.width(),
                      border_bounds.height());
}

void ConstrainedWindowNonClientView::PaintTitleBar(ChromeCanvas* canvas) {
  if (!window_delegate_)
    return;

  if (should_show_throbber())
    PaintThrobber(canvas);

  if (window_delegate_->ShouldShowWindowTitle()) {
    PaintWindowTitle(canvas);
  }
}

void ConstrainedWindowNonClientView::PaintThrobber(ChromeCanvas* canvas) {
  int image_size = throbber_frames_.height();
  int image_offset = current_throbber_frame_ * image_size;
  canvas->DrawBitmapInt(throbber_frames_,
                        image_offset, 0, image_size, image_size,
                        icon_bounds_.x(), icon_bounds_.y(),
                        image_size, image_size,
                        false);
}

void ConstrainedWindowNonClientView::PaintWindowTitle(ChromeCanvas* canvas) {
  canvas->DrawStringInt(container_->GetWindowTitle(),
                        resources_->GetTitleFont(),
                        resources_->GetTitleColor(), title_bounds_.x(),
                        title_bounds_.y(), title_bounds_.width(),
                        title_bounds_.height());
}

// static
void ConstrainedWindowNonClientView::InitClass() {
  static bool initialized = false;
  if (!initialized) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();

    throbber_frames_ = *rb.GetBitmapNamed(IDR_THROBBER);
    DCHECK(throbber_frames_.width() % throbber_frames_.height() == 0);
    throbber_frame_count_ =
        throbber_frames_.width() / throbber_frames_.height();

    initialized = true;
  }
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedTabContentsWindowDelegate

class ConstrainedTabContentsWindowDelegate
    : public ChromeViews::WindowDelegate {
 public:
  explicit ConstrainedTabContentsWindowDelegate(TabContents* contents)
      : contents_(contents),
        contents_view_(NULL) {
  }

  void set_contents_view(ChromeViews::View* contents_view) {
    contents_view_ = contents_view;
  }

  // ChromeViews::WindowDelegate implementation:
  virtual bool CanResize() const {
    return true;
  }
  virtual std::wstring GetWindowTitle() const {
    return contents_->GetTitle();
  }
  virtual bool ShouldShowWindowIcon() const {
    return false;
  }
  virtual SkBitmap GetWindowIcon() {
    return contents_->GetFavIcon();
  }
  virtual ChromeViews::View* GetContentsView() {
    return contents_view_;
  }

 private:
  TabContents* contents_;
  ChromeViews::View* contents_view_;

  DISALLOW_EVIL_CONSTRUCTORS(ConstrainedTabContentsWindowDelegate);
};

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowImpl, public:

// The space (in pixels) between minimized pop-ups stacked horizontally and
// vertically.
static const int kPopupRepositionOffset = 5;
static const int kConstrainedWindowEdgePadding = 10;

ConstrainedWindowImpl::~ConstrainedWindowImpl() {
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowImpl, ConstrainedWindow implementation:

ConstrainedWindowNonClientView* ConstrainedWindowImpl::non_client_view() {
  return static_cast<ConstrainedWindowNonClientView*>(non_client_view_);
}

void ConstrainedWindowImpl::ActivateConstrainedWindow() {
  if (CanDetach()) {
    // Detachable pop-ups are torn out as soon as the window is activated.
    Detach();
    return;
  }

  // Other pop-ups are simply moved to the front of the z-order.
  SetWindowPos(HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);

  // Store the focus of our parent focus manager so we can restore it when we
  // close.
  ChromeViews::FocusManager* focus_manager =
      ChromeViews::FocusManager::GetFocusManager(GetHWND());
  DCHECK(focus_manager);
  focus_manager = focus_manager->GetParentFocusManager();
  if (focus_manager) {
    // We could not have a parent focus manager if the ConstrainedWindow is
    // displayed in a tab that is not currently selected.
    // TODO(jcampan): we should store the ConstrainedWindow active events in
    // that case and replay them when the WebContents becomes selected.
    focus_manager->StoreFocusedView();

    if (constrained_contents_) {
      // We contain another window, let's assume it knows how to process the
      // focus and let's focus it.
      // TODO(jcampan): so far this case is the WebContents case. We need to
      // better find whether the inner window should get focus.
      ::SetFocus(constrained_contents_->GetContainerHWND());
    } else {
      // Give our window the focus so we get keyboard messages.
      ::SetFocus(GetHWND());
    }
  }
}

void ConstrainedWindowImpl::CloseConstrainedWindow() {
  // Broadcast to all observers of NOTIFY_CWINDOW_CLOSED.
  // One example of such an observer is AutomationCWindowTracker in the
  // automation component.
  NotificationService::current()->Notify(NOTIFY_CWINDOW_CLOSED,
                                         Source<ConstrainedWindow>(this),
                                         NotificationService::NoDetails());

  Close();
}

void ConstrainedWindowImpl::RepositionConstrainedWindowTo(
    const gfx::Point& anchor_point) {
  anchor_point_ = anchor_point;
  ResizeConstrainedTitlebar();
}

bool ConstrainedWindowImpl::IsSuppressedConstrainedWindow() const {
  return !is_dialog_;
}

void ConstrainedWindowImpl::WasHidden() {
  if (constrained_contents_)
    constrained_contents_->WasHidden();
}

void ConstrainedWindowImpl::DidBecomeSelected() {
  if (constrained_contents_)
    constrained_contents_->DidBecomeSelected();
}

std::wstring ConstrainedWindowImpl::GetWindowTitle() const {
  // TODO(erg): (http://b/1085485) Need to decide if we what we want long term
  // in our popup window titles.
  std::wstring page_title;
  if (window_delegate())
    page_title = window_delegate()->GetWindowTitle();

  std::wstring display_title;
  bool title_set = false;
  if (constrained_contents_) {
    // TODO(erg): This is in the process of being translated now, but we need
    // to do UI work so that display_title is "IDS_BLOCKED_POPUP - <page
    // title>".
    display_title = l10n_util::GetString(IDS_BLOCKED_POPUP);
    title_set = true;
  }

  if (!title_set) {
    if (page_title.empty())
      display_title = L"Untitled";
    else
      display_title = page_title;
  }

  return display_title;
}

void ConstrainedWindowImpl::UpdateWindowTitle() {
  UpdateUI(TabContents::INVALIDATE_TITLE);
}

const gfx::Rect& ConstrainedWindowImpl::GetCurrentBounds() const {
  return current_bounds_;
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowImpl, TabContentsDelegate implementation:

void ConstrainedWindowImpl::NavigationStateChanged(
    const TabContents* source,
    unsigned int changed_flags) {
  UpdateUI(changed_flags);
}

void ConstrainedWindowImpl::ReplaceContents(TabContents* source,
                                            TabContents* new_contents) {
  source->set_delegate(NULL);

  constrained_contents_ = new_contents;
  constrained_contents_->set_delegate(this);
  UpdateUI(TabContents::INVALIDATE_EVERYTHING);
}

void ConstrainedWindowImpl::AddNewContents(TabContents* source,
                                           TabContents* new_contents,
                                           WindowOpenDisposition disposition,
                                           const gfx::Rect& initial_pos,
                                           bool user_gesture) {
  // Pass this to the delegate, since we can't open new tabs in the Constrained
  // Window, they are sent up to the browser to open as new tabs.
  owner_->AddNewContents(
      this, new_contents, disposition, initial_pos, user_gesture);
}

void ConstrainedWindowImpl::ActivateContents(TabContents* contents) {
  // Ask the delegate's (which is a TabContents) own TabContentsDelegate to
  // activate itself...
  owner_->delegate()->ActivateContents(owner_);

  // Set as the foreground constrained window.
  ActivateConstrainedWindow();
}

void ConstrainedWindowImpl::OpenURLFromTab(
    TabContents* source,
    const GURL& url,
    WindowOpenDisposition disposition,
    PageTransition::Type transition,
    const std::string& override_encoding) {
  // We ignore source right now.
  owner_->OpenURL(this, url, disposition, transition);
}

void ConstrainedWindowImpl::LoadingStateChanged(TabContents* source) {
  // TODO(beng): (http://b/1085543) Implement a throbber for the Constrained
  //             Window.
  UpdateUI(TabContents::INVALIDATE_EVERYTHING);
  non_client_view()->SetShowThrobber(source->is_loading());
}

void ConstrainedWindowImpl::NavigateToPage(TabContents* source,
                                           const GURL& url,
                                           PageTransition::Type transition) {
  UpdateUI(TabContents::INVALIDATE_EVERYTHING);
}

void ConstrainedWindowImpl::SetTitlebarVisibilityPercentage(double percentage) {
  titlebar_visibility_ = percentage;
  ResizeConstrainedTitlebar();
}

void ConstrainedWindowImpl::StartSuppressedAnimation() {
  animation_.reset(new ConstrainedWindowAnimation(this));
  animation_->Start();
}

void ConstrainedWindowImpl::CloseContents(TabContents* source) {
  Close();
}

void ConstrainedWindowImpl::MoveContents(TabContents* source,
                                         const gfx::Rect& pos) {
  if (!IsSuppressedConstrainedWindow())
    SetWindowBounds(pos);
  else
    ResizeConstrainedWindow(pos.width(), pos.height());
}

bool ConstrainedWindowImpl::IsPopup(TabContents* source) {
  return true;
}

TabContents* ConstrainedWindowImpl::GetConstrainingContents(
    TabContents* source) {
  return owner_;
}

void ConstrainedWindowImpl::ToolbarSizeChanged(TabContents* source, 
                                             bool finished) {
  // We don't control the layout of anything that could be animating, 
  // so do nothing.
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowImpl, private:

ConstrainedWindowImpl::ConstrainedWindowImpl(
    TabContents* owner,
    ChromeViews::WindowDelegate* window_delegate,
    TabContents* constrained_contents)
    : CustomFrameWindow(window_delegate,
                        new ConstrainedWindowNonClientView(this, owner)),
      contents_window_delegate_(window_delegate),
      constrained_contents_(constrained_contents),
      titlebar_visibility_(0.0) {
  Init(owner);
}

ConstrainedWindowImpl::ConstrainedWindowImpl(
    TabContents* owner,
    ChromeViews::WindowDelegate* window_delegate) 
    : CustomFrameWindow(window_delegate,
                        new ConstrainedWindowNonClientView(this, owner)),
      constrained_contents_(NULL) {
  Init(owner);
}

void ConstrainedWindowImpl::Init(TabContents* owner) {
  owner_ = owner;
  focus_restoration_disabled_ = false;
  is_dialog_ = false;
  contents_container_ = NULL;
  set_window_style(WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION |
                   WS_THICKFRAME | WS_SYSMENU);
  set_focus_on_creation(false);
}

void ConstrainedWindowImpl::ResizeConstrainedTitlebar() {
  DCHECK(constrained_contents_)
      << "ResizeConstrainedTitlebar() is only valid for web popups";
  // If we represent a web popup and we were not opened as the result of a
  // user gesture, we override the position specified in |initial_bounds| to
  // place ourselves at the bottom right of the parent HWND.
  CRect this_bounds;
  GetClientRect(&this_bounds);

  ResizeConstrainedWindow(this_bounds.Width(), this_bounds.Height());
}

void ConstrainedWindowImpl::ResizeConstrainedWindow(int width, int height) {
  DCHECK(constrained_contents_)
      << "ResizeConstrainedTitlebar() is only valid for web popups";

  // Make sure we aren't larger then our containing tab contents.
  if (width > anchor_point_.x())
    width = anchor_point_.x();

  // Determine the height of the title bar of a constrained window, so
  // that we can offset by that much vertically if necessary...
  int titlebar_height = non_client_view()->CalculateTitlebarHeight();

  int visible_titlebar_pixels =
      static_cast<int>(titlebar_height * titlebar_visibility_);

  int x = anchor_point_.x() - width;
  int y = anchor_point_.y() - visible_titlebar_pixels;

  // NOTE: Previously, we passed in |visible_titlebar_pixels| instead
  // of |height|. This didn't actually change any of the properties of
  // the child HWNDS. If we ever set the |anchor_point_| intelligently
  // so that it deals with scrollbars, we'll need to change height
  // back to |visible_titlebar_pixels| and find a different solution,
  // otherwise part of the window will be displayed over the scrollbar.
  SetWindowPos(NULL, x, y, width, height,
               SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW);
}

void ConstrainedWindowImpl::InitAsDialog(const gfx::Rect& initial_bounds) {
  is_dialog_ = true;
  non_client_view()->set_window_delegate(window_delegate());
  CustomFrameWindow::Init(owner_->GetContainerHWND(), initial_bounds);
  ActivateConstrainedWindow();
}

void ConstrainedWindowImpl::InitWindowForContents(
    TabContents* constrained_contents,
    ConstrainedTabContentsWindowDelegate* delegate) {
  constrained_contents_ = constrained_contents;
  constrained_contents_->set_delegate(this);
  contents_container_ = new ChromeViews::HWNDView;
  delegate->set_contents_view(contents_container_);
  non_client_view()->set_window_delegate(contents_window_delegate_.get());
}

void ConstrainedWindowImpl::InitSizeForContents(
    const gfx::Rect& initial_bounds) {
  CustomFrameWindow::Init(owner_->GetContainerHWND(), initial_bounds);
  contents_container_->Attach(constrained_contents_->GetContainerHWND());

  constrained_contents_->SizeContents(
      gfx::Size(contents_container_->GetWidth(),
                contents_container_->GetHeight()));
  current_bounds_ = initial_bounds;

  // Note that this is HWND_TOP, not HWND_TOPMOST... this is important
  // because otherwise the window will not be visible on top of the
  // RenderWidgetHostView!
  win_util::SetChildBounds(GetHWND(), GetParent(), HWND_TOP, initial_bounds,
                           kConstrainedWindowEdgePadding, 0);
}

bool ConstrainedWindowImpl::CanDetach() const {
  // Constrained TabContentses can be detached, dialog boxes can't.
  return constrained_contents_ ? true : false;
}

void ConstrainedWindowImpl::Detach() {
  DCHECK(CanDetach());
  // Tell the container not to restore focus to whatever view was focused last,
  // since this will interfere with the new window activation in the case where
  // a constrained window is destroyed by being detached.
  focus_restoration_disabled_ = true;

  // Detach the HWND immediately.
  contents_container_->Detach();
  contents_container_ = NULL;

  // To try and create as seamless as possible a popup experience, web pop-ups
  // are automatically detached when the user interacts with them. We can
  // dial this back if we feel this is too much.

  // The detached contents "should" be re-parented by the delegate's
  // DetachContents, but we clear the delegate pointing to us just in case.
  constrained_contents_->set_delegate(NULL);

  // We want to detach the constrained window at the same position on screen
  // as the constrained window, so we need to get its screen bounds.
  CRect constrained_window_bounds;
  GetBounds(&constrained_window_bounds, true);

  // Obtain the constrained TabContents' size from its HWND...
  CRect bounds;
  ::GetWindowRect(constrained_contents_->GetContainerHWND(), &bounds);

  // ... but overwrite its screen position with the screen position of its
  // containing ConstrainedWindowImpl. We do this because the code called by
  // |DetachContents| assumes the bounds contains position and size information
  // similar to what is sent when a popup is not suppressed and must be opened,
  // i.e. the position is the screen position of the top left of the detached
  // popup window, and the size is the size of the content area.
  bounds.SetRect(constrained_window_bounds.left, constrained_window_bounds.top,
                 constrained_window_bounds.left + bounds.Width(),
                 constrained_window_bounds.top + bounds.Height());

  // Save the cursor position so that we know where to send a mouse message
  // when the new detached window is created.
  CPoint cursor_pos;
  ::GetCursorPos(&cursor_pos);
  gfx::Point screen_point(cursor_pos.x, cursor_pos.y);

  // Determine what aspect of the constrained frame was clicked on, so that we
  // can continue the mouse move on this aspect of the detached frame.
  int frame_component = static_cast<int>(OnNCHitTest(screen_point.ToPOINT()));

  // Finally we actually detach the TabContents, and then clean up.
  owner_->DetachContents(this, constrained_contents_, gfx::Rect(bounds),
                         screen_point, frame_component);
  constrained_contents_ = NULL;
  Close();
}

void ConstrainedWindowImpl::SetWindowBounds(const gfx::Rect& bounds) {
  // Note: SetChildBounds ensures that the constrained window is constrained
  //       to the bounds of its parent, however there remains a bug where the
  //       window is positioned incorrectly when the outer window is opened on
  //       a monitor that has negative coords (e.g. secondary monitor to left
  //       of primary, see http://b/issue?id=967905.)
  gfx::Size window_size = non_client_view()->CalculateWindowSizeForClientSize(
      bounds.width(), bounds.height());

  current_bounds_ = bounds;
  current_bounds_.set_width(window_size.width());
  current_bounds_.set_height(window_size.height());
  win_util::SetChildBounds(GetHWND(), GetParent(), NULL, current_bounds_,
                           kConstrainedWindowEdgePadding, 0);
}

void ConstrainedWindowImpl::UpdateUI(unsigned int changed_flags) {
  if (changed_flags & TabContents::INVALIDATE_TITLE)
    non_client_view()->UpdateWindowTitle();
}

////////////////////////////////////////////////////////////////////////////////
// ConstrainedWindowImpl, ChromeViews::HWNDViewContainer overrides:

void ConstrainedWindowImpl::OnDestroy() {
  // We do this here, rather than |Close|, since the window may be destroyed in
  // a way other than by some other component calling Close, e.g. by the native
  // window hierarchy closing. We are guaranteed to receive a WM_DESTROY
  // message regardless of how the window is closed.
  // Note that when we get this message, the focus manager of the
  // ConstrainedWindow has already been destroyed (by the processing of
  // WM_DESTROY in FocusManager).  So the FocusManager we retrieve here is the
  // parent one (the one from the top window).
  ChromeViews::FocusManager* focus_manager =
      ChromeViews::FocusManager::GetFocusManager(GetHWND());
  if (focus_manager) {
    // We may not have a focus manager if:
    // - we are hidden when closed (the TabContent would be detached).
    // - the tab has been closed and we are closed as a result.
    // TODO(jcampan): when hidden, we should modify the stored focus of the tab
    // so when it becomes visible again we retrieve the focus appropriately.
    if (!focus_restoration_disabled_)
      focus_manager->RestoreFocusedView();
  }

  // If we have a child TabContents, we need to unhook it here so that it is
  // not automatically WM_DESTROYed by virtue of the fact that it is part of
  // our Window hierarchy. Rather, it needs to be destroyed just like top level
  // TabContentses are: from OnMsgCloseACK in RenderWidgetHost. So we hide the
  // TabContents and sever the parent relationship now. Note the GetParent
  // check so that we don't hide and re-parent TabContentses that have been
  // detached and re-attached into a new top level browser window via a user
  // drag action.
  if (constrained_contents_ &&
      ::GetParent(constrained_contents_->GetContainerHWND()) == GetHWND()) {
    ::ShowWindow(constrained_contents_->GetContainerHWND(), SW_HIDE);
    ::SetParent(constrained_contents_->GetContainerHWND(), NULL);
  }

  // Make sure we call super so that it can do its cleanup.
  Window::OnDestroy();
}

void ConstrainedWindowImpl::OnFinalMessage(HWND window) {
  // Tell our constraining TabContents that we've gone so it can update its
  // list.
  owner_->WillClose(this);
  if (constrained_contents_) {
    constrained_contents_->CloseContents();
    constrained_contents_ = NULL;
  }

  HWNDViewContainer::OnFinalMessage(window);
}

void ConstrainedWindowImpl::OnGetMinMaxInfo(LPMINMAXINFO mm_info) {
  // Override this function to set the maximize area as the client area of the
  // containing window.
  CRect parent_rect;
  ::GetClientRect(GetParent(), &parent_rect);

  mm_info->ptMaxSize.x = parent_rect.Width();
  mm_info->ptMaxSize.y = parent_rect.Height();
  mm_info->ptMaxPosition.x = parent_rect.left;
  mm_info->ptMaxPosition.y = parent_rect.top;
}

LRESULT ConstrainedWindowImpl::OnMouseActivate(HWND window,
                                               UINT hittest_code,
                                               UINT message) {
  // We need to store this value before we call ActivateConstrainedWindow()
  // since the window may be detached and so this function will return false
  // afterwards.
  bool can_detach = CanDetach();

  // We only detach the window if the user clicked on the title bar. That
  // way, users can click inside the contents of legitimate popups obtained
  // with a mouse gesture.
  if (hittest_code != HTCLIENT && hittest_code != HTNOWHERE &&
      hittest_code != HTCLOSE) {
    ActivateConstrainedWindow();
  } else {
    // If the user did not click on the title bar, don't stop message
    // propagation.
    can_detach = false;
  }

  // If the popup can be detached, then we tell the parent window not to
  // activate since we will already have adjusted activation ourselves. We also
  // do _not_ eat the event otherwise the user will have to click again to
  // interact with the popup.
  return can_detach ? MA_NOACTIVATEANDEAT : MA_ACTIVATE;
}

void ConstrainedWindowImpl::OnWindowPosChanged(WINDOWPOS* window_pos) {
  // If the window was moved or sized, tell the owner.
  if (!(window_pos->flags & SWP_NOMOVE) || !(window_pos->flags & SWP_NOSIZE))
    owner_->DidMoveOrResize(this);
  SetMsgHandled(FALSE);
}

///////////////////////////////////////////////////////////////////////////////
// ConstrainedWindow, public:

// static
ConstrainedWindow* ConstrainedWindow::CreateConstrainedDialog(
    TabContents* parent,
    const gfx::Rect& initial_bounds,
    ChromeViews::View* contents_view,
    ChromeViews::WindowDelegate* window_delegate) {
  ConstrainedWindowImpl* window = new ConstrainedWindowImpl(parent,
                                                            window_delegate);
  window->InitAsDialog(initial_bounds);
  return window;
}

// static
ConstrainedWindow* ConstrainedWindow::CreateConstrainedPopup(
    TabContents* parent,
    const gfx::Rect& initial_bounds,
    TabContents* constrained_contents) {
  ConstrainedTabContentsWindowDelegate* d =
      new ConstrainedTabContentsWindowDelegate(constrained_contents);
  ConstrainedWindowImpl* window =
      new ConstrainedWindowImpl(parent, d, constrained_contents);
  window->InitWindowForContents(constrained_contents, d);

  gfx::Rect window_bounds = window->non_client_view()->
      CalculateWindowBoundsForClientBounds(
          initial_bounds,
          parent->delegate()->ShouldDisplayURLField());

  window->InitSizeForContents(window_bounds);

  // This is a constrained popup window and thus we need to animate it in.
  window->StartSuppressedAnimation();

  return window;
}