Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / ui / message_center / views / message_center_view.cc
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/message_center/views/message_center_view.h"
6
7 #include <list>
8 #include <map>
9
10 #include "base/command_line.h"
11 #include "base/memory/weak_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/stl_util.h"
14 #include "ui/base/l10n/l10n_util.h"
15 #include "ui/gfx/animation/multi_animation.h"
16 #include "ui/gfx/animation/slide_animation.h"
17 #include "ui/gfx/canvas.h"
18 #include "ui/gfx/insets.h"
19 #include "ui/gfx/rect.h"
20 #include "ui/gfx/size.h"
21 #include "ui/message_center/message_center.h"
22 #include "ui/message_center/message_center_style.h"
23 #include "ui/message_center/message_center_switches.h"
24 #include "ui/message_center/message_center_tray.h"
25 #include "ui/message_center/message_center_types.h"
26 #include "ui/message_center/views/message_center_button_bar.h"
27 #include "ui/message_center/views/message_view.h"
28 #include "ui/message_center/views/message_view_context_menu_controller.h"
29 #include "ui/message_center/views/notification_view.h"
30 #include "ui/message_center/views/notifier_settings_view.h"
31 #include "ui/resources/grit/ui_resources.h"
32 #include "ui/strings/grit/ui_strings.h"
33 #include "ui/views/animation/bounds_animator.h"
34 #include "ui/views/animation/bounds_animator_observer.h"
35 #include "ui/views/background.h"
36 #include "ui/views/border.h"
37 #include "ui/views/controls/button/button.h"
38 #include "ui/views/controls/label.h"
39 #include "ui/views/controls/scroll_view.h"
40 #include "ui/views/controls/scrollbar/overlay_scroll_bar.h"
41 #include "ui/views/layout/box_layout.h"
42 #include "ui/views/layout/fill_layout.h"
43 #include "ui/views/widget/widget.h"
44
45 namespace message_center {
46
47 namespace {
48
49 const SkColor kNoNotificationsTextColor = SkColorSetRGB(0xb4, 0xb4, 0xb4);
50 #if defined(OS_LINUX) && defined(OS_CHROMEOS)
51 const SkColor kTransparentColor = SkColorSetARGB(0, 0, 0, 0);
52 #endif
53 const int kAnimateClearingNextNotificationDelayMS = 40;
54
55 const int kDefaultAnimationDurationMs = 120;
56 const int kDefaultFrameRateHz = 60;
57 }  // namespace
58
59 class NoNotificationMessageView : public views::View {
60  public:
61   NoNotificationMessageView();
62   ~NoNotificationMessageView() override;
63
64   // Overridden from views::View.
65   gfx::Size GetPreferredSize() const override;
66   int GetHeightForWidth(int width) const override;
67   void Layout() override;
68
69  private:
70   views::Label* label_;
71
72   DISALLOW_COPY_AND_ASSIGN(NoNotificationMessageView);
73 };
74
75 NoNotificationMessageView::NoNotificationMessageView() {
76   label_ = new views::Label(l10n_util::GetStringUTF16(
77       IDS_MESSAGE_CENTER_NO_MESSAGES));
78   label_->SetAutoColorReadabilityEnabled(false);
79   label_->SetEnabledColor(kNoNotificationsTextColor);
80   // Set transparent background to ensure that subpixel rendering
81   // is disabled. See crbug.com/169056
82 #if defined(OS_LINUX) && defined(OS_CHROMEOS)
83   label_->SetBackgroundColor(kTransparentColor);
84 #endif
85   AddChildView(label_);
86 }
87
88 NoNotificationMessageView::~NoNotificationMessageView() {
89 }
90
91 gfx::Size NoNotificationMessageView::GetPreferredSize() const {
92   return gfx::Size(kMinScrollViewHeight, label_->GetPreferredSize().width());
93 }
94
95 int NoNotificationMessageView::GetHeightForWidth(int width) const {
96   return kMinScrollViewHeight;
97 }
98
99 void NoNotificationMessageView::Layout() {
100   int text_height = label_->GetHeightForWidth(width());
101   int margin = (height() - text_height) / 2;
102   label_->SetBounds(0, margin, width(), text_height);
103 }
104
105 // Displays a list of messages for rich notifications. Functions as an array of
106 // MessageViews and animates them on transitions. It also supports
107 // repositioning.
108 class MessageListView : public views::View,
109                         public views::BoundsAnimatorObserver {
110  public:
111   explicit MessageListView(MessageCenterView* message_center_view,
112                            bool top_down);
113   ~MessageListView() override;
114
115   void AddNotificationAt(MessageView* view, int i);
116   void RemoveNotification(MessageView* view);
117   void UpdateNotification(MessageView* view, const Notification& notification);
118   void SetRepositionTarget(const gfx::Rect& target_rect);
119   void ResetRepositionSession();
120   void ClearAllNotifications(const gfx::Rect& visible_scroll_rect);
121
122  protected:
123   // Overridden from views::View.
124   void Layout() override;
125   gfx::Size GetPreferredSize() const override;
126   int GetHeightForWidth(int width) const override;
127   void PaintChildren(gfx::Canvas* canvas,
128                      const views::CullSet& cull_set) override;
129   void ReorderChildLayers(ui::Layer* parent_layer) override;
130
131   // Overridden from views::BoundsAnimatorObserver.
132   void OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) override;
133   void OnBoundsAnimatorDone(views::BoundsAnimator* animator) override;
134
135  private:
136   bool IsValidChild(const views::View* child) const;
137   void DoUpdateIfPossible();
138
139   // Animates all notifications below target upwards to align with the top of
140   // the last closed notification.
141   void AnimateNotificationsBelowTarget();
142   // Animates all notifications above target downwards to align with the top of
143   // the last closed notification.
144   void AnimateNotificationsAboveTarget();
145
146   // Schedules animation for a child to the specified position. Returns false
147   // if |child| will disappear after the animation.
148   bool AnimateChild(views::View* child, int top, int height);
149
150   // Animate clearing one notification.
151   void AnimateClearingOneNotification();
152   MessageCenterView* message_center_view() const {
153     return message_center_view_;
154   }
155
156   MessageCenterView* message_center_view_;  // Weak reference.
157   // The top position of the reposition target rectangle.
158   int reposition_top_;
159   int fixed_height_;
160   bool has_deferred_task_;
161   bool clear_all_started_;
162   bool top_down_;
163   std::set<views::View*> adding_views_;
164   std::set<views::View*> deleting_views_;
165   std::set<views::View*> deleted_when_done_;
166   std::list<views::View*> clearing_all_views_;
167   scoped_ptr<views::BoundsAnimator> animator_;
168   base::WeakPtrFactory<MessageListView> weak_ptr_factory_;
169
170   DISALLOW_COPY_AND_ASSIGN(MessageListView);
171 };
172
173 MessageListView::MessageListView(MessageCenterView* message_center_view,
174                                  bool top_down)
175     : message_center_view_(message_center_view),
176       reposition_top_(-1),
177       fixed_height_(0),
178       has_deferred_task_(false),
179       clear_all_started_(false),
180       top_down_(top_down),
181       weak_ptr_factory_(this) {
182   views::BoxLayout* layout =
183       new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 1);
184   layout->SetDefaultFlex(1);
185   SetLayoutManager(layout);
186
187   // Set the margin to 0 for the layout. BoxLayout assumes the same margin
188   // for top and bottom, but the bottom margin here should be smaller
189   // because of the shadow of message view. Use an empty border instead
190   // to provide this margin.
191   gfx::Insets shadow_insets = MessageView::GetShadowInsets();
192   set_background(views::Background::CreateSolidBackground(
193       kMessageCenterBackgroundColor));
194   SetBorder(views::Border::CreateEmptyBorder(
195       top_down ? 0 : kMarginBetweenItems - shadow_insets.top(),    /* top */
196       kMarginBetweenItems - shadow_insets.left(),                  /* left */
197       top_down ? kMarginBetweenItems - shadow_insets.bottom() : 0, /* bottom */
198       kMarginBetweenItems - shadow_insets.right() /* right */));
199 }
200
201 MessageListView::~MessageListView() {
202   if (animator_.get())
203     animator_->RemoveObserver(this);
204 }
205
206 void MessageListView::Layout() {
207   if (animator_.get())
208     return;
209
210   gfx::Rect child_area = GetContentsBounds();
211   int top = child_area.y();
212   int between_items =
213       kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
214
215   for (int i = 0; i < child_count(); ++i) {
216     views::View* child = child_at(i);
217     if (!child->visible())
218       continue;
219     int height = child->GetHeightForWidth(child_area.width());
220     child->SetBounds(child_area.x(), top, child_area.width(), height);
221     top += height + between_items;
222   }
223 }
224
225 void MessageListView::AddNotificationAt(MessageView* view, int index) {
226   // |index| refers to a position in a subset of valid children. |real_index|
227   // in a list includes the invalid children, so we compute the real index by
228   // walking the list until |index| number of valid children are encountered,
229   // or to the end of the list.
230   int real_index = 0;
231   while (real_index < child_count()) {
232     if (IsValidChild(child_at(real_index))) {
233       --index;
234       if (index < 0)
235         break;
236     }
237     ++real_index;
238   }
239
240   AddChildViewAt(view, real_index);
241   if (GetContentsBounds().IsEmpty())
242     return;
243
244   adding_views_.insert(view);
245   DoUpdateIfPossible();
246 }
247
248 void MessageListView::RemoveNotification(MessageView* view) {
249   DCHECK_EQ(view->parent(), this);
250   if (GetContentsBounds().IsEmpty()) {
251     delete view;
252   } else {
253     if (view->layer()) {
254       deleting_views_.insert(view);
255     } else {
256       if (animator_.get())
257         animator_->StopAnimatingView(view);
258       delete view;
259     }
260     DoUpdateIfPossible();
261   }
262 }
263
264 void MessageListView::UpdateNotification(MessageView* view,
265                                          const Notification& notification) {
266   int index = GetIndexOf(view);
267   DCHECK_LE(0, index);  // GetIndexOf is negative if not a child.
268
269   if (animator_.get())
270     animator_->StopAnimatingView(view);
271   if (deleting_views_.find(view) != deleting_views_.end())
272     deleting_views_.erase(view);
273   if (deleted_when_done_.find(view) != deleted_when_done_.end())
274     deleted_when_done_.erase(view);
275   view->UpdateWithNotification(notification);
276   DoUpdateIfPossible();
277 }
278
279 gfx::Size MessageListView::GetPreferredSize() const {
280   int width = 0;
281   for (int i = 0; i < child_count(); i++) {
282     const views::View* child = child_at(i);
283     if (IsValidChild(child))
284       width = std::max(width, child->GetPreferredSize().width());
285   }
286
287   return gfx::Size(width + GetInsets().width(),
288                    GetHeightForWidth(width + GetInsets().width()));
289 }
290
291 int MessageListView::GetHeightForWidth(int width) const {
292   if (fixed_height_ > 0)
293     return fixed_height_;
294
295   width -= GetInsets().width();
296   int height = 0;
297   int padding = 0;
298   for (int i = 0; i < child_count(); ++i) {
299     const views::View* child = child_at(i);
300     if (!IsValidChild(child))
301       continue;
302     height += child->GetHeightForWidth(width) + padding;
303     padding = kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
304   }
305
306   return height + GetInsets().height();
307 }
308
309 void MessageListView::PaintChildren(gfx::Canvas* canvas,
310                                     const views::CullSet& cull_set) {
311   // Paint in the inversed order. Otherwise upper notification may be
312   // hidden by the lower one.
313   for (int i = child_count() - 1; i >= 0; --i) {
314     if (!child_at(i)->layer())
315       child_at(i)->Paint(canvas, cull_set);
316   }
317 }
318
319 void MessageListView::ReorderChildLayers(ui::Layer* parent_layer) {
320   // Reorder children to stack the last child layer at the top. Otherwise
321   // upper notification may be hidden by the lower one.
322   for (int i = 0; i < child_count(); ++i) {
323     if (child_at(i)->layer())
324       parent_layer->StackAtBottom(child_at(i)->layer());
325   }
326 }
327
328 void MessageListView::SetRepositionTarget(const gfx::Rect& target) {
329   reposition_top_ = target.y();
330   fixed_height_ = GetHeightForWidth(width());
331 }
332
333 void MessageListView::ResetRepositionSession() {
334   // Don't call DoUpdateIfPossible(), but let Layout() do the task without
335   // animation. Reset will cause the change of the bubble size itself, and
336   // animation from the old location will look weird.
337   if (reposition_top_ >= 0 && animator_.get()) {
338     has_deferred_task_ = false;
339     // cancel cause OnBoundsAnimatorDone which deletes |deleted_when_done_|.
340     animator_->Cancel();
341     STLDeleteContainerPointers(deleting_views_.begin(), deleting_views_.end());
342     deleting_views_.clear();
343     adding_views_.clear();
344     animator_.reset();
345   }
346
347   reposition_top_ = -1;
348   fixed_height_ = 0;
349 }
350
351 void MessageListView::ClearAllNotifications(
352     const gfx::Rect& visible_scroll_rect) {
353   for (int i = 0; i < child_count(); ++i) {
354     views::View* child = child_at(i);
355     if (!child->visible())
356       continue;
357     if (gfx::IntersectRects(child->bounds(), visible_scroll_rect).IsEmpty())
358       continue;
359     clearing_all_views_.push_back(child);
360   }
361   DoUpdateIfPossible();
362 }
363
364 void MessageListView::OnBoundsAnimatorProgressed(
365     views::BoundsAnimator* animator) {
366   DCHECK_EQ(animator_.get(), animator);
367   for (std::set<views::View*>::iterator iter = deleted_when_done_.begin();
368        iter != deleted_when_done_.end(); ++iter) {
369     const gfx::SlideAnimation* animation = animator->GetAnimationForView(*iter);
370     if (animation)
371       (*iter)->layer()->SetOpacity(animation->CurrentValueBetween(1.0, 0.0));
372   }
373 }
374
375 void MessageListView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) {
376   STLDeleteContainerPointers(
377       deleted_when_done_.begin(), deleted_when_done_.end());
378   deleted_when_done_.clear();
379
380   if (clear_all_started_) {
381     clear_all_started_ = false;
382     message_center_view()->OnAllNotificationsCleared();
383   }
384
385   if (has_deferred_task_) {
386     has_deferred_task_ = false;
387     DoUpdateIfPossible();
388   }
389
390   if (GetWidget())
391     GetWidget()->SynthesizeMouseMoveEvent();
392 }
393
394 bool MessageListView::IsValidChild(const views::View* child) const {
395   return child->visible() &&
396       deleting_views_.find(const_cast<views::View*>(child)) ==
397           deleting_views_.end() &&
398       deleted_when_done_.find(const_cast<views::View*>(child)) ==
399           deleted_when_done_.end();
400 }
401
402 void MessageListView::DoUpdateIfPossible() {
403   gfx::Rect child_area = GetContentsBounds();
404   if (child_area.IsEmpty())
405     return;
406
407   if (animator_.get() && animator_->IsAnimating()) {
408     has_deferred_task_ = true;
409     return;
410   }
411
412   if (!animator_.get()) {
413     animator_.reset(new views::BoundsAnimator(this));
414     animator_->AddObserver(this);
415   }
416
417   if (!clearing_all_views_.empty()) {
418     AnimateClearingOneNotification();
419     return;
420   }
421
422   if (top_down_ ||
423       CommandLine::ForCurrentProcess()->HasSwitch(
424           switches::kEnableMessageCenterAlwaysScrollUpUponNotificationRemoval))
425     AnimateNotificationsBelowTarget();
426   else
427     AnimateNotificationsAboveTarget();
428
429   adding_views_.clear();
430   deleting_views_.clear();
431 }
432
433 void MessageListView::AnimateNotificationsBelowTarget() {
434   int last_index = -1;
435   for (int i = 0; i < child_count(); ++i) {
436     views::View* child = child_at(i);
437     if (!IsValidChild(child)) {
438       AnimateChild(child, child->y(), child->height());
439     } else if (reposition_top_ < 0 || child->y() > reposition_top_) {
440       // Find first notification below target (or all notifications if no
441       // target).
442       last_index = i;
443       break;
444     }
445   }
446   if (last_index > 0) {
447     int between_items =
448         kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
449     int top = (reposition_top_ > 0) ? reposition_top_ : GetInsets().top();
450
451     for (int i = last_index; i < child_count(); ++i) {
452       // Animate notifications below target upwards.
453       views::View* child = child_at(i);
454       if (AnimateChild(child, top, child->height()))
455         top += child->height() + between_items;
456     }
457   }
458 }
459
460 void MessageListView::AnimateNotificationsAboveTarget() {
461   int last_index = -1;
462   for (int i = child_count() - 1; i >= 0; --i) {
463     views::View* child = child_at(i);
464     if (!IsValidChild(child)) {
465       AnimateChild(child, child->y(), child->height());
466     } else if (reposition_top_ < 0 || child->y() < reposition_top_) {
467       // Find first notification above target (or all notifications if no
468       // target).
469       last_index = i;
470       break;
471     }
472   }
473   if (last_index >= 0) {
474     int between_items =
475         kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
476     int bottom = (reposition_top_ > 0)
477                      ? reposition_top_ + child_at(last_index)->height()
478                      : GetHeightForWidth(width()) - GetInsets().bottom();
479     for (int i = last_index; i >= 0; --i) {
480       // Animate notifications above target downwards.
481       views::View* child = child_at(i);
482       if (AnimateChild(child, bottom - child->height(), child->height()))
483         bottom -= child->height() + between_items;
484     }
485   }
486 }
487
488 bool MessageListView::AnimateChild(views::View* child, int top, int height) {
489   gfx::Rect child_area = GetContentsBounds();
490   if (adding_views_.find(child) != adding_views_.end()) {
491     child->SetBounds(child_area.right(), top, child_area.width(), height);
492     animator_->AnimateViewTo(
493         child, gfx::Rect(child_area.x(), top, child_area.width(), height));
494   } else if (deleting_views_.find(child) != deleting_views_.end()) {
495     DCHECK(child->layer());
496     // No moves, but animate to fade-out.
497     animator_->AnimateViewTo(child, child->bounds());
498     deleted_when_done_.insert(child);
499     return false;
500   } else {
501     gfx::Rect target(child_area.x(), top, child_area.width(), height);
502     if (child->bounds().origin() != target.origin())
503       animator_->AnimateViewTo(child, target);
504     else
505       child->SetBoundsRect(target);
506   }
507   return true;
508 }
509
510 void MessageListView::AnimateClearingOneNotification() {
511   DCHECK(!clearing_all_views_.empty());
512
513   clear_all_started_ = true;
514
515   views::View* child = clearing_all_views_.front();
516   clearing_all_views_.pop_front();
517
518   // Slide from left to right.
519   gfx::Rect new_bounds = child->bounds();
520   new_bounds.set_x(new_bounds.right() + kMarginBetweenItems);
521   animator_->AnimateViewTo(child, new_bounds);
522
523   // Schedule to start sliding out next notification after a short delay.
524   if (!clearing_all_views_.empty()) {
525     base::MessageLoop::current()->PostDelayedTask(
526         FROM_HERE,
527         base::Bind(&MessageListView::AnimateClearingOneNotification,
528                    weak_ptr_factory_.GetWeakPtr()),
529         base::TimeDelta::FromMilliseconds(
530             kAnimateClearingNextNotificationDelayMS));
531   }
532 }
533
534 // MessageCenterView ///////////////////////////////////////////////////////////
535
536 MessageCenterView::MessageCenterView(MessageCenter* message_center,
537                                      MessageCenterTray* tray,
538                                      int max_height,
539                                      bool initially_settings_visible,
540                                      bool top_down,
541                                      const base::string16& title)
542     : message_center_(message_center),
543       tray_(tray),
544       scroller_(NULL),
545       settings_view_(NULL),
546       button_bar_(NULL),
547       top_down_(top_down),
548       settings_visible_(initially_settings_visible),
549       source_view_(NULL),
550       source_height_(0),
551       target_view_(NULL),
552       target_height_(0),
553       is_closing_(false),
554       context_menu_controller_(new MessageViewContextMenuController(this)) {
555   message_center_->AddObserver(this);
556   set_notify_enter_exit_on_child(true);
557   set_background(views::Background::CreateSolidBackground(
558       kMessageCenterBackgroundColor));
559
560   NotifierSettingsProvider* notifier_settings_provider =
561       message_center_->GetNotifierSettingsProvider();
562   button_bar_ = new MessageCenterButtonBar(this,
563                                            message_center,
564                                            notifier_settings_provider,
565                                            initially_settings_visible,
566                                            title);
567
568   const int button_height = button_bar_->GetPreferredSize().height();
569
570   scroller_ = new views::ScrollView();
571   scroller_->ClipHeightTo(kMinScrollViewHeight, max_height - button_height);
572   scroller_->SetVerticalScrollBar(new views::OverlayScrollBar(false));
573   scroller_->set_background(
574       views::Background::CreateSolidBackground(kMessageCenterBackgroundColor));
575
576   scroller_->SetPaintToLayer(true);
577   scroller_->SetFillsBoundsOpaquely(false);
578   scroller_->layer()->SetMasksToBounds(true);
579
580   empty_list_view_.reset(new NoNotificationMessageView);
581   empty_list_view_->set_owned_by_client();
582   message_list_view_.reset(new MessageListView(this, top_down));
583   message_list_view_->set_owned_by_client();
584
585   // We want to swap the contents of the scroll view between the empty list
586   // view and the message list view, without constructing them afresh each
587   // time.  So, since the scroll view deletes old contents each time you
588   // set the contents (regardless of the |owned_by_client_| setting) we need
589   // an intermediate view for the contents whose children we can swap in and
590   // out.
591   views::View* scroller_contents = new views::View();
592   scroller_contents->SetLayoutManager(new views::FillLayout());
593   scroller_contents->AddChildView(empty_list_view_.get());
594   scroller_->SetContents(scroller_contents);
595
596   settings_view_ = new NotifierSettingsView(notifier_settings_provider);
597
598   if (initially_settings_visible)
599     scroller_->SetVisible(false);
600   else
601     settings_view_->SetVisible(false);
602
603   AddChildView(scroller_);
604   AddChildView(settings_view_);
605   AddChildView(button_bar_);
606 }
607
608 MessageCenterView::~MessageCenterView() {
609   if (!is_closing_)
610     message_center_->RemoveObserver(this);
611 }
612
613 void MessageCenterView::SetNotifications(
614     const NotificationList::Notifications& notifications)  {
615   if (is_closing_)
616     return;
617
618   notification_views_.clear();
619
620   int index = 0;
621   for (NotificationList::Notifications::const_iterator iter =
622            notifications.begin(); iter != notifications.end(); ++iter) {
623     AddNotificationAt(*(*iter), index++);
624
625     message_center_->DisplayedNotification(
626         (*iter)->id(), message_center::DISPLAY_SOURCE_MESSAGE_CENTER);
627     if (notification_views_.size() >= kMaxVisibleMessageCenterNotifications)
628       break;
629   }
630
631   NotificationsChanged();
632   scroller_->RequestFocus();
633 }
634
635 void MessageCenterView::SetSettingsVisible(bool visible) {
636   if (is_closing_)
637     return;
638
639   if (visible == settings_visible_)
640     return;
641
642   settings_visible_ = visible;
643
644   if (visible) {
645     source_view_ = scroller_;
646     target_view_ = settings_view_;
647   } else {
648     source_view_ = settings_view_;
649     target_view_ = scroller_;
650   }
651   source_height_ = source_view_->GetHeightForWidth(width());
652   target_height_ = target_view_->GetHeightForWidth(width());
653
654   gfx::MultiAnimation::Parts parts;
655   // First part: slide resize animation.
656   parts.push_back(gfx::MultiAnimation::Part(
657       (source_height_ == target_height_) ? 0 : kDefaultAnimationDurationMs,
658       gfx::Tween::EASE_OUT));
659   // Second part: fade-out the source_view.
660   if (source_view_->layer()) {
661     parts.push_back(gfx::MultiAnimation::Part(
662         kDefaultAnimationDurationMs, gfx::Tween::LINEAR));
663   } else {
664     parts.push_back(gfx::MultiAnimation::Part());
665   }
666   // Third part: fade-in the target_view.
667   if (target_view_->layer()) {
668     parts.push_back(gfx::MultiAnimation::Part(
669         kDefaultAnimationDurationMs, gfx::Tween::LINEAR));
670     target_view_->layer()->SetOpacity(0);
671     target_view_->SetVisible(true);
672   } else {
673     parts.push_back(gfx::MultiAnimation::Part());
674   }
675   settings_transition_animation_.reset(new gfx::MultiAnimation(
676       parts, base::TimeDelta::FromMicroseconds(1000000 / kDefaultFrameRateHz)));
677   settings_transition_animation_->set_delegate(this);
678   settings_transition_animation_->set_continuous(false);
679   settings_transition_animation_->Start();
680
681   button_bar_->SetBackArrowVisible(visible);
682 }
683
684 void MessageCenterView::ClearAllNotifications() {
685   if (is_closing_)
686     return;
687
688   scroller_->SetEnabled(false);
689   button_bar_->SetAllButtonsEnabled(false);
690   message_list_view_->ClearAllNotifications(scroller_->GetVisibleRect());
691 }
692
693 void MessageCenterView::OnAllNotificationsCleared() {
694   scroller_->SetEnabled(true);
695   button_bar_->SetAllButtonsEnabled(true);
696   button_bar_->SetCloseAllButtonEnabled(false);
697   message_center_->RemoveAllVisibleNotifications(true);  // Action by user.
698 }
699
700 size_t MessageCenterView::NumMessageViewsForTest() const {
701   return message_list_view_->child_count();
702 }
703
704 void MessageCenterView::OnSettingsChanged() {
705   scroller_->InvalidateLayout();
706   PreferredSizeChanged();
707   Layout();
708 }
709
710 void MessageCenterView::SetIsClosing(bool is_closing) {
711   is_closing_ = is_closing;
712   if (is_closing)
713     message_center_->RemoveObserver(this);
714   else
715     message_center_->AddObserver(this);
716 }
717
718 void MessageCenterView::Layout() {
719   if (is_closing_)
720     return;
721
722   int button_height = button_bar_->GetHeightForWidth(width()) +
723                       button_bar_->GetInsets().height();
724   // Skip unnecessary re-layout of contents during the resize animation.
725   bool animating = settings_transition_animation_ &&
726                    settings_transition_animation_->is_animating();
727   if (animating && settings_transition_animation_->current_part_index() == 0) {
728     if (!top_down_) {
729       button_bar_->SetBounds(
730           0, height() - button_height, width(), button_height);
731     }
732     return;
733   }
734
735   scroller_->SetBounds(0,
736                        top_down_ ? button_height : 0,
737                        width(),
738                        height() - button_height);
739   settings_view_->SetBounds(0,
740                             top_down_ ? button_height : 0,
741                             width(),
742                             height() - button_height);
743
744   bool is_scrollable = false;
745   if (scroller_->visible())
746     is_scrollable = scroller_->height() < message_list_view_->height();
747   else
748     is_scrollable = settings_view_->IsScrollable();
749
750   if (!animating) {
751     if (is_scrollable) {
752       // Draw separator line on the top of the button bar if it is on the bottom
753       // or draw it at the bottom if the bar is on the top.
754       button_bar_->SetBorder(views::Border::CreateSolidSidedBorder(
755           top_down_ ? 0 : 1, 0, top_down_ ? 1 : 0, 0, kFooterDelimiterColor));
756     } else {
757       button_bar_->SetBorder(views::Border::CreateEmptyBorder(
758           top_down_ ? 0 : 1, 0, top_down_ ? 1 : 0, 0));
759     }
760     button_bar_->SchedulePaint();
761   }
762   button_bar_->SetBounds(0,
763                          top_down_ ? 0 : height() - button_height,
764                          width(),
765                          button_height);
766   if (GetWidget())
767     GetWidget()->GetRootView()->SchedulePaint();
768 }
769
770 gfx::Size MessageCenterView::GetPreferredSize() const {
771   if (settings_transition_animation_ &&
772       settings_transition_animation_->is_animating()) {
773     int content_width = std::max(source_view_->GetPreferredSize().width(),
774                                  target_view_->GetPreferredSize().width());
775     int width = std::max(content_width,
776                          button_bar_->GetPreferredSize().width());
777     return gfx::Size(width, GetHeightForWidth(width));
778   }
779
780   int width = 0;
781   for (int i = 0; i < child_count(); ++i) {
782     const views::View* child = child_at(0);
783     if (child->visible())
784       width = std::max(width, child->GetPreferredSize().width());
785   }
786   return gfx::Size(width, GetHeightForWidth(width));
787 }
788
789 int MessageCenterView::GetHeightForWidth(int width) const {
790   if (settings_transition_animation_ &&
791       settings_transition_animation_->is_animating()) {
792     int content_height = target_height_;
793     if (settings_transition_animation_->current_part_index() == 0) {
794       content_height = settings_transition_animation_->CurrentValueBetween(
795           source_height_, target_height_);
796     }
797     return button_bar_->GetHeightForWidth(width) + content_height;
798   }
799
800   int content_height = 0;
801   if (scroller_->visible())
802     content_height += scroller_->GetHeightForWidth(width);
803   else
804     content_height += settings_view_->GetHeightForWidth(width);
805   return button_bar_->GetHeightForWidth(width) +
806          button_bar_->GetInsets().height() + content_height;
807 }
808
809 bool MessageCenterView::OnMouseWheel(const ui::MouseWheelEvent& event) {
810   // Do not rely on the default scroll event handler of ScrollView because
811   // the scroll happens only when the focus is on the ScrollView. The
812   // notification center will allow the scrolling even when the focus is on
813   // the buttons.
814   if (scroller_->bounds().Contains(event.location()))
815     return scroller_->OnMouseWheel(event);
816   return views::View::OnMouseWheel(event);
817 }
818
819 void MessageCenterView::OnMouseExited(const ui::MouseEvent& event) {
820   if (is_closing_)
821     return;
822
823   message_list_view_->ResetRepositionSession();
824   NotificationsChanged();
825 }
826
827 void MessageCenterView::OnNotificationAdded(const std::string& id) {
828   int index = 0;
829   const NotificationList::Notifications& notifications =
830       message_center_->GetVisibleNotifications();
831   for (NotificationList::Notifications::const_iterator iter =
832            notifications.begin(); iter != notifications.end();
833        ++iter, ++index) {
834     if ((*iter)->id() == id) {
835       AddNotificationAt(*(*iter), index);
836       break;
837     }
838     if (notification_views_.size() >= kMaxVisibleMessageCenterNotifications)
839       break;
840   }
841   NotificationsChanged();
842 }
843
844 void MessageCenterView::OnNotificationRemoved(const std::string& id,
845                                               bool by_user) {
846   NotificationViewsMap::iterator view_iter = notification_views_.find(id);
847   if (view_iter == notification_views_.end())
848     return;
849   NotificationView* view = view_iter->second;
850   int index = message_list_view_->GetIndexOf(view);
851   DCHECK_LE(0, index);
852   if (by_user) {
853     message_list_view_->SetRepositionTarget(view->bounds());
854     // Moves the keyboard focus to the next notification if the removed
855     // notification is focused so that the user can dismiss notifications
856     // without re-focusing by tab key.
857     if (view->IsCloseButtonFocused() ||
858         view == GetFocusManager()->GetFocusedView()) {
859       views::View* next_focused_view = NULL;
860       if (message_list_view_->child_count() > index + 1)
861         next_focused_view = message_list_view_->child_at(index + 1);
862       else if (index > 0)
863         next_focused_view = message_list_view_->child_at(index - 1);
864
865       if (next_focused_view) {
866         if (view->IsCloseButtonFocused())
867           // Safe cast since all views in MessageListView are MessageViews.
868           static_cast<MessageView*>(
869               next_focused_view)->RequestFocusOnCloseButton();
870         else
871           next_focused_view->RequestFocus();
872       }
873     }
874   }
875   message_list_view_->RemoveNotification(view);
876   notification_views_.erase(view_iter);
877   NotificationsChanged();
878 }
879
880 void MessageCenterView::OnNotificationUpdated(const std::string& id) {
881   NotificationViewsMap::const_iterator view_iter = notification_views_.find(id);
882   if (view_iter == notification_views_.end())
883     return;
884   NotificationView* view = view_iter->second;
885   // TODO(dimich): add MessageCenter::GetVisibleNotificationById(id)
886   const NotificationList::Notifications& notifications =
887       message_center_->GetVisibleNotifications();
888   for (NotificationList::Notifications::const_iterator iter =
889            notifications.begin(); iter != notifications.end(); ++iter) {
890     if ((*iter)->id() == id) {
891       int old_width = view->width();
892       int old_height = view->GetHeightForWidth(old_width);
893       message_list_view_->UpdateNotification(view, **iter);
894       if (view->GetHeightForWidth(old_width) != old_height)
895         NotificationsChanged();
896       break;
897     }
898   }
899 }
900
901 void MessageCenterView::ClickOnNotification(
902     const std::string& notification_id) {
903   message_center_->ClickOnNotification(notification_id);
904 }
905
906 void MessageCenterView::RemoveNotification(const std::string& notification_id,
907                                            bool by_user) {
908   message_center_->RemoveNotification(notification_id, by_user);
909 }
910
911 scoped_ptr<ui::MenuModel> MessageCenterView::CreateMenuModel(
912     const NotifierId& notifier_id,
913     const base::string16& display_source) {
914   return tray_->CreateNotificationMenuModel(notifier_id, display_source);
915 }
916
917 bool MessageCenterView::HasClickedListener(const std::string& notification_id) {
918   return message_center_->HasClickedListener(notification_id);
919 }
920
921 void MessageCenterView::ClickOnNotificationButton(
922     const std::string& notification_id,
923     int button_index) {
924   message_center_->ClickOnNotificationButton(notification_id, button_index);
925 }
926
927 void MessageCenterView::AnimationEnded(const gfx::Animation* animation) {
928   DCHECK_EQ(animation, settings_transition_animation_.get());
929
930   Visibility visibility = target_view_ == settings_view_
931                               ? VISIBILITY_SETTINGS
932                               : VISIBILITY_MESSAGE_CENTER;
933   message_center_->SetVisibility(visibility);
934
935   source_view_->SetVisible(false);
936   target_view_->SetVisible(true);
937   if (source_view_->layer())
938     source_view_->layer()->SetOpacity(1.0);
939   if (target_view_->layer())
940     target_view_->layer()->SetOpacity(1.0);
941   settings_transition_animation_.reset();
942   PreferredSizeChanged();
943   Layout();
944 }
945
946 void MessageCenterView::AnimationProgressed(const gfx::Animation* animation) {
947   DCHECK_EQ(animation, settings_transition_animation_.get());
948   PreferredSizeChanged();
949   if (settings_transition_animation_->current_part_index() == 1 &&
950       source_view_->layer()) {
951     source_view_->layer()->SetOpacity(
952         1.0 - settings_transition_animation_->GetCurrentValue());
953     SchedulePaint();
954   } else if (settings_transition_animation_->current_part_index() == 2 &&
955              target_view_->layer()) {
956     target_view_->layer()->SetOpacity(
957         settings_transition_animation_->GetCurrentValue());
958     SchedulePaint();
959   }
960 }
961
962 void MessageCenterView::AnimationCanceled(const gfx::Animation* animation) {
963   DCHECK_EQ(animation, settings_transition_animation_.get());
964   AnimationEnded(animation);
965 }
966
967 void MessageCenterView::AddNotificationAt(const Notification& notification,
968                                           int index) {
969   NotificationView* view =
970       NotificationView::Create(this, notification, false);  // Not top-level.
971   view->set_context_menu_controller(context_menu_controller_.get());
972   notification_views_[notification.id()] = view;
973   view->set_scroller(scroller_);
974   message_list_view_->AddNotificationAt(view, index);
975 }
976
977 void MessageCenterView::NotificationsChanged() {
978   bool no_message_views = notification_views_.empty();
979
980   // When the child view is removed from the hierarchy, its focus is cleared.
981   // In this case we want to save which view has focus so that the user can
982   // continue to interact with notifications in the order they were expecting.
983   views::FocusManager* focus_manager = scroller_->GetFocusManager();
984   View* focused_view = NULL;
985   // |focus_manager| can be NULL in tests.
986   if (focus_manager)
987     focused_view = focus_manager->GetFocusedView();
988
989   // All the children of this view are owned by |this|.
990   scroller_->contents()->RemoveAllChildViews(/*delete_children=*/false);
991   scroller_->contents()->AddChildView(
992       no_message_views ? empty_list_view_.get() : message_list_view_.get());
993
994   button_bar_->SetCloseAllButtonEnabled(!no_message_views);
995   scroller_->SetFocusable(!no_message_views);
996
997   if (focus_manager && focused_view)
998     focus_manager->SetFocusedView(focused_view);
999
1000   scroller_->InvalidateLayout();
1001   PreferredSizeChanged();
1002   Layout();
1003 }
1004
1005 void MessageCenterView::SetNotificationViewForTest(MessageView* view) {
1006   message_list_view_->AddNotificationAt(view, 0);
1007 }
1008
1009 }  // namespace message_center