Upstream version 6.35.121.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/memory/weak_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/stl_util.h"
13 #include "grit/ui_resources.h"
14 #include "grit/ui_strings.h"
15 #include "ui/base/l10n/l10n_util.h"
16 #include "ui/base/resource/resource_bundle.h"
17 #include "ui/gfx/animation/multi_animation.h"
18 #include "ui/gfx/animation/slide_animation.h"
19 #include "ui/gfx/canvas.h"
20 #include "ui/gfx/insets.h"
21 #include "ui/gfx/rect.h"
22 #include "ui/gfx/size.h"
23 #include "ui/message_center/message_center.h"
24 #include "ui/message_center/message_center_style.h"
25 #include "ui/message_center/message_center_tray.h"
26 #include "ui/message_center/message_center_types.h"
27 #include "ui/message_center/message_center_util.h"
28 #include "ui/message_center/views/message_center_button_bar.h"
29 #include "ui/message_center/views/message_view.h"
30 #include "ui/message_center/views/message_view_context_menu_controller.h"
31 #include "ui/message_center/views/notification_view.h"
32 #include "ui/message_center/views/notifier_settings_view.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   virtual ~NoNotificationMessageView();
63
64   // Overridden from views::View.
65   virtual gfx::Size GetPreferredSize() OVERRIDE;
66   virtual int GetHeightForWidth(int width) OVERRIDE;
67   virtual 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() {
92   return gfx::Size(kMinScrollViewHeight, label_->GetPreferredSize().width());
93 }
94
95 int NoNotificationMessageView::GetHeightForWidth(int width) {
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   virtual ~MessageListView();
114
115   void AddNotificationAt(MessageView* view, int i);
116   void RemoveNotification(MessageView* view);
117   void UpdateNotification(MessageView* view, MessageView* new_view);
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   virtual void Layout() OVERRIDE;
125   virtual gfx::Size GetPreferredSize() OVERRIDE;
126   virtual int GetHeightForWidth(int width) OVERRIDE;
127   virtual void PaintChildren(gfx::Canvas* canvas) OVERRIDE;
128   virtual void ReorderChildLayers(ui::Layer* parent_layer) OVERRIDE;
129
130   // Overridden from views::BoundsAnimatorObserver.
131   virtual void OnBoundsAnimatorProgressed(
132       views::BoundsAnimator* animator) OVERRIDE;
133   virtual void OnBoundsAnimatorDone(views::BoundsAnimator* animator) OVERRIDE;
134
135  private:
136   bool IsValidChild(views::View* child);
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->set_spread_blank_space(true);
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                                          MessageView* new_view) {
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   gfx::Rect old_bounds = view->bounds();
272   if (deleting_views_.find(view) != deleting_views_.end())
273     deleting_views_.erase(view);
274   if (deleted_when_done_.find(view) != deleted_when_done_.end())
275     deleted_when_done_.erase(view);
276   delete view;
277   AddChildViewAt(new_view, index);
278   new_view->SetBounds(old_bounds.x(),
279                       old_bounds.y(),
280                       old_bounds.width(),
281                       new_view->GetHeightForWidth(old_bounds.width()));
282   DoUpdateIfPossible();
283 }
284
285 gfx::Size MessageListView::GetPreferredSize() {
286   int width = 0;
287   for (int i = 0; i < child_count(); i++) {
288     views::View* child = child_at(i);
289     if (IsValidChild(child))
290       width = std::max(width, child->GetPreferredSize().width());
291   }
292
293   return gfx::Size(width + GetInsets().width(),
294                    GetHeightForWidth(width + GetInsets().width()));
295 }
296
297 int MessageListView::GetHeightForWidth(int width) {
298   if (fixed_height_ > 0)
299     return fixed_height_;
300
301   width -= GetInsets().width();
302   int height = 0;
303   int padding = 0;
304   for (int i = 0; i < child_count(); ++i) {
305     views::View* child = child_at(i);
306     if (!IsValidChild(child))
307       continue;
308     height += child->GetHeightForWidth(width) + padding;
309     padding = kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
310   }
311
312   return height + GetInsets().height();
313 }
314
315 void MessageListView::PaintChildren(gfx::Canvas* canvas) {
316   // Paint in the inversed order. Otherwise upper notification may be
317   // hidden by the lower one.
318   for (int i = child_count() - 1; i >= 0; --i) {
319     if (!child_at(i)->layer())
320       child_at(i)->Paint(canvas);
321   }
322 }
323
324 void MessageListView::ReorderChildLayers(ui::Layer* parent_layer) {
325   // Reorder children to stack the last child layer at the top. Otherwise
326   // upper notification may be hidden by the lower one.
327   for (int i = 0; i < child_count(); ++i) {
328     if (child_at(i)->layer())
329       parent_layer->StackAtBottom(child_at(i)->layer());
330   }
331 }
332
333 void MessageListView::SetRepositionTarget(const gfx::Rect& target) {
334   reposition_top_ = target.y();
335   fixed_height_ = GetHeightForWidth(width());
336 }
337
338 void MessageListView::ResetRepositionSession() {
339   // Don't call DoUpdateIfPossible(), but let Layout() do the task without
340   // animation. Reset will cause the change of the bubble size itself, and
341   // animation from the old location will look weird.
342   if (reposition_top_ >= 0 && animator_.get()) {
343     has_deferred_task_ = false;
344     // cancel cause OnBoundsAnimatorDone which deletes |deleted_when_done_|.
345     animator_->Cancel();
346     STLDeleteContainerPointers(deleting_views_.begin(), deleting_views_.end());
347     deleting_views_.clear();
348     adding_views_.clear();
349     animator_.reset();
350   }
351
352   reposition_top_ = -1;
353   fixed_height_ = 0;
354 }
355
356 void MessageListView::ClearAllNotifications(
357     const gfx::Rect& visible_scroll_rect) {
358   for (int i = 0; i < child_count(); ++i) {
359     views::View* child = child_at(i);
360     if (!child->visible())
361       continue;
362     if (gfx::IntersectRects(child->bounds(), visible_scroll_rect).IsEmpty())
363       continue;
364     clearing_all_views_.push_back(child);
365   }
366   DoUpdateIfPossible();
367 }
368
369 void MessageListView::OnBoundsAnimatorProgressed(
370     views::BoundsAnimator* animator) {
371   DCHECK_EQ(animator_.get(), animator);
372   for (std::set<views::View*>::iterator iter = deleted_when_done_.begin();
373        iter != deleted_when_done_.end(); ++iter) {
374     const gfx::SlideAnimation* animation = animator->GetAnimationForView(*iter);
375     if (animation)
376       (*iter)->layer()->SetOpacity(animation->CurrentValueBetween(1.0, 0.0));
377   }
378 }
379
380 void MessageListView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) {
381   STLDeleteContainerPointers(
382       deleted_when_done_.begin(), deleted_when_done_.end());
383   deleted_when_done_.clear();
384
385   if (clear_all_started_) {
386     clear_all_started_ = false;
387     message_center_view()->OnAllNotificationsCleared();
388   }
389
390   if (has_deferred_task_) {
391     has_deferred_task_ = false;
392     DoUpdateIfPossible();
393   }
394
395   if (GetWidget())
396     GetWidget()->SynthesizeMouseMoveEvent();
397 }
398
399 bool MessageListView::IsValidChild(views::View* child) {
400   return child->visible() &&
401          deleting_views_.find(child) == deleting_views_.end() &&
402          deleted_when_done_.find(child) == deleted_when_done_.end();
403 }
404
405 void MessageListView::DoUpdateIfPossible() {
406   gfx::Rect child_area = GetContentsBounds();
407   if (child_area.IsEmpty())
408     return;
409
410   if (animator_.get() && animator_->IsAnimating()) {
411     has_deferred_task_ = true;
412     return;
413   }
414
415   if (!animator_.get()) {
416     animator_.reset(new views::BoundsAnimator(this));
417     animator_->AddObserver(this);
418   }
419
420   if (!clearing_all_views_.empty()) {
421     AnimateClearingOneNotification();
422     return;
423   }
424
425   if (top_down_)
426     AnimateNotificationsBelowTarget();
427   else
428     AnimateNotificationsAboveTarget();
429
430   adding_views_.clear();
431   deleting_views_.clear();
432 }
433
434 void MessageListView::AnimateNotificationsBelowTarget() {
435   int last_index = -1;
436   for (int i = 0; i < child_count(); ++i) {
437     views::View* child = child_at(i);
438     if (!IsValidChild(child)) {
439       AnimateChild(child, child->y(), child->height());
440     } else if (reposition_top_ < 0 || child->y() > reposition_top_) {
441       // Find first notification below target (or all notifications if no
442       // target).
443       last_index = i;
444       break;
445     }
446   }
447   if (last_index > 0) {
448     int between_items =
449         kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
450     int top = (reposition_top_ > 0) ? reposition_top_ : GetInsets().top();
451
452     for (int i = last_index; i < child_count(); ++i) {
453       // Animate notifications below target upwards.
454       views::View* child = child_at(i);
455       if (AnimateChild(child, top, child->height()))
456         top += child->height() + between_items;
457     }
458   }
459 }
460
461 void MessageListView::AnimateNotificationsAboveTarget() {
462   int last_index = -1;
463   for (int i = child_count() - 1; i >= 0; --i) {
464     views::View* child = child_at(i);
465     if (!IsValidChild(child)) {
466       AnimateChild(child, child->y(), child->height());
467     } else if (reposition_top_ < 0 || child->y() < reposition_top_) {
468       // Find first notification above target (or all notifications if no
469       // target).
470       last_index = i;
471       break;
472     }
473   }
474   if (last_index >= 0) {
475     int between_items =
476         kMarginBetweenItems - MessageView::GetShadowInsets().bottom();
477     int bottom = (reposition_top_ > 0)
478                      ? reposition_top_ + child_at(last_index)->height()
479                      : GetHeightForWidth(width()) - GetInsets().bottom();
480     for (int i = last_index; i >= 0; --i) {
481       // Animate notifications above target downwards.
482       views::View* child = child_at(i);
483       if (AnimateChild(child, bottom - child->height(), child->height()))
484         bottom -= child->height() + between_items;
485     }
486   }
487 }
488
489 bool MessageListView::AnimateChild(views::View* child, int top, int height) {
490   gfx::Rect child_area = GetContentsBounds();
491   if (adding_views_.find(child) != adding_views_.end()) {
492     child->SetBounds(child_area.right(), top, child_area.width(), height);
493     animator_->AnimateViewTo(
494         child, gfx::Rect(child_area.x(), top, child_area.width(), height));
495   } else if (deleting_views_.find(child) != deleting_views_.end()) {
496     DCHECK(child->layer());
497     // No moves, but animate to fade-out.
498     animator_->AnimateViewTo(child, child->bounds());
499     deleted_when_done_.insert(child);
500     return false;
501   } else {
502     gfx::Rect target(child_area.x(), top, child_area.width(), height);
503     if (child->bounds().origin() != target.origin())
504       animator_->AnimateViewTo(child, target);
505     else
506       child->SetBoundsRect(target);
507   }
508   return true;
509 }
510
511 void MessageListView::AnimateClearingOneNotification() {
512   DCHECK(!clearing_all_views_.empty());
513
514   clear_all_started_ = true;
515
516   views::View* child = clearing_all_views_.front();
517   clearing_all_views_.pop_front();
518
519   // Slide from left to right.
520   gfx::Rect new_bounds = child->bounds();
521   new_bounds.set_x(new_bounds.right() + kMarginBetweenItems);
522   animator_->AnimateViewTo(child, new_bounds);
523
524   // Schedule to start sliding out next notification after a short delay.
525   if (!clearing_all_views_.empty()) {
526     base::MessageLoop::current()->PostDelayedTask(
527         FROM_HERE,
528         base::Bind(&MessageListView::AnimateClearingOneNotification,
529                    weak_ptr_factory_.GetWeakPtr()),
530         base::TimeDelta::FromMilliseconds(
531             kAnimateClearingNextNotificationDelayMS));
532   }
533 }
534
535 // MessageCenterView ///////////////////////////////////////////////////////////
536
537 MessageCenterView::MessageCenterView(MessageCenter* message_center,
538                                      MessageCenterTray* tray,
539                                      int max_height,
540                                      bool initially_settings_visible,
541                                      bool top_down)
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
567   const int button_height = button_bar_->GetPreferredSize().height();
568
569   scroller_ = new views::ScrollView();
570   scroller_->ClipHeightTo(kMinScrollViewHeight, max_height - button_height);
571   scroller_->SetVerticalScrollBar(new views::OverlayScrollBar(false));
572   scroller_->set_background(
573       views::Background::CreateSolidBackground(kMessageCenterBackgroundColor));
574
575   scroller_->SetPaintToLayer(true);
576   scroller_->SetFillsBoundsOpaquely(false);
577   scroller_->layer()->SetMasksToBounds(true);
578
579   empty_list_view_.reset(new NoNotificationMessageView);
580   empty_list_view_->set_owned_by_client();
581   message_list_view_.reset(new MessageListView(this, top_down));
582   message_list_view_->set_owned_by_client();
583
584   // We want to swap the contents of the scroll view between the empty list
585   // view and the message list view, without constructing them afresh each
586   // time.  So, since the scroll view deletes old contents each time you
587   // set the contents (regardless of the |owned_by_client_| setting) we need
588   // an intermediate view for the contents whose children we can swap in and
589   // out.
590   views::View* scroller_contents = new views::View();
591   scroller_contents->SetLayoutManager(new views::FillLayout());
592   scroller_contents->AddChildView(empty_list_view_.get());
593   scroller_->SetContents(scroller_contents);
594
595   settings_view_ = new NotifierSettingsView(notifier_settings_provider);
596
597   if (initially_settings_visible)
598     scroller_->SetVisible(false);
599   else
600     settings_view_->SetVisible(false);
601
602   AddChildView(scroller_);
603   AddChildView(settings_view_);
604   AddChildView(button_bar_);
605 }
606
607 MessageCenterView::~MessageCenterView() {
608   if (!is_closing_)
609     message_center_->RemoveObserver(this);
610 }
611
612 void MessageCenterView::SetNotifications(
613     const NotificationList::Notifications& notifications)  {
614   if (is_closing_)
615     return;
616
617   notification_views_.clear();
618
619   int index = 0;
620   for (NotificationList::Notifications::const_iterator iter =
621            notifications.begin(); iter != notifications.end(); ++iter) {
622     AddNotificationAt(*(*iter), index++);
623
624     message_center_->DisplayedNotification((*iter)->id());
625     if (notification_views_.size() >= kMaxVisibleMessageCenterNotifications)
626       break;
627   }
628
629   NotificationsChanged();
630   scroller_->RequestFocus();
631 }
632
633 void MessageCenterView::SetSettingsVisible(bool visible) {
634   if (is_closing_)
635     return;
636
637   if (visible == settings_visible_)
638     return;
639
640   settings_visible_ = visible;
641
642   if (visible) {
643     source_view_ = scroller_;
644     target_view_ = settings_view_;
645   } else {
646     source_view_ = settings_view_;
647     target_view_ = scroller_;
648   }
649   source_height_ = source_view_->GetHeightForWidth(width());
650   target_height_ = target_view_->GetHeightForWidth(width());
651
652   gfx::MultiAnimation::Parts parts;
653   // First part: slide resize animation.
654   parts.push_back(gfx::MultiAnimation::Part(
655       (source_height_ == target_height_) ? 0 : kDefaultAnimationDurationMs,
656       gfx::Tween::EASE_OUT));
657   // Second part: fade-out the source_view.
658   if (source_view_->layer()) {
659     parts.push_back(gfx::MultiAnimation::Part(
660         kDefaultAnimationDurationMs, gfx::Tween::LINEAR));
661   } else {
662     parts.push_back(gfx::MultiAnimation::Part());
663   }
664   // Third part: fade-in the target_view.
665   if (target_view_->layer()) {
666     parts.push_back(gfx::MultiAnimation::Part(
667         kDefaultAnimationDurationMs, gfx::Tween::LINEAR));
668     target_view_->layer()->SetOpacity(0);
669     target_view_->SetVisible(true);
670   } else {
671     parts.push_back(gfx::MultiAnimation::Part());
672   }
673   settings_transition_animation_.reset(new gfx::MultiAnimation(
674       parts, base::TimeDelta::FromMicroseconds(1000000 / kDefaultFrameRateHz)));
675   settings_transition_animation_->set_delegate(this);
676   settings_transition_animation_->set_continuous(false);
677   settings_transition_animation_->Start();
678
679   button_bar_->SetBackArrowVisible(visible);
680 }
681
682 void MessageCenterView::ClearAllNotifications() {
683   if (is_closing_)
684     return;
685
686   scroller_->SetEnabled(false);
687   button_bar_->SetAllButtonsEnabled(false);
688   message_list_view_->ClearAllNotifications(scroller_->GetVisibleRect());
689 }
690
691 void MessageCenterView::OnAllNotificationsCleared() {
692   scroller_->SetEnabled(true);
693   button_bar_->SetAllButtonsEnabled(true);
694   button_bar_->SetCloseAllButtonEnabled(false);
695   message_center_->RemoveAllVisibleNotifications(true);  // Action by user.
696 }
697
698 size_t MessageCenterView::NumMessageViewsForTest() const {
699   return message_list_view_->child_count();
700 }
701
702 void MessageCenterView::OnSettingsChanged() {
703   scroller_->InvalidateLayout();
704   PreferredSizeChanged();
705   Layout();
706 }
707
708 void MessageCenterView::SetIsClosing(bool is_closing) {
709   is_closing_ = is_closing;
710   if (is_closing)
711     message_center_->RemoveObserver(this);
712   else
713     message_center_->AddObserver(this);
714 }
715
716 void MessageCenterView::Layout() {
717   if (is_closing_)
718     return;
719
720   int button_height = button_bar_->GetHeightForWidth(width()) +
721                       button_bar_->GetInsets().height();
722   // Skip unnecessary re-layout of contents during the resize animation.
723   bool animating = settings_transition_animation_ &&
724                    settings_transition_animation_->is_animating();
725   if (animating && settings_transition_animation_->current_part_index() == 0) {
726     if (!top_down_) {
727       button_bar_->SetBounds(
728           0, height() - button_height, width(), button_height);
729     }
730     return;
731   }
732
733   scroller_->SetBounds(0,
734                        top_down_ ? button_height : 0,
735                        width(),
736                        height() - button_height);
737   settings_view_->SetBounds(0,
738                             top_down_ ? button_height : 0,
739                             width(),
740                             height() - button_height);
741
742   bool is_scrollable = false;
743   if (scroller_->visible())
744     is_scrollable = scroller_->height() < message_list_view_->height();
745   else
746     is_scrollable = settings_view_->IsScrollable();
747
748   if (!animating) {
749     if (is_scrollable) {
750       // Draw separator line on the top of the button bar if it is on the bottom
751       // or draw it at the bottom if the bar is on the top.
752       button_bar_->SetBorder(views::Border::CreateSolidSidedBorder(
753           top_down_ ? 0 : 1, 0, top_down_ ? 1 : 0, 0, kFooterDelimiterColor));
754     } else {
755       button_bar_->SetBorder(views::Border::CreateEmptyBorder(
756           top_down_ ? 0 : 1, 0, top_down_ ? 1 : 0, 0));
757     }
758     button_bar_->SchedulePaint();
759   }
760   button_bar_->SetBounds(0,
761                          top_down_ ? 0 : height() - button_height,
762                          width(),
763                          button_height);
764   if (GetWidget())
765     GetWidget()->GetRootView()->SchedulePaint();
766 }
767
768 gfx::Size MessageCenterView::GetPreferredSize() {
769   if (settings_transition_animation_ &&
770       settings_transition_animation_->is_animating()) {
771     int content_width = std::max(source_view_->GetPreferredSize().width(),
772                                  target_view_->GetPreferredSize().width());
773     int width = std::max(content_width,
774                          button_bar_->GetPreferredSize().width());
775     return gfx::Size(width, GetHeightForWidth(width));
776   }
777
778   int width = 0;
779   for (int i = 0; i < child_count(); ++i) {
780     views::View* child = child_at(0);
781     if (child->visible())
782       width = std::max(width, child->GetPreferredSize().width());
783   }
784   return gfx::Size(width, GetHeightForWidth(width));
785 }
786
787 int MessageCenterView::GetHeightForWidth(int width) {
788   if (settings_transition_animation_ &&
789       settings_transition_animation_->is_animating()) {
790     int content_height = target_height_;
791     if (settings_transition_animation_->current_part_index() == 0) {
792       content_height = settings_transition_animation_->CurrentValueBetween(
793           source_height_, target_height_);
794     }
795     return button_bar_->GetHeightForWidth(width) + content_height;
796   }
797
798   int content_height = 0;
799   if (scroller_->visible())
800     content_height += scroller_->GetHeightForWidth(width);
801   else
802     content_height += settings_view_->GetHeightForWidth(width);
803   return button_bar_->GetHeightForWidth(width) +
804          button_bar_->GetInsets().height() + content_height;
805 }
806
807 bool MessageCenterView::OnMouseWheel(const ui::MouseWheelEvent& event) {
808   // Do not rely on the default scroll event handler of ScrollView because
809   // the scroll happens only when the focus is on the ScrollView. The
810   // notification center will allow the scrolling even when the focus is on
811   // the buttons.
812   if (scroller_->bounds().Contains(event.location()))
813     return scroller_->OnMouseWheel(event);
814   return views::View::OnMouseWheel(event);
815 }
816
817 void MessageCenterView::OnMouseExited(const ui::MouseEvent& event) {
818   if (is_closing_)
819     return;
820
821   message_list_view_->ResetRepositionSession();
822   NotificationsChanged();
823 }
824
825 void MessageCenterView::OnNotificationAdded(const std::string& id) {
826   int index = 0;
827   const NotificationList::Notifications& notifications =
828       message_center_->GetVisibleNotifications();
829   for (NotificationList::Notifications::const_iterator iter =
830            notifications.begin(); iter != notifications.end();
831        ++iter, ++index) {
832     if ((*iter)->id() == id) {
833       AddNotificationAt(*(*iter), index);
834       break;
835     }
836     if (notification_views_.size() >= kMaxVisibleMessageCenterNotifications)
837       break;
838   }
839   NotificationsChanged();
840 }
841
842 void MessageCenterView::OnNotificationRemoved(const std::string& id,
843                                               bool by_user) {
844   NotificationViewsMap::iterator view_iter = notification_views_.find(id);
845   if (view_iter == notification_views_.end())
846     return;
847   NotificationView* view = view_iter->second;
848   int index = message_list_view_->GetIndexOf(view);
849   DCHECK_LE(0, index);
850   if (by_user) {
851     message_list_view_->SetRepositionTarget(view->bounds());
852     // Moves the keyboard focus to the next notification if the removed
853     // notification is focused so that the user can dismiss notifications
854     // without re-focusing by tab key.
855     if (view->IsCloseButtonFocused() ||
856         view == GetFocusManager()->GetFocusedView()) {
857       views::View* next_focused_view = NULL;
858       if (message_list_view_->child_count() > index + 1)
859         next_focused_view = message_list_view_->child_at(index + 1);
860       else if (index > 0)
861         next_focused_view = message_list_view_->child_at(index - 1);
862
863       if (next_focused_view) {
864         if (view->IsCloseButtonFocused())
865           // Safe cast since all views in MessageListView are MessageViews.
866           static_cast<MessageView*>(
867               next_focused_view)->RequestFocusOnCloseButton();
868         else
869           next_focused_view->RequestFocus();
870       }
871     }
872   }
873   message_list_view_->RemoveNotification(view);
874   notification_views_.erase(view_iter);
875   NotificationsChanged();
876 }
877
878 void MessageCenterView::OnNotificationUpdated(const std::string& id) {
879   NotificationViewsMap::const_iterator view_iter = notification_views_.find(id);
880   if (view_iter == notification_views_.end())
881     return;
882   NotificationView* view = view_iter->second;
883   // TODO(dimich): add MessageCenter::GetVisibleNotificationById(id)
884   const NotificationList::Notifications& notifications =
885       message_center_->GetVisibleNotifications();
886   for (NotificationList::Notifications::const_iterator iter =
887            notifications.begin(); iter != notifications.end(); ++iter) {
888     if ((*iter)->id() == id) {
889       NotificationView* new_view =
890           NotificationView::Create(this,
891                                    *(*iter),
892                                    false); // Not creating a top-level
893                                            // notification.
894       new_view->set_context_menu_controller(context_menu_controller_.get());
895       new_view->set_scroller(scroller_);
896       message_list_view_->UpdateNotification(view, new_view);
897       notification_views_[id] = new_view;
898       NotificationsChanged();
899       break;
900     }
901   }
902 }
903
904 void MessageCenterView::ClickOnNotification(
905     const std::string& notification_id) {
906   message_center_->ClickOnNotification(notification_id);
907 }
908
909 void MessageCenterView::RemoveNotification(const std::string& notification_id,
910                                            bool by_user) {
911   message_center_->RemoveNotification(notification_id, by_user);
912 }
913
914 scoped_ptr<ui::MenuModel> MessageCenterView::CreateMenuModel(
915     const NotifierId& notifier_id,
916     const base::string16& display_source) {
917   return tray_->CreateNotificationMenuModel(notifier_id, display_source);
918 }
919
920 bool MessageCenterView::HasClickedListener(const std::string& notification_id) {
921   return message_center_->HasClickedListener(notification_id);
922 }
923
924 void MessageCenterView::ClickOnNotificationButton(
925     const std::string& notification_id,
926     int button_index) {
927   message_center_->ClickOnNotificationButton(notification_id, button_index);
928 }
929
930 void MessageCenterView::AnimationEnded(const gfx::Animation* animation) {
931   DCHECK_EQ(animation, settings_transition_animation_.get());
932
933   Visibility visibility = target_view_ == settings_view_
934                               ? VISIBILITY_SETTINGS
935                               : VISIBILITY_MESSAGE_CENTER;
936   message_center_->SetVisibility(visibility);
937
938   source_view_->SetVisible(false);
939   target_view_->SetVisible(true);
940   if (source_view_->layer())
941     source_view_->layer()->SetOpacity(1.0);
942   if (target_view_->layer())
943     target_view_->layer()->SetOpacity(1.0);
944   settings_transition_animation_.reset();
945   PreferredSizeChanged();
946   Layout();
947 }
948
949 void MessageCenterView::AnimationProgressed(const gfx::Animation* animation) {
950   DCHECK_EQ(animation, settings_transition_animation_.get());
951   PreferredSizeChanged();
952   if (settings_transition_animation_->current_part_index() == 1 &&
953       source_view_->layer()) {
954     source_view_->layer()->SetOpacity(
955         1.0 - settings_transition_animation_->GetCurrentValue());
956     SchedulePaint();
957   } else if (settings_transition_animation_->current_part_index() == 2 &&
958              target_view_->layer()) {
959     target_view_->layer()->SetOpacity(
960         settings_transition_animation_->GetCurrentValue());
961     SchedulePaint();
962   }
963 }
964
965 void MessageCenterView::AnimationCanceled(const gfx::Animation* animation) {
966   DCHECK_EQ(animation, settings_transition_animation_.get());
967   AnimationEnded(animation);
968 }
969
970 void MessageCenterView::AddNotificationAt(const Notification& notification,
971                                           int index) {
972   NotificationView* view =
973       NotificationView::Create(this, notification, false);  // Not top-level.
974   view->set_context_menu_controller(context_menu_controller_.get());
975   notification_views_[notification.id()] = view;
976   view->set_scroller(scroller_);
977   message_list_view_->AddNotificationAt(view, index);
978 }
979
980 void MessageCenterView::NotificationsChanged() {
981   bool no_message_views = notification_views_.empty();
982
983   // When the child view is removed from the hierarchy, its focus is cleared.
984   // In this case we want to save which view has focus so that the user can
985   // continue to interact with notifications in the order they were expecting.
986   views::FocusManager* focus_manager = scroller_->GetFocusManager();
987   View* focused_view = NULL;
988   // |focus_manager| can be NULL in tests.
989   if (focus_manager)
990     focused_view = focus_manager->GetFocusedView();
991
992   // All the children of this view are owned by |this|.
993   scroller_->contents()->RemoveAllChildViews(/*delete_children=*/false);
994   scroller_->contents()->AddChildView(
995       no_message_views ? empty_list_view_.get() : message_list_view_.get());
996
997   button_bar_->SetCloseAllButtonEnabled(!no_message_views);
998   scroller_->SetFocusable(!no_message_views);
999
1000   if (focus_manager && focused_view)
1001     focus_manager->SetFocusedView(focused_view);
1002
1003   scroller_->InvalidateLayout();
1004   PreferredSizeChanged();
1005   Layout();
1006 }
1007
1008 void MessageCenterView::SetNotificationViewForTest(MessageView* view) {
1009   message_list_view_->AddNotificationAt(view, 0);
1010 }
1011
1012 }  // namespace message_center