hung_renderer_view.cc revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright (c) 2012 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 "chrome/browser/ui/views/hung_renderer_view.h"
6
7#if defined(OS_WIN) && !defined(USE_AURA)
8#include <windows.h>
9#endif
10
11#include "base/i18n/rtl.h"
12#include "base/memory/scoped_vector.h"
13#include "base/strings/utf_string_conversions.h"
14#include "chrome/browser/favicon/favicon_tab_helper.h"
15#include "chrome/browser/platform_util.h"
16#include "chrome/browser/ui/browser_dialogs.h"
17#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
18#include "chrome/browser/ui/tab_contents/tab_contents_iterator.h"
19#include "chrome/common/chrome_constants.h"
20#include "chrome/common/logging_chrome.h"
21#include "content/public/browser/render_process_host.h"
22#include "content/public/browser/render_view_host.h"
23#include "content/public/browser/web_contents.h"
24#include "content/public/browser/web_contents_view.h"
25#include "content/public/common/result_codes.h"
26#include "grit/chromium_strings.h"
27#include "grit/generated_resources.h"
28#include "grit/theme_resources.h"
29#include "ui/base/l10n/l10n_util.h"
30#include "ui/base/resource/resource_bundle.h"
31#include "ui/gfx/canvas.h"
32#include "ui/views/controls/button/label_button.h"
33#include "ui/views/controls/image_view.h"
34#include "ui/views/controls/label.h"
35#include "ui/views/layout/grid_layout.h"
36#include "ui/views/layout/layout_constants.h"
37#include "ui/views/widget/widget.h"
38#include "ui/views/window/client_view.h"
39
40#if defined(USE_AURA)
41#include "ui/aura/window.h"
42#endif
43
44#if defined(OS_WIN)
45#include "ui/base/win/shell.h"
46#endif
47
48using content::WebContents;
49
50// These functions allow certain chrome platforms to override the default hung
51// renderer dialog. For e.g. Chrome on Windows 8 metro
52bool PlatformShowCustomHungRendererDialog(WebContents* contents);
53bool PlatformHideCustomHungRendererDialog(WebContents* contents);
54
55#if !defined(OS_WIN)
56bool PlatformShowCustomHungRendererDialog(WebContents* contents) {
57  return false;
58}
59
60bool PlatformHideCustomHungRendererDialog(WebContents* contents) {
61  return false;
62}
63#endif  // OS_WIN
64
65HungRendererDialogView* HungRendererDialogView::g_instance_ = NULL;
66
67///////////////////////////////////////////////////////////////////////////////
68// HungPagesTableModel, public:
69
70HungPagesTableModel::HungPagesTableModel(Delegate* delegate)
71    : observer_(NULL),
72      delegate_(delegate) {
73}
74
75HungPagesTableModel::~HungPagesTableModel() {
76}
77
78content::RenderProcessHost* HungPagesTableModel::GetRenderProcessHost() {
79  return tab_observers_.empty() ? NULL :
80      tab_observers_[0]->web_contents()->GetRenderProcessHost();
81}
82
83content::RenderViewHost* HungPagesTableModel::GetRenderViewHost() {
84  return tab_observers_.empty() ? NULL :
85      tab_observers_[0]->web_contents()->GetRenderViewHost();
86}
87
88void HungPagesTableModel::InitForWebContents(WebContents* hung_contents) {
89  tab_observers_.clear();
90  if (hung_contents) {
91    // Force hung_contents to be first.
92    if (hung_contents) {
93      tab_observers_.push_back(new WebContentsObserverImpl(this,
94                                                           hung_contents));
95    }
96    for (TabContentsIterator it; !it.done(); it.Next()) {
97      if (*it != hung_contents &&
98          it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost())
99        tab_observers_.push_back(new WebContentsObserverImpl(this, *it));
100    }
101  }
102  // The world is different.
103  if (observer_)
104    observer_->OnModelChanged();
105}
106
107///////////////////////////////////////////////////////////////////////////////
108// HungPagesTableModel, ui::TableModel implementation:
109
110int HungPagesTableModel::RowCount() {
111  return static_cast<int>(tab_observers_.size());
112}
113
114string16 HungPagesTableModel::GetText(int row, int column_id) {
115  DCHECK(row >= 0 && row < RowCount());
116  string16 title = tab_observers_[row]->web_contents()->GetTitle();
117  if (title.empty())
118    title = CoreTabHelper::GetDefaultTitle();
119  // TODO(xji): Consider adding a special case if the title text is a URL,
120  // since those should always have LTR directionality. Please refer to
121  // http://crbug.com/6726 for more information.
122  base::i18n::AdjustStringForLocaleDirection(&title);
123  return title;
124}
125
126gfx::ImageSkia HungPagesTableModel::GetIcon(int row) {
127  DCHECK(row >= 0 && row < RowCount());
128  return FaviconTabHelper::FromWebContents(
129      tab_observers_[row]->web_contents())->GetFavicon().AsImageSkia();
130}
131
132void HungPagesTableModel::SetObserver(ui::TableModelObserver* observer) {
133  observer_ = observer;
134}
135
136void HungPagesTableModel::GetGroupRange(int model_index,
137                                        views::GroupRange* range) {
138  DCHECK(range);
139  range->start = 0;
140  range->length = RowCount();
141}
142
143void HungPagesTableModel::TabDestroyed(WebContentsObserverImpl* tab) {
144  // Clean up tab_observers_ and notify our observer.
145  TabObservers::iterator i = std::find(
146      tab_observers_.begin(), tab_observers_.end(), tab);
147  DCHECK(i != tab_observers_.end());
148  int index = static_cast<int>(i - tab_observers_.begin());
149  tab_observers_.erase(i);
150  if (observer_)
151    observer_->OnItemsRemoved(index, 1);
152
153  // Notify the delegate.
154  delegate_->TabDestroyed();
155  // WARNING: we've likely been deleted.
156}
157
158HungPagesTableModel::WebContentsObserverImpl::WebContentsObserverImpl(
159    HungPagesTableModel* model, WebContents* tab)
160    : content::WebContentsObserver(tab),
161      model_(model) {
162}
163
164void HungPagesTableModel::WebContentsObserverImpl::RenderProcessGone(
165    base::TerminationStatus status) {
166  model_->TabDestroyed(this);
167}
168
169void HungPagesTableModel::WebContentsObserverImpl::WebContentsDestroyed(
170    WebContents* tab) {
171  model_->TabDestroyed(this);
172}
173
174///////////////////////////////////////////////////////////////////////////////
175// HungRendererDialogView
176
177// static
178gfx::ImageSkia* HungRendererDialogView::frozen_icon_ = NULL;
179
180// The distance in pixels from the top of the relevant contents to place the
181// warning window.
182static const int kOverlayContentsOffsetY = 50;
183
184// The dimensions of the hung pages list table view, in pixels.
185static const int kTableViewWidth = 300;
186static const int kTableViewHeight = 100;
187
188// Padding space in pixels between frozen icon to the info label, hung pages
189// list table view and the Kill pages button.
190static const int kCentralColumnPadding =
191    views::kUnrelatedControlLargeHorizontalSpacing;
192
193///////////////////////////////////////////////////////////////////////////////
194// HungRendererDialogView, public:
195
196// static
197HungRendererDialogView* HungRendererDialogView::Create(
198    gfx::NativeView context) {
199  if (!g_instance_) {
200    g_instance_ = new HungRendererDialogView;
201    views::DialogDelegate::CreateDialogWidget(g_instance_, context, NULL);
202  }
203  return g_instance_;
204}
205
206// static
207HungRendererDialogView* HungRendererDialogView::GetInstance() {
208  return g_instance_;
209}
210
211// static
212bool HungRendererDialogView::IsFrameActive(WebContents* contents) {
213  gfx::NativeView frame_view =
214      platform_util::GetTopLevel(contents->GetView()->GetNativeView());
215  return platform_util::IsWindowActive(frame_view);
216}
217
218#if !defined(OS_WIN)
219// static
220void HungRendererDialogView::KillRendererProcess(
221    base::ProcessHandle process_handle) {
222  base::KillProcess(process_handle, content::RESULT_CODE_HUNG, false);
223}
224#endif  // OS_WIN
225
226
227HungRendererDialogView::HungRendererDialogView()
228    : hung_pages_table_(NULL),
229      kill_button_(NULL),
230      initialized_(false) {
231  InitClass();
232}
233
234HungRendererDialogView::~HungRendererDialogView() {
235  hung_pages_table_->SetModel(NULL);
236}
237
238void HungRendererDialogView::ShowForWebContents(WebContents* contents) {
239  DCHECK(contents && GetWidget());
240
241  // Don't show the warning unless the foreground window is the frame, or this
242  // window (but still invisible). If the user has another window or
243  // application selected, activating ourselves is rude.
244  if (!IsFrameActive(contents) &&
245      !platform_util::IsWindowActive(GetWidget()->GetNativeWindow()))
246    return;
247
248  if (!GetWidget()->IsActive()) {
249    gfx::Rect bounds = GetDisplayBounds(contents);
250
251    gfx::NativeView frame_view =
252        platform_util::GetTopLevel(contents->GetView()->GetNativeView());
253
254    views::Widget* insert_after =
255        views::Widget::GetWidgetForNativeView(frame_view);
256    GetWidget()->SetBoundsConstrained(bounds);
257    if (insert_after)
258      GetWidget()->StackAboveWidget(insert_after);
259
260    // We only do this if the window isn't active (i.e. hasn't been shown yet,
261    // or is currently shown but deactivated for another WebContents). This is
262    // because this window is a singleton, and it's possible another active
263    // renderer may hang while this one is showing, and we don't want to reset
264    // the list of hung pages for a potentially unrelated renderer while this
265    // one is showing.
266    hung_pages_table_model_->InitForWebContents(contents);
267    GetWidget()->Show();
268  }
269}
270
271void HungRendererDialogView::EndForWebContents(WebContents* contents) {
272  DCHECK(contents);
273  if (hung_pages_table_model_->RowCount() == 0 ||
274      hung_pages_table_model_->GetRenderProcessHost() ==
275      contents->GetRenderProcessHost()) {
276    GetWidget()->Close();
277    // Close is async, make sure we drop our references to the tab immediately
278    // (it may be going away).
279    hung_pages_table_model_->InitForWebContents(NULL);
280  }
281}
282
283///////////////////////////////////////////////////////////////////////////////
284// HungRendererDialogView, views::DialogDelegate implementation:
285
286string16 HungRendererDialogView::GetWindowTitle() const {
287  return l10n_util::GetStringUTF16(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE);
288}
289
290void HungRendererDialogView::WindowClosing() {
291  // We are going to be deleted soon, so make sure our instance is destroyed.
292  g_instance_ = NULL;
293}
294
295int HungRendererDialogView::GetDialogButtons() const {
296  // We specifically don't want a CANCEL button here because that code path is
297  // also called when the window is closed by the user clicking the X button in
298  // the window's titlebar, and also if we call Window::Close. Rather, we want
299  // the OK button to wait for responsiveness (and close the dialog) and our
300  // additional button (which we create) to kill the process (which will result
301  // in the dialog being destroyed).
302  return ui::DIALOG_BUTTON_OK;
303}
304
305string16 HungRendererDialogView::GetDialogButtonLabel(
306    ui::DialogButton button) const {
307  if (button == ui::DIALOG_BUTTON_OK)
308    return l10n_util::GetStringUTF16(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT);
309  return views::DialogDelegateView::GetDialogButtonLabel(button);
310}
311
312views::View* HungRendererDialogView::CreateExtraView() {
313  DCHECK(!kill_button_);
314  kill_button_ = new views::LabelButton(this,
315      l10n_util::GetStringUTF16(IDS_BROWSER_HANGMONITOR_RENDERER_END));
316  kill_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
317  return kill_button_;
318}
319
320bool HungRendererDialogView::Accept(bool window_closing) {
321  // Don't do anything if we're being called only because the dialog is being
322  // destroyed and we don't supply a Cancel function...
323  if (window_closing)
324    return true;
325
326  // Start waiting again for responsiveness.
327  if (hung_pages_table_model_->GetRenderViewHost())
328    hung_pages_table_model_->GetRenderViewHost()->RestartHangMonitorTimeout();
329  return true;
330}
331
332
333bool HungRendererDialogView::UseNewStyleForThisDialog() const {
334#if defined(OS_WIN)
335  // Use the old dialog style without Aero glass, otherwise the dialog will be
336  // visually constrained to browser window bounds. See http://crbug.com/323278
337  return ui::win::IsAeroGlassEnabled();
338#endif
339  return views::DialogDelegateView::UseNewStyleForThisDialog();
340}
341
342///////////////////////////////////////////////////////////////////////////////
343// HungRendererDialogView, views::ButtonListener implementation:
344
345void HungRendererDialogView::ButtonPressed(
346    views::Button* sender, const ui::Event& event) {
347  if (sender == kill_button_ &&
348      hung_pages_table_model_->GetRenderProcessHost()) {
349
350    base::ProcessHandle process_handle =
351        hung_pages_table_model_->GetRenderProcessHost()->GetHandle();
352
353    KillRendererProcess(process_handle);
354  }
355}
356
357///////////////////////////////////////////////////////////////////////////////
358// HungRendererDialogView, HungPagesTableModel::Delegate overrides:
359
360void HungRendererDialogView::TabDestroyed() {
361  GetWidget()->Close();
362}
363
364///////////////////////////////////////////////////////////////////////////////
365// HungRendererDialogView, views::View overrides:
366
367void HungRendererDialogView::ViewHierarchyChanged(
368    const ViewHierarchyChangedDetails& details) {
369  if (!initialized_ && details.is_add && details.child == this && GetWidget())
370    Init();
371}
372
373///////////////////////////////////////////////////////////////////////////////
374// HungRendererDialogView, private:
375
376void HungRendererDialogView::Init() {
377  views::ImageView* frozen_icon_view = new views::ImageView;
378  frozen_icon_view->SetImage(frozen_icon_);
379
380  views::Label* info_label = new views::Label(
381      l10n_util::GetStringUTF16(IDS_BROWSER_HANGMONITOR_RENDERER));
382  info_label->SetMultiLine(true);
383  info_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
384
385  hung_pages_table_model_.reset(new HungPagesTableModel(this));
386  std::vector<ui::TableColumn> columns;
387  columns.push_back(ui::TableColumn());
388  hung_pages_table_ = new views::TableView(
389      hung_pages_table_model_.get(), columns, views::ICON_AND_TEXT, true);
390  hung_pages_table_->SetGrouper(hung_pages_table_model_.get());
391
392  using views::GridLayout;
393  using views::ColumnSet;
394
395  GridLayout* layout = GridLayout::CreatePanel(this);
396  SetLayoutManager(layout);
397
398  const int double_column_set_id = 0;
399  ColumnSet* column_set = layout->AddColumnSet(double_column_set_id);
400  column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0,
401                        GridLayout::FIXED, frozen_icon_->width(), 0);
402  column_set->AddPaddingColumn(0, kCentralColumnPadding);
403  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
404                        GridLayout::USE_PREF, 0, 0);
405
406  layout->StartRow(0, double_column_set_id);
407  layout->AddView(frozen_icon_view, 1, 3);
408  // Add the label with a preferred width of 1, this way it doesn't effect the
409  // overall preferred size of the dialog.
410  layout->AddView(
411      info_label, 1, 1, GridLayout::FILL, GridLayout::LEADING, 1, 0);
412
413  layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
414
415  layout->StartRow(0, double_column_set_id);
416  layout->SkipColumns(1);
417  layout->AddView(hung_pages_table_->CreateParentIfNecessary(), 1, 1,
418                  views::GridLayout::FILL,
419                  views::GridLayout::FILL, kTableViewWidth, kTableViewHeight);
420
421  initialized_ = true;
422}
423
424gfx::Rect HungRendererDialogView::GetDisplayBounds(
425    WebContents* contents) {
426#if defined(USE_AURA)
427  gfx::Rect contents_bounds(
428      contents->GetView()->GetNativeView()->GetBoundsInRootWindow());
429#elif defined(OS_WIN)
430  HWND contents_hwnd = contents->GetView()->GetNativeView();
431  RECT contents_bounds_rect;
432  GetWindowRect(contents_hwnd, &contents_bounds_rect);
433  gfx::Rect contents_bounds(contents_bounds_rect);
434#endif
435  gfx::Rect window_bounds = GetWidget()->GetWindowBoundsInScreen();
436
437  int window_x = contents_bounds.x() +
438      (contents_bounds.width() - window_bounds.width()) / 2;
439  int window_y = contents_bounds.y() + kOverlayContentsOffsetY;
440  return gfx::Rect(window_x, window_y, window_bounds.width(),
441                   window_bounds.height());
442}
443
444// static
445void HungRendererDialogView::InitClass() {
446  static bool initialized = false;
447  if (!initialized) {
448    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
449    frozen_icon_ = rb.GetImageSkiaNamed(IDR_FROZEN_TAB_ICON);
450    initialized = true;
451  }
452}
453
454namespace chrome {
455
456void ShowHungRendererDialog(WebContents* contents) {
457  if (!logging::DialogsAreSuppressed() &&
458      !PlatformShowCustomHungRendererDialog(contents)) {
459    gfx::NativeView toplevel_view =
460        platform_util::GetTopLevel(contents->GetView()->GetNativeView());
461#if defined(USE_AURA)
462    // Don't show the dialog if there is no root window for the renderer,
463    // because it's invisible to the user (happens when the renderer is for
464    // prerendering for example).
465    if (!toplevel_view->GetRootWindow())
466      return;
467#endif
468    HungRendererDialogView* view = HungRendererDialogView::Create(
469        toplevel_view);
470    view->ShowForWebContents(contents);
471  }
472}
473
474void HideHungRendererDialog(WebContents* contents) {
475  if (!logging::DialogsAreSuppressed() &&
476      !PlatformHideCustomHungRendererDialog(contents) &&
477      HungRendererDialogView::GetInstance())
478    HungRendererDialogView::GetInstance()->EndForWebContents(contents);
479}
480
481}  // namespace chrome
482